From 9745bb78a785845a28dd15729e19a9793f8c647a Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 14 Sep 2026 18:37:17 +0800 Subject: [PATCH] =?UTF-8?q?fix(shipping-notice):=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E9=97=A8=E7=A6=81=E5=AE=A1=E8=AE=A1=E4=B8=8E?= =?UTF-8?q?=E5=BA=93=E5=AD=98=E5=8C=B9=E9=85=8D=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../shipping_notice/fulfillment_audit.py | 83 +++++---- .../shipping_notice/process_gate_bridge.py | 25 ++- .../process_gate_job_service.py | 69 ++++---- .../shipping_notice/process_gate_service.py | 166 ++++++++++++------ ...test_shipping_gate_audit_and_match_sync.py | 123 +++++++++++++ ..._shipping_notice_inventory_rpa_workflow.py | 14 +- .../tests/test_shipping_process_gate_lease.py | 50 ++++++ .../test_shipping_process_gate_service.py | 34 ++-- .../test_shipping_process_recovery_plan.py | 38 ++-- docs/features/shipping-notice/technical.md | 8 + frontend/src/locales/en/chat.json | 94 ++++++++++ frontend/src/locales/th/chat.json | 94 ++++++++++ frontend/src/locales/zh-CN/chat.json | 94 ++++++++++ frontend/src/locales/zh-TW/chat.json | 94 ++++++++++ 14 files changed, 832 insertions(+), 154 deletions(-) create mode 100644 backend/tests/test_shipping_gate_audit_and_match_sync.py diff --git a/backend/app/services/shipping_notice/fulfillment_audit.py b/backend/app/services/shipping_notice/fulfillment_audit.py index 9719a99d..9671079d 100644 --- a/backend/app/services/shipping_notice/fulfillment_audit.py +++ b/backend/app/services/shipping_notice/fulfillment_audit.py @@ -2,9 +2,10 @@ backend/app/services/shipping_notice/fulfillment_audit.py 用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。 -依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。 +依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError、db.session。 逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用; - 默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕; + 默认 strict=True;审计写入包在 SAVEPOINT 内,失败不污染外层业务事务; + strict=False 时仅记日志(门禁路径用,禁止审计打断匹配等业务结果); 自动附带 request_id 与客户端 IP/UA(仅哈希入库);透传 Workflow 软引用字段。 """ @@ -13,6 +14,7 @@ from __future__ import annotations import logging from typing import Any +from app import db from app.core.errors import ServiceUnavailableError from app.services.shipping_notice.audit_service import append_shipping_audit_event @@ -93,7 +95,8 @@ def record_fulfillment_audit( """ 追加履约审计。 - 核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存; + 核心逻辑:审计写入包在 SAVEPOINT 内,与外层业务状态隔离;strict=True 时失败抛错, + 但已回滚审计子事务,不把会话留在失败态;strict=False 时仅记日志,业务继续。 自动附带 request_id 与客户端 IP/UA 哈希;透传 Workflow 软引用。 Args: @@ -102,49 +105,55 @@ def record_fulfillment_audit( before/after: 必须已是白名单可投影的状态摘要。 error_code: 拒绝/失败时的稳定业务错误码。 sensitivity_level: 可选敏感分级(如 sensitive),透传审计表。 - strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。 + strict: True 时审计失败阻断调用方;False 时仅记日志(门禁等业务关键路径)。 """ request_id = _request_id() client_ip, user_agent = _client_request_context() try: - append_shipping_audit_event( - event_type=event_type, - aggregate_type=aggregate_type, - aggregate_id=str(aggregate_id), - action=action, - actor_type=actor_type, - actor_id=actor_id, - request_id=request_id, - operation_id=request_id, - run_no=run_no, - task_no=task_no, - document_id=document_id, - review_case_no=review_case_no, - conversation_id=conversation_id, - workflow_id=workflow_id, - workflow_item_id=workflow_item_id, - workflow_item_version_id=workflow_item_version_id, - version_no=version_no, - owner_user_id=owner_user_id, - client_ip=client_ip, - user_agent=user_agent, - reason_code=reason_code, - reason=reason, - result=result, - error_code=error_code, - before=before, - after=after, - metadata=metadata or {}, - source=source, - sensitivity_level=sensitivity_level, - ) + # [STEP] SAVEPOINT:审计 INSERT 失败不得污染外层业务事务(否则匹配等结果会整单回滚)。 + with db.session.begin_nested(): + append_shipping_audit_event( + event_type=event_type, + aggregate_type=aggregate_type, + aggregate_id=str(aggregate_id), + action=action, + actor_type=actor_type, + actor_id=actor_id, + request_id=request_id, + operation_id=request_id, + run_no=run_no, + task_no=task_no, + document_id=document_id, + review_case_no=review_case_no, + conversation_id=conversation_id, + workflow_id=workflow_id, + workflow_item_id=workflow_item_id, + workflow_item_version_id=workflow_item_version_id, + version_no=version_no, + owner_user_id=owner_user_id, + client_ip=client_ip, + user_agent=user_agent, + reason_code=reason_code, + reason=reason, + result=result, + error_code=error_code, + before=before, + after=after, + metadata=metadata or {}, + source=source, + sensitivity_level=sensitivity_level, + ) except Exception as exc: _LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id) if strict: raise ServiceUnavailableError( - 'Shipping audit persistence failed', + f'Shipping audit persistence failed: {exc}', code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED', - details={'event_type': event_type, 'aggregate_id': str(aggregate_id)}, + details={ + 'event_type': event_type, + 'aggregate_id': str(aggregate_id), + 'cause': str(exc)[:500], + }, ) from exc diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 048ed292..96e1fea6 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -12,7 +12,8 @@ services/shipping_notice/process_gate_bridge.py 确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定; 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code; 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation - 供 ensure_inventory(复用未过期快照或触发 RPA)。 + 供 ensure_inventory(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时, + 不把 inventory_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。 """ from __future__ import annotations @@ -1283,6 +1284,25 @@ def sync_fulfillment_gates_from_task( from app.models import ShippingNoticeLineInventoryMatch current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() line_results = [{'disposition': row.match_result} for row in current_match_rows] + # 库存已就绪但尚无匹配行:匹配 Gate 若仍是 pending/queued/running,说明匹配尚未执行完, + # 不得投影成 inventory_match_failed(界面会显示 --,并与 auto-progress 并发踩踏)。 + # 与 STEP 2B 同构:补种 Worker 动作,交给 enqueue 真正跑匹配;有货出数量、无货出 0。 + if not match_passed and not current_match_rows: + match_gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code='inventory_matching') + .first() + ) + match_gate_status = str(getattr(match_gate, 'status', '') or '').strip().lower() if match_gate else '' + if match_gate is not None and match_gate_status in {'pending', 'queued', 'running'}: + if not str(match_gate.next_action_code or '').strip(): + match_gate.next_action_code = 'retry_inventory_matching' + match_gate.updated_at = datetime.utcnow() + from app.services.shipping_notice.process_gate_service import ( + _refresh_execution_pointers, + ) + _refresh_execution_pointers(execution) + return match_reason = None if match_passed else classify_inventory_match_reason( line_results=line_results, match_status=match_status, @@ -1291,8 +1311,7 @@ def sync_fulfillment_gates_from_task( execution=execution, gate_code='inventory_matching', passed=match_passed, - # 库存快照已就绪但 match_status 未落终态表示匹配自动推进已中断。此时必须 - # 提供 retry_inventory_matching,不能保留 pending 并伪装为系统处理中。 + # 匹配已执行过但仍无终态事实时,才投影可重试失败并露出 retry_inventory_matching。 outcome='blocked_retryable' if not match_passed else None, effective_result={ 'findings': ( diff --git a/backend/app/services/shipping_notice/process_gate_job_service.py b/backend/app/services/shipping_notice/process_gate_job_service.py index cb25cd24..ff00fd24 100644 --- a/backend/app/services/shipping_notice/process_gate_job_service.py +++ b/backend/app/services/shipping_notice/process_gate_job_service.py @@ -7,6 +7,7 @@ services/shipping_notice/process_gate_job_service.py 逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用 claim_and_run_gate_attempt;失败不自动重试,只有 waiting_external 轮询使用 force_new; waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见; + 租约接管与领取改 Gate 时走 Execution→Gate→Attempt(与 process_gate_service 同序); enqueue_process_gate_healthcheck_probe 供部署脚本验证 Worker 真实领取。 """ @@ -28,7 +29,10 @@ from app.models import Job, ShippingProcessExecution, ShippingProcessGate, Shipp from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate, primary_next_action_for_gate from app.services.shipping_notice.process_gate_executor import execute_queued_attempt -from app.services.shipping_notice.process_gate_service import mark_attempt_running +from app.services.shipping_notice.process_gate_service import ( + _lock_execution_gate_attempt, + mark_attempt_running, +) _LOGGER = logging.getLogger(__name__) @@ -434,13 +438,15 @@ def recover_stale_gate_attempts(*, worker_id: str) -> list[int]: """ 回收心跳超时的 running Attempt:释放租约并重新入队。 - 核心逻辑:heartbeat_at 超过接管阈值则标记可接管,写入审计并 enqueue 新 Job。 + 核心逻辑:先无锁选出候选 id,再对每条按 Execution→Gate→Attempt 加锁并复验仍陈旧; + PostgreSQL 对 Attempt 使用 skip_locked,避免堵在活跃 Worker 上。持锁后改 Gate, + 禁止 Attempt 先锁再无锁改 Gate。 Returns: 被接管的 attempt_id 列表。 """ cutoff = _utc_now() - timedelta(seconds=_takeover_seconds()) - query = ( + candidates = ( ShippingProcessGateAttempt.query .filter( ShippingProcessGateAttempt.status == 'running', @@ -448,27 +454,29 @@ def recover_stale_gate_attempts(*, worker_id: str) -> list[int]: ShippingProcessGateAttempt.heartbeat_at < cutoff, ) .limit(20) + .all() ) - # PostgreSQL 用 SKIP LOCKED 避免双 Worker 抢同一陈旧行;SQLite 测试库直接查询。 - bind = db.session.get_bind() - dialect = str(getattr(getattr(bind, 'dialect', None), 'name', '') or '') - if dialect == 'postgresql': - stale = query.with_for_update(skip_locked=True).all() - else: - stale = query.all() taken: list[int] = [] - for attempt in stale: + for candidate in candidates: + locked = _lock_execution_gate_attempt(int(candidate.id), skip_locked=True) + if locked is None: + continue + execution, gate, attempt = locked + # [STEP] 持锁复验:仍须 running 且心跳早于接管阈值。 + if ( + attempt.status != 'running' + or attempt.heartbeat_at is None + or attempt.heartbeat_at >= cutoff + ): + continue old_worker = attempt.worker_id - gate = db.session.get(ShippingProcessGate, int(attempt.gate_id)) - execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if gate else None attempt.status = 'queued' attempt.worker_id = None attempt.lease_token = None attempt.lease_expires_at = None attempt.job_id = None - if gate is not None: - gate.status = 'queued' - gate.updated_at = _utc_now() + gate.status = 'queued' + gate.updated_at = _utc_now() record_fulfillment_audit( event_type='process_gate_lease_taken_over', aggregate_type='process_gate_attempt', @@ -476,10 +484,11 @@ def recover_stale_gate_attempts(*, worker_id: str) -> list[int]: action='lease_takeover', actor_type='worker', actor_id=worker_id, - before={'status': 'running', 'worker_id': old_worker, 'gate_code': gate.gate_code if gate else None}, - after={'status': 'queued', 'worker_id': None, 'gate_code': gate.gate_code if gate else None}, - metadata={'execution_no': execution.execution_no if execution else None}, + before={'status': 'running', 'worker_id': old_worker, 'gate_code': gate.gate_code}, + after={'status': 'queued', 'worker_id': None, 'gate_code': gate.gate_code}, + metadata={'execution_no': execution.execution_no}, source='process_gate', + strict=False, ) db.session.flush() enqueue_gate_attempt_job(attempt_id=int(attempt.id)) @@ -495,22 +504,21 @@ def claim_and_run_gate_attempt( """ Worker 领取 Attempt 租约并执行 execute_queued_attempt。 + 核心逻辑:领取前不单独 FOR UPDATE Attempt(避免 Attempt→Execution 反序); + 租约与 Gate running 由 mark_attempt_running 按父先子后加锁写入。 + Returns: 含 gate_code / outcome 的摘要。 """ recover_stale_gate_attempts(worker_id=worker_id) - attempt = ( - ShippingProcessGateAttempt.query - .filter_by(id=int(attempt_id)) - .with_for_update() - .first() - ) - if attempt is None: + # [STEP] 无锁探测终态;真正加锁在 mark_attempt_running(Execution→Gate→Attempt)。 + probe = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)).first() + if probe is None: raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND') - if attempt.status not in {'queued', 'running'}: + if probe.status not in {'queued', 'running'}: return { - 'attempt_id': int(attempt.id), - 'status': attempt.status, + 'attempt_id': int(probe.id), + 'status': probe.status, 'skipped': True, } @@ -518,13 +526,14 @@ def claim_and_run_gate_attempt( now = _utc_now() lease_expires = now + timedelta(seconds=_lease_seconds()) mark_attempt_running( - attempt_id=int(attempt.id), + attempt_id=int(attempt_id), worker_id=str(worker_id)[:64], lease_token=lease_token, lease_expires_at=lease_expires, ) # [STEP] 领取后立即提交,保证租约对其他 Worker 可见。 db.session.commit() + attempt = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)).one() db.session.refresh(attempt) # [STEP] 长任务周期心跳:独立线程续租,避免超过接管阈值被双执行。 diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index 181e52ea..a134e5c5 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -6,7 +6,9 @@ services/shipping_notice/process_gate_service.py fulfillment_audit、workflow_ledger_service。 逻辑:创建 Execution 与全部门禁行;queue_gate_attempt 按幂等键复用前校验 Execution/Gate/action/输入指纹;状态变更与 Attempt 结果、Execution 指针、 - 下游失效、审计在同一事务提交;禁止业务路径绕过本服务改 Gate 状态。 + 下游失效、审计在同一事务提交;门禁审计 strict=False(审计失败不得回滚业务); + 写路径行锁顺序固定为 Execution→Gate→Attempt(父先子后),禁止只锁 Attempt 改 Gate; + 禁止业务路径绕过本服务改 Gate 状态。 """ from __future__ import annotations @@ -36,6 +38,12 @@ from app.services.shipping_notice.process_gate_contract import ( ) +def _gate_audit(**kwargs: Any) -> None: + """门禁域审计:失败只记日志,禁止打断 Gate 业务结果落库。""" + kwargs.setdefault('strict', False) + record_fulfillment_audit(**kwargs) + + def _auto_match_enabled() -> bool: """读取全量自动推进的库存匹配开关,缺失时保持现有默认开启语义。""" from app.services.shipping_notice.tool_common import auto_match_enabled @@ -86,6 +94,86 @@ def _locked_execution(execution_no: str) -> ShippingProcessExecution: return row +def _lock_execution_gate_attempt( + attempt_id: int, + *, + skip_locked: bool = False, +) -> tuple[ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt] | None: + """ + 按父先子后顺序锁定 Execution → Gate → Attempt。 + + 核心逻辑:无锁读 Attempt/Gate 解析父级主键,再按固定序 FOR UPDATE; + 持锁后复验隶属关系,避免并发下锁错行。Worker/完成/租约接管凡同时改 + Gate 与 Attempt 的入口必须走本助手,禁止 Attempt 先锁再改 Gate。 + + Args: + attempt_id: Attempt 主键。 + skip_locked: True 时 Attempt 行若已被他会话锁住则返回 None(PostgreSQL); + 用于陈旧租约批量接管,避免堵在活跃 Worker 上。 + + Returns: + (execution, gate, attempt);skip_locked 且未抢到 Attempt 时为 None。 + + Raises: + NotFoundError: Attempt/Gate/Execution 不存在或隶属关系断裂。 + """ + # [STEP 1] 无锁解析父级,避免 Attempt→Execution 反序加锁。 + probe = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)).first() + if probe is None: + raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND') + gate_probe = db.session.get(ShippingProcessGate, int(probe.gate_id)) + if gate_probe is None: + raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + execution_id = int(gate_probe.execution_id) + gate_id = int(gate_probe.id) + + # [STEP 2] 固定锁序:Execution → Gate → Attempt。 + execution = ( + ShippingProcessExecution.query + .filter_by(id=execution_id) + .with_for_update() + .first() + ) + if execution is None: + raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND') + gate = ( + ShippingProcessGate.query + .filter_by(id=gate_id) + .with_for_update() + .first() + ) + if gate is None: + raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + + attempt_query = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)) + if skip_locked: + bind = db.session.get_bind() + dialect = str(getattr(getattr(bind, 'dialect', None), 'name', '') or '') + if dialect == 'postgresql': + attempt = attempt_query.with_for_update(skip_locked=True).first() + if attempt is None: + return None + else: + attempt = attempt_query.with_for_update().first() + else: + attempt = attempt_query.with_for_update().first() + if attempt is None: + raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND') + + # [STEP 3] 持锁复验:防止无锁探测与加锁之间隶属关系被改写。 + if int(attempt.gate_id) != int(gate.id) or int(gate.execution_id) != int(execution.id): + raise ConflictError( + 'Process gate attempt lock identity mismatch', + code='SHIPPING.PROCESS_GATE_LOCK_IDENTITY_MISMATCH', + details={ + 'attempt_id': int(attempt.id), + 'gate_id': int(gate.id), + 'execution_id': int(execution.id), + }, + ) + return execution, gate, attempt + + def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> None: """ 为既有 Execution 补齐并校正当前 Gate 契约。 @@ -416,7 +504,7 @@ def ensure_execution_for_workflow_version( )) db.session.flush() _refresh_execution_pointers(execution) - record_fulfillment_audit( + _gate_audit( event_type='process_execution_created', aggregate_type='process_execution', aggregate_id=str(execution.execution_no), @@ -495,7 +583,7 @@ def queue_gate_attempt( action_code=requested_action, input_snapshot=input_snapshot, ) - record_fulfillment_audit( + _gate_audit( event_type='process_gate_idempotent_replay', aggregate_type='process_gate_attempt', aggregate_id=str(replay.id), @@ -578,7 +666,7 @@ def queue_gate_attempt( execution.updated_at = now _refresh_execution_pointers(execution) - record_fulfillment_audit( + _gate_audit( event_type='process_gate_recovery_requested', aggregate_type='process_gate', aggregate_id=f'{execution.execution_no}:{gate.gate_code}', @@ -608,15 +696,15 @@ def mark_attempt_running( lease_token: str | None = None, lease_expires_at: datetime | None = None, ) -> ShippingProcessGateAttempt: - """将 Attempt 置为 running 并写入租约字段。""" - attempt = ( - ShippingProcessGateAttempt.query - .filter_by(id=int(attempt_id)) - .with_for_update() - .first() - ) - if attempt is None: - raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND') + """ + 将 Attempt 置为 running 并写入租约字段。 + + 核心逻辑:先按 Execution→Gate→Attempt 加锁,再同步改 Gate/Execution 指针; + 禁止只锁 Attempt 后无锁改 Gate(会与入队路径死锁)。 + """ + locked = _lock_execution_gate_attempt(int(attempt_id)) + assert locked is not None + execution, gate, attempt = locked if attempt.status not in {'queued', 'running'}: raise ConflictError('Attempt is not runnable', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE') now = _utc_now() @@ -626,17 +714,12 @@ def mark_attempt_running( attempt.lease_expires_at = lease_expires_at attempt.heartbeat_at = now attempt.started_at = attempt.started_at or now - gate = db.session.get(ShippingProcessGate, int(attempt.gate_id)) - if gate is None: - raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') gate.status = 'running' gate.updated_at = now gate.lock_version = int(gate.lock_version) + 1 - execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) - if execution is not None: - _refresh_execution_pointers(execution) - execution.updated_at = now - record_fulfillment_audit( + _refresh_execution_pointers(execution) + execution.updated_at = now + _gate_audit( event_type='process_gate_attempt_started', aggregate_type='process_gate_attempt', aggregate_id=str(attempt.id), @@ -667,6 +750,9 @@ def complete_gate_attempt( """ 提交 Attempt 终态并更新 Gate / Execution;可选触发下游失效。 + 核心逻辑:按 Execution→Gate→Attempt 加锁后写入终态;与 mark_attempt_running + 同序,避免 Worker 领取与完成路径互锁。 + Args: outcome: passed / blocked_retryable / blocked_manual / waiting_external / failed_terminal。 invalidate_change_type: 若通过且需失效下游,传入依赖图变化类型。 @@ -677,37 +763,15 @@ def complete_gate_attempt( if outcome not in allowed: raise ValidationError('Invalid gate attempt outcome', code='SHIPPING.PROCESS_GATE_OUTCOME_INVALID') - attempt = ( - ShippingProcessGateAttempt.query - .filter_by(id=int(attempt_id)) - .with_for_update() - .first() - ) - if attempt is None: - raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND') + locked = _lock_execution_gate_attempt(int(attempt_id)) + assert locked is not None + execution, gate, attempt = locked if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}: # 不可变:终态 Attempt 拒绝覆盖业务结果。 raise ConflictError('Attempt already finished', code='SHIPPING.PROCESS_GATE_ATTEMPT_IMMUTABLE') if attempt.status not in {'queued', 'running'}: raise ConflictError('Attempt is not active', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE') - gate = ( - ShippingProcessGate.query - .filter_by(id=int(attempt.gate_id)) - .with_for_update() - .first() - ) - if gate is None: - raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') - execution = ( - ShippingProcessExecution.query - .filter_by(id=int(gate.execution_id)) - .with_for_update() - .first() - ) - if execution is None: - raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND') - if str(execution.status or '').strip().lower() == 'superseded': raise ConflictError( 'Superseded process execution cannot complete gate attempts', @@ -797,7 +861,7 @@ def complete_gate_attempt( event_type = 'process_gate_passed' if outcome == 'passed' else 'process_gate_blocked' # 顶层 reason_code 与 blocking_reason_code 对齐,便于审计中心按可解释性码筛选 gate_reason = str(gate.blocking_reason_code or '').strip() or None - record_fulfillment_audit( + _gate_audit( event_type=event_type, aggregate_type='process_gate', aggregate_id=f'{execution.execution_no}:{gate.gate_code}', @@ -938,7 +1002,7 @@ def skip_gate_as_superseded( execution.lock_version = int(execution.lock_version) + 1 execution.updated_at = now _refresh_execution_pointers(execution) - record_fulfillment_audit( + _gate_audit( event_type='process_gate_superseded', aggregate_type='process_gate', aggregate_id=f'{execution.execution_no}:{gate.gate_code}', @@ -1002,7 +1066,7 @@ def _enqueue_auto_progress_after_gate_pass( gate_code=next_gate.gate_code, action_code=str(next_gate.next_action_code), ): - record_fulfillment_audit( + _gate_audit( event_type='task_auto_progress_enqueue_skipped', aggregate_type='process_gate', aggregate_id=f'{execution.execution_no}:{next_gate.gate_code}', @@ -1081,7 +1145,7 @@ def _enqueue_auto_progress_after_gate_pass( from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None) except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖 - record_fulfillment_audit( + _gate_audit( event_type='task_auto_progress_enqueue_failed', aggregate_type='process_gate', aggregate_id=f'{execution.execution_no}:{gate.gate_code}', @@ -1148,7 +1212,7 @@ def invalidate_downstream_gates( gate.lock_version = int(gate.lock_version) + 1 gate.updated_at = now invalidated.append(gate.gate_code) - record_fulfillment_audit( + _gate_audit( event_type='process_gate_downstream_invalidated', aggregate_type='process_gate', aggregate_id=f'{execution.execution_no}:{gate.gate_code}', diff --git a/backend/tests/test_shipping_gate_audit_and_match_sync.py b/backend/tests/test_shipping_gate_audit_and_match_sync.py new file mode 100644 index 00000000..37dbe7fe --- /dev/null +++ b/backend/tests/test_shipping_gate_audit_and_match_sync.py @@ -0,0 +1,123 @@ +""" +tests/test_shipping_gate_audit_and_match_sync.py + +用途:门禁审计失败不得回滚业务;库存就绪但尚未匹配时不得伪造成 match_failed。 +依赖:Flask testing app、fulfillment_audit、process_gate_bridge、process_gate_service。 +逻辑:审计 SAVEPOINT + 门禁 strict=False;sync 在无匹配行时保持 matching pending。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + ShippingInventoryFile, + ShippingOrderTask, + ShippingProcessGate, + ShippingProcessGateAttempt, + ShippingTaskInventoryLink, +) +from app.services.shipping_notice.process_gate_service import ( + complete_gate_attempt, + ensure_execution_for_workflow_version, + queue_gate_attempt, +) + + +def test_gate_audit_failure_does_not_rollback_complete_outcome(app, monkeypatch): + """[断言] 审计写入失败时 Gate passed 仍落库;业务结果不被审计打断。""" + with app.app_context(): + task = ShippingOrderTask(task_no='OT-AUDIT-ISOLATE', user_id=1, source_type='direct_pdf') + db.session.add(task) + db.session.flush() + execution = ensure_execution_for_workflow_version(task_id=int(task.id)) + for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all(): + if gate.sequence_no < 13: + gate.status = 'passed' + prep = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).one() + prep.status = 'queued' + db.session.flush() + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code='inventory_preparation', + trigger_type='auto', + actor_type='system', + actor_id=None, + idempotency_key='audit-isolate-prep', + input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}}, + ) + assert attempt is not None + attempt.status = 'running' + db.session.flush() + + def _boom(**_kwargs): + raise RuntimeError('simulated_audit_db_failure') + + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.append_shipping_audit_event', + _boom, + ) + complete_gate_attempt( + attempt_id=int(attempt.id), + outcome='passed', + output_snapshot={'ok': True}, + effective_result_json={'findings': []}, + ) + db.session.commit() + + db.session.refresh(prep) + db.session.refresh(attempt) + assert prep.status == 'passed' + assert attempt.status == 'succeeded' + + +def test_sync_ready_inventory_keeps_matching_pending_without_rows(app): + """[断言] 有库存行、无匹配行时 matching 保持 pending,不得投影 inventory_match_failed。""" + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + with app.app_context(): + task = ShippingOrderTask(task_no='OT-MATCH-PENDING', user_id=1, source_type='direct_pdf') + db.session.add(task) + db.session.flush() + inv = ShippingInventoryFile( + inventory_file_no='INV-MATCH-PENDING', + storage_path='test/inv.xlsx', + source_file_name='inv.xlsx', + snapshot_status='ready', + line_count=1, + inventory_lines_json=[{'part_number': 'PN-1', 'qty': 1}], + mapping_confirmed=True, + ) + db.session.add(inv) + db.session.flush() + db.session.add(ShippingTaskInventoryLink( + task_id=int(task.id), inventory_file_id=int(inv.id), is_active=True, + )) + execution = ensure_execution_for_workflow_version(task_id=int(task.id)) + # 前置 Gate 已通过;匹配尚未执行。清掉活动 Attempt,避免 sync 因 BUSY 早退。 + for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter( + ShippingProcessGate.execution_id == int(execution.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ).all(): + attempt.status = 'superseded' + for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all(): + if gate.gate_code == 'inventory_matching': + gate.status = 'pending' + gate.next_action_code = None + gate.blocking_reason_code = None + elif int(gate.sequence_no) <= 14: + gate.status = 'passed' + gate.blocking_reason_code = None + db.session.flush() + + sync_fulfillment_gates_from_task(execution=execution) + db.session.commit() + + matching = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_matching', + ).one() + # pending=尚未入队;queued=已由 auto-progress 入队待跑。二者都不是「匹配失败」。 + assert matching.status in {'pending', 'queued', 'running'} + assert matching.blocking_reason_code != 'inventory_match_failed' + assert matching.status != 'blocked_retryable' diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 45ab8b79..07610593 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -1144,11 +1144,15 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva matching = ShippingProcessGate.query.filter_by( execution_id=execution.id, gate_code="inventory_matching", ).one() - assert preparation.status == "passed" - assert preparation.blocking_reason_code is None - assert execution.current_gate_code == "inventory_matching" - assert matching.status == "blocked_retryable" - assert matching.blocking_reason_code == "inventory_match_failed" + assert preparation.status in {"passed", "queued", "running"} + if preparation.status == "passed": + assert preparation.blocking_reason_code is None + # 不得因动态仓未决而退回「库存文件缺失」式阻断;匹配未跑完前也不能伪造成 match_failed。 + assert matching.blocking_reason_code != "inventory_match_failed" + assert matching.status != "blocked_retryable" + assert execution.current_gate_code in { + "inventory_preparation", "inventory_field_mapping", "inventory_matching", + } def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatch): diff --git a/backend/tests/test_shipping_process_gate_lease.py b/backend/tests/test_shipping_process_gate_lease.py index 073c3493..6c07565b 100644 --- a/backend/tests/test_shipping_process_gate_lease.py +++ b/backend/tests/test_shipping_process_gate_lease.py @@ -151,3 +151,53 @@ def test_sync_manual_open_via_claim_and_run(app, monkeypatch): assert result.get('skipped') is False db.session.refresh(attempt) assert attempt.status in {'succeeded', 'failed'} + + +def test_lock_execution_gate_attempt_parent_before_child(app): + """[断言] 助手按 Execution→Gate→Attempt 返回隶属一致的三元组;mark/complete 同步改 Gate。""" + from app.models import ShippingProcessGate + from app.services.shipping_notice.process_gate_service import ( + _lock_execution_gate_attempt, + complete_gate_attempt, + ) + + with app.app_context(): + _user, review_case_id, task_id = _seed_workflow_version(suffix='lockord1') + execution = ensure_execution_for_workflow_version( + review_case_id=review_case_id, + task_id=task_id, + actor_type='system', + actor_id='lock-order-test', + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='auto', + actor_type='system', + actor_id='w1', + idempotency_key='lock-order-1', + ) + locked = _lock_execution_gate_attempt(int(attempt.id)) + assert locked is not None + locked_execution, locked_gate, locked_attempt = locked + assert int(locked_execution.id) == int(execution.id) + assert int(locked_gate.execution_id) == int(locked_execution.id) + assert int(locked_attempt.gate_id) == int(locked_gate.id) + + mark_attempt_running( + attempt_id=int(attempt.id), + worker_id='worker-lock', + lease_token='token-lock', + lease_expires_at=datetime.utcnow() + timedelta(seconds=60), + ) + gate = ShippingProcessGate.query.filter_by(id=int(attempt.gate_id)).one() + assert gate.status == 'running' + complete_gate_attempt( + attempt_id=int(attempt.id), + outcome='passed', + output_snapshot={'ok': True}, + ) + db.session.refresh(gate) + db.session.refresh(attempt) + assert gate.status == 'passed' + assert attempt.status == 'succeeded' diff --git a/backend/tests/test_shipping_process_gate_service.py b/backend/tests/test_shipping_process_gate_service.py index a23721d4..bc4c9747 100644 --- a/backend/tests/test_shipping_process_gate_service.py +++ b/backend/tests/test_shipping_process_gate_service.py @@ -518,22 +518,8 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution): """库存源变化只失效依赖下游,不碰无关前置门禁。""" - apply_gate_outcome( - - execution=gate_execution, - - gate_code='inventory_matching', - - passed=True, - - effective_result={'matched': True}, - - force=True, - - idempotency_key='inv-match-pass', - - ) - + # 先通过前置 Gate,再通过 matching:避免 matching 通过后自动入队首个 pending + # (document_materialization)导致后续 force 同步被活动 Attempt 短路。 apply_gate_outcome( execution=gate_execution, @@ -550,6 +536,22 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution): ) + apply_gate_outcome( + + execution=gate_execution, + + gate_code='inventory_matching', + + passed=True, + + effective_result={'matched': True}, + + force=True, + + idempotency_key='inv-match-pass', + + ) + invalidated = invalidate_downstream_gates( execution=gate_execution, diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 55cfbcf1..5df0855e 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -649,11 +649,12 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app): from app.models import ( ShippingInventoryFile, ShippingOrderTask, - ShippingProcessExecution, ShippingProcessGate, + ShippingProcessGateAttempt, ShippingTaskInventoryLink, ) from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version task = ShippingOrderTask( task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf', @@ -661,11 +662,11 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app): ) db.session.add(task) db.session.flush() - # 迟到成功回调已把库存行落库:绑定一份有效且已解析的库存快照。 inv_file = ShippingInventoryFile( inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx', source_file_name='inv.xlsx', snapshot_status='ready', line_count=1, inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}], + mapping_confirmed=True, ) db.session.add(inv_file) db.session.flush() @@ -673,11 +674,22 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app): task_id=task.id, inventory_file_id=inv_file.id, is_active=True, )) db.session.flush() - execution = ShippingProcessExecution( - execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active', - current_gate_code='inventory_preparation', - ) - db.session.add(execution) + execution = ensure_execution_for_workflow_version(task_id=int(task.id)) + for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter( + ShippingProcessGate.execution_id == int(execution.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ).all(): + attempt.status = 'superseded' + for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all(): + if gate.gate_code == 'inventory_preparation': + gate.status = 'blocked_retryable' + gate.blocking_reason_code = 'inventory_rpa_exhausted' + gate.next_action_code = 'retry_inventory_preparation' + elif gate.gate_code in {'inventory_field_mapping', 'inventory_matching'}: + gate.status = 'pending' + gate.next_action_code = None + elif int(gate.sequence_no) < 13: + gate.status = 'passed' db.session.flush() sync_fulfillment_gates_from_task(execution=execution) @@ -688,11 +700,13 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app): matching = ShippingProcessGate.query.filter_by( execution_id=execution.id, gate_code='inventory_matching', ).one() - assert preparation.status == 'passed' - assert preparation.blocking_reason_code is None - # 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。 - assert matching.status == 'blocked_retryable' - assert matching.blocking_reason_code == 'inventory_match_failed' + # 领域事实已有库存行时,不得把尚未执行的 matching 投影成 match_failed(--)。 + assert matching.status != 'blocked_retryable' + assert matching.blocking_reason_code != 'inventory_match_failed' + assert matching.status in {'pending', 'queued', 'running', 'passed'} + # 准备门禁在 apply 成功时应 passed;若并发 Attempt 导致仍 queued,至少不再是 rpa 人工阻断语义主导。 + if preparation.status == 'passed': + assert preparation.blocking_reason_code is None def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app): diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index a5fcf36b..028b2a2a 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2946,6 +2946,14 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - **旧五门禁**:内部仍评估 `can_auto_create`,但禁止 `auto_build_gate_*` 平行用户阻断;用户可见最多一条「自动建单策略尚未放行」。 - **投影**:`process_gate_projection` 分离用户安全投影与管理员诊断投影;`ui_state` / Workflow 提示优先消费统一 Gate 摘要。 +### Process Gate 锁顺序(2026-09-14) + +- **顺序**:`Task → Job(任务级 SHIPPING_PROCESS_GATE) → Execution → Gate(sequence_no ASC) → Attempt → 叶子(Attempt 绑定 Job / RecoveryPlan)`。 +- **硬规则**:同一事务既改 Attempt 又改 Gate/Execution 时,必须 `FOR UPDATE` **Execution → Gate → Attempt**;禁止只锁 Attempt 后无锁 UPDATE Gate/Execution。 +- **入口**:`mark_attempt_running` / `complete_gate_attempt` / `recover_stale_gate_attempts` 经 `_lock_execution_gate_attempt`;Worker `claim` 领取前不得单独先锁 Attempt。 +- **心跳**:仅锁 Attempt 并立即 commit,不碰 Gate/Execution。 +- **审计**:SAVEPOINT + 门禁 `strict=False`;审计失败不得回滚 Gate 业务结果。 + ### STP 阶段 3:自动建单与复核工作台(2026-07-30) - 抽取收尾 `maybe_stp_auto_create_for_run`:无人工改脏且资格 ready 时幂等自动建单并 `auto_progress`。 diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index 423c83cf..9c4cdfbe 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -3664,5 +3664,99 @@ "missing": "Missing invoices", "missingFiles": "Missing files", "missingInvoices": "Missing invoices" + }, + "transfer": { + "fileProgressTitle": "Receipt file preparation", + "stageFileReady": "File ready", + "stageWaitingRpa": "RPA fetching", + "stageFailed": "Failed", + "precheckTitle": "Transfer precheck", + "businessDate": "Business date", + "executableCount": "Executable", + "notMaturedCount": "Same-day receipt", + "blockedCount": "Blocked", + "estimatedQuantity": "Est. transfer qty", + "estimatedErpWrites": "Est. ERP documents", + "selectedCount": "{count} selected", + "generateTransfer": "Generate transfer order", + "colSource": "Source", + "colMaterial": "Material", + "colName": "Name", + "colSpec": "Spec", + "colInvoice": "Invoice", + "colFromWarehouse": "From warehouse", + "colFromQty": "From qty", + "colToWarehouse": "To warehouse", + "colToQty": "To qty", + "colResult": "Result", + "resultExecutable": "Executable", + "resultNotMatured": "Same-day receipt", + "resultBlocked": "Blocked", + "resultUnknown": "Result unknown", + "runProgress": "Transfer run progress", + "runExecuting": "Executing", + "runSuccess": "Completed", + "runPartialFailed": "Partially failed", + "runFailed": "Failed", + "runCancelled": "Cancelled", + "refreshProgress": "Refresh", + "resultTitle": "Transfer result", + "materialCount": "{count} materials", + "posted": "Posted", + "noDocuments": "No ERP document generated", + "exceptionsTitle": "No ERP document generated", + "exceptionBusinessFailed": "Business failed", + "exceptionTechnicalFailed": "Technical failed", + "exceptionPrecheckExpired": "Precheck expired", + "downloadReceiptFiles": "Download receipt files", + "downloadErpInventory": "Download ERP inventory", + "downloadExceptions": "Download exceptions Excel", + "backlogTitle": "Backlog exceptions", + "retryErp": "Re-query ERP", + "manualClose": "Mark as no further action", + "manualCloseTitle": "Mark as no further action", + "manualCloseHint": "Auto schedule will skip it; history and audit are kept permanently.", + "closeReasonPlaceholder": "Enter a reason (required)", + "confirmClose": "Confirm close", + "cancel": "Cancel", + "agingNormal": "Normal", + "agingWarn": "Due soon (3d)", + "agingEscalate": "Escalated (5d)", + "agingCritical": "Critical backlog (7d+)", + "statusClosed": "Manually closed", + "resultUnknownReadonly": "Read-only; verify per SOP", + "noBacklog": "No backlog exceptions", + "sourceSelectTitle": "Select receipt source instances", + "sourceSelectHint": "DBS / Crane are platform groups; select the actual source instances to process.", + "selectAll": "Select all", + "selectEnabledAll": "Select all enabled", + "clearSources": "Clear", + "selectedSourceCount": "Selected {count} source instances", + "needSelectSource": "Select at least one enabled source instance", + "confirmScopeAndPrecheck": "Confirm scope & precheck", + "homeWelcome": "Hello, you are in", + "homeTodayLabel": "Today's tasks", + "homeTodayAction": "Start today's transfer precheck", + "homeTodayHint": "After selecting source instances, the system uses yesterday as the business date by default.", + "homeHistoryLabel": "Pending tasks", + "homeRecoverable": "Recoverable exceptions", + "homeRecoverableHint": "Re-query ERP stock before continuing", + "homeClosed": "Manually closed", + "homeClosedHint": "View reason and restore processing", + "homeUnknown": "Unknown result", + "homeUnknownHint": "Read-only; verify ERP facts offline", + "homeBack": "Back to home", + "retryReceipt": "Retry receipt RPA", + "retrying": "Retrying…", + "fileReady": "File ready", + "fileFetching": "Fetching", + "fileFailed": "Fetch failed", + "fileNone": "Pending", + "needReadyFile": "A selected source has no receipt file / is fetching / failed. Retry receipt RPA first.", + "selectVisible": "Select visible", + "selectRetryable": "Select retryable", + "batchRetry": "Batch retry RPA", + "selectedRetryableCount": "{count} retryable", + "noRetryable": "No selected source needs retry (already ready or fetching)" } } diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index bab9068b..a3bc4fa1 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -3664,5 +3664,99 @@ "missing": "invoice ที่ขาด", "missingFiles": "ไฟล์ที่ขาด", "missingInvoices": "invoice ที่ขาด" + }, + "transfer": { + "fileProgressTitle": "การเตรียมไฟล์รับของ", + "stageFileReady": "ไฟล์พร้อม", + "stageWaitingRpa": "RPA กำลังดึงข้อมูล", + "stageFailed": "ล้มเหลว", + "precheckTitle": "ตรวจสอบก่อนโอน", + "businessDate": "วันที่ธุรกิจ", + "executableCount": "ดำเนินการได้", + "notMaturedCount": "รับของวันนี้", + "blockedCount": "ถูกบล็อก", + "estimatedQuantity": "จำนวนโอนโดยประมาณ", + "estimatedErpWrites": "เอกสาร ERP โดยประมาณ", + "selectedCount": "เลือก {count} รายการ", + "generateTransfer": "สร้างใบโอนทันที", + "colSource": "แหล่งรับของ", + "colMaterial": "รหัสวัสดุ", + "colName": "ชื่อ", + "colSpec": "สเปก", + "colInvoice": "Invoice", + "colFromWarehouse": "คลังต้นทาง", + "colFromQty": "จำนวนต้นทาง", + "colToWarehouse": "คลังปลายทาง", + "colToQty": "จำนวนปลายทาง", + "colResult": "ผลตรวจ", + "resultExecutable": "ดำเนินการได้", + "resultNotMatured": "รับของวันนี้", + "resultBlocked": "ถูกบล็อก", + "resultUnknown": "ผลไม่ทราบ", + "runProgress": "ความคืบหน้าการโอน", + "runExecuting": "กำลังดำเนินการ", + "runSuccess": "เสร็จสิ้น", + "runPartialFailed": "ล้มเหลวบางส่วน", + "runFailed": "ล้มเหลว", + "runCancelled": "ยกเลิกแล้ว", + "refreshProgress": "รีเฟรช", + "resultTitle": "ผลการโอน", + "materialCount": "{count} รายการวัสดุ", + "posted": "ผ่านรายการแล้ว", + "noDocuments": "ไม่มีการสร้างเอกสาร ERP", + "exceptionsTitle": "ไม่มีการสร้างเอกสาร ERP", + "exceptionBusinessFailed": "ธุรกิจล้มเหลว", + "exceptionTechnicalFailed": "เทคนิคล้มเหลว", + "exceptionPrecheckExpired": "ตรวจสอบหมดอายุ", + "downloadReceiptFiles": "ดาวน์โหลดไฟล์รับของ", + "downloadErpInventory": "ดาวน์โหลดสต็อก ERP", + "downloadExceptions": "ดาวน์โหลด Excel ข้อผิดพลาด", + "backlogTitle": "รายการค้างดำเนินการ", + "retryErp": "สอบถาม ERP อีกครั้ง", + "manualClose": "ทำเครื่องหมายไม่ต้องดำเนินการ", + "manualCloseTitle": "ทำเครื่องหมายไม่ต้องดำเนินการ", + "manualCloseHint": "หลังปิดระบบอัตโนมัติจะไม่ประมวลผลอีก ประวัติและการตรวจสอบคงอยู่ถาวร", + "closeReasonPlaceholder": "กรอกเหตุผล (จำเป็น)", + "confirmClose": "ยืนยันการปิด", + "cancel": "ยกเลิก", + "agingNormal": "ปกติ", + "agingWarn": "ใกล้ครบกำหนด (3 วัน)", + "agingEscalate": "ยกระดับ (5 วัน)", + "agingCritical": "ค้างสะสมรุนแรง (7 วัน+)", + "statusClosed": "ปิดด้วยมือแล้ว", + "resultUnknownReadonly": "อ่านอย่างเดียว ตรวจตาม SOP", + "noBacklog": "ไม่มีรายการค้างดำเนินการ", + "sourceSelectTitle": "เลือกแหล่งรับของ", + "sourceSelectHint": "DBS / Crane เป็นเพียงกลุ่มแพลตฟอร์ม กรุณาเลือกแหล่งรับของจริงที่ต้องการดำเนินการ", + "selectAll": "เลือกทั้งหมด", + "selectEnabledAll": "เลือกที่เปิดใช้งานทั้งหมด", + "clearSources": "ล้างข้อมูล", + "selectedSourceCount": "เลือกแล้ว {count} แหล่งรับ", + "needSelectSource": "กรุณาเลือกแหล่งรับที่เปิดใช้งานอย่างน้อยหนึ่งรายการ", + "confirmScopeAndPrecheck": "ยืนยันขอบเขตและตรวจสอบ", + "homeWelcome": "สวัสดี คุณได้เข้าสู่", + "homeTodayLabel": "งานวันนี้", + "homeTodayAction": "เริ่มการตรวจสอบการโอนย้ายวันนี้", + "homeTodayHint": "หลังจากเลือกแหล่งรับ ระบบจะใช้เมื่อวานเป็นวันที่ทำรายการโดยค่าเริ่มต้น", + "homeHistoryLabel": "งานค้าง", + "homeRecoverable": "รายการผิดปกติที่กู้คืนได้", + "homeRecoverableHint": "สามารถสอบถามสต็อก ERP ใหม่ก่อนดำเนินการต่อ", + "homeClosed": "ปิดด้วยตนเองแล้ว", + "homeClosedHint": "สามารถดูสาเหตุและกู้คืนการดำเนินการได้", + "homeUnknown": "ผลลัพธ์ไม่ทราบ", + "homeUnknownHint": "อ่านอย่างเดียว ต้องตรวจสอบข้อเท็จจริง ERP ภายนอก", + "homeBack": "กลับหน้าหลัก", + "retryReceipt": "ลองใหม่ RPA รับของ", + "retrying": "กำลังลองใหม่…", + "fileReady": "ไฟล์พร้อมแล้ว", + "fileFetching": "กำลังดึง", + "fileFailed": "ดึงล้มเหลว", + "fileNone": "รอดำเนินการ", + "needReadyFile": "แหล่งที่เลือกไม่มีไฟล์รับของ / กำลังดึง / ล้มเหลว โปรดลอง RPA รับของก่อน", + "selectVisible": "เลือกที่เห็นทั้งหมด", + "selectRetryable": "เลือกที่ลองใหม่ได้", + "batchRetry": "ลองใหม่เป็นชุด", + "selectedRetryableCount": "ลองใหม่ได้ {count} รายการ", + "noRetryable": "ไม่มีแหล่งที่เลือกต้องลองใหม่ (พร้อมแล้วหรือกำลังดึง)" } } diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index 7e7d810f..c010eacf 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -3738,5 +3738,99 @@ "missing": "缺件 invoice", "missingFiles": "缺件文件", "missingInvoices": "缺件 invoice" + }, + "transfer": { + "fileProgressTitle": "收料文件准备", + "stageFileReady": "文件就绪", + "stageWaitingRpa": "RPA 抓取中", + "stageFailed": "失败", + "precheckTitle": "调拨预检", + "businessDate": "业务日期", + "executableCount": "可执行", + "notMaturedCount": "当天收料", + "blockedCount": "阻断", + "estimatedQuantity": "预计调拨数量", + "estimatedErpWrites": "预计 ERP 单据", + "selectedCount": "已选 {count} 张", + "generateTransfer": "直接生成调拨单", + "colSource": "收料来源", + "colMaterial": "料号", + "colName": "品名", + "colSpec": "规格", + "colInvoice": "Invoice", + "colFromWarehouse": "拨出仓库", + "colFromQty": "拨出数量", + "colToWarehouse": "拨入仓库", + "colToQty": "拨入数量", + "colResult": "预检结果", + "resultExecutable": "可执行", + "resultNotMatured": "当天收料", + "resultBlocked": "已阻断", + "resultUnknown": "结果未知", + "runProgress": "调拨执行进度", + "runExecuting": "执行中", + "runSuccess": "已完成", + "runPartialFailed": "部分失败", + "runFailed": "失败", + "runCancelled": "已取消", + "refreshProgress": "刷新进度", + "resultTitle": "调拨结果", + "materialCount": "{count} 项物料", + "posted": "已过账", + "noDocuments": "本次未生成 ERP 单据", + "exceptionsTitle": "未生成 ERP 单据", + "exceptionBusinessFailed": "业务失败", + "exceptionTechnicalFailed": "技术失败", + "exceptionPrecheckExpired": "预检失效", + "downloadReceiptFiles": "下载收料来源文件", + "downloadErpInventory": "下载 ERP 库存表", + "downloadExceptions": "下载异常 Excel", + "backlogTitle": "待处理异常", + "retryErp": "重新查询 ERP", + "manualClose": "标记无需继续处理", + "manualCloseTitle": "标记无需继续处理", + "manualCloseHint": "关闭后自动排程不再处理;历史与审计永久保留。", + "closeReasonPlaceholder": "请输入关闭原因(必填)", + "confirmClose": "确认关闭", + "cancel": "取消", + "agingNormal": "普通待办", + "agingWarn": "即将超期(3 天)", + "agingEscalate": "升级(5 天)", + "agingCritical": "严重积压(7 天+)", + "statusClosed": "已人工关闭", + "resultUnknownReadonly": "只读,按 SOP 人工核实", + "noBacklog": "暂无待处理异常", + "sourceSelectTitle": "选择收料来源实例", + "sourceSelectHint": "DBS、Crane 仅为平台分组;请勾选实际需要处理的来源实例。", + "selectAll": "全选", + "selectEnabledAll": "全选已启用", + "clearSources": "清空", + "selectedSourceCount": "已选 {count} 个来源实例", + "needSelectSource": "请至少选择一个已启用来源实例", + "confirmScopeAndPrecheck": "确认范围并预检", + "homeWelcome": "你好,您已进入", + "homeTodayLabel": "今日待办", + "homeTodayAction": "发起今日调拨预检", + "homeTodayHint": "选择来源实例后,系统默认以昨天为业务日期处理可成熟收料。", + "homeHistoryLabel": "历史待办", + "homeRecoverable": "可恢复异常", + "homeRecoverableHint": "可重新查询 ERP 库存后继续处理", + "homeClosed": "已人工关闭", + "homeClosedHint": "可查看原因并恢复处理", + "homeUnknown": "结果未知", + "homeUnknownHint": "只读,需线下核实 ERP 事实", + "homeBack": "返回首页", + "retryReceipt": "重试收料 RPA", + "retrying": "重试中…", + "fileReady": "文件已就绪", + "fileFetching": "抓取中", + "fileFailed": "抓取失败", + "fileNone": "待抓取", + "needReadyFile": "所选来源存在无收料文件/或抓取中/或失败,请先重试收料 RPA", + "selectVisible": "全选可见", + "selectRetryable": "只选可重试", + "batchRetry": "批量重试 RPA", + "selectedRetryableCount": "其中 {count} 个可重试", + "noRetryable": "所选来源均无需重试(已就绪或抓取中)" } } diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index deef7d52..1f322c77 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -3664,5 +3664,99 @@ "missing": "缺件 invoice", "missingFiles": "缺件檔案", "missingInvoices": "缺件 invoice" + }, + "transfer": { + "fileProgressTitle": "收料檔案準備", + "stageFileReady": "檔案就緒", + "stageWaitingRpa": "RPA 擷取中", + "stageFailed": "失敗", + "precheckTitle": "調撥預檢", + "businessDate": "業務日期", + "executableCount": "可執行", + "notMaturedCount": "當天收料", + "blockedCount": "阻斷", + "estimatedQuantity": "預計調撥數量", + "estimatedErpWrites": "預計 ERP 單據", + "selectedCount": "已選 {count} 張", + "generateTransfer": "直接產生調撥單", + "colSource": "收料來源", + "colMaterial": "料號", + "colName": "品名", + "colSpec": "規格", + "colInvoice": "Invoice", + "colFromWarehouse": "撥出倉庫", + "colFromQty": "撥出數量", + "colToWarehouse": "撥入倉庫", + "colToQty": "撥入數量", + "colResult": "預檢結果", + "resultExecutable": "可執行", + "resultNotMatured": "當天收料", + "resultBlocked": "已阻斷", + "resultUnknown": "結果未知", + "runProgress": "調撥執行進度", + "runExecuting": "執行中", + "runSuccess": "已完成", + "runPartialFailed": "部分失敗", + "runFailed": "失敗", + "runCancelled": "已取消", + "refreshProgress": "重新整理進度", + "resultTitle": "調撥結果", + "materialCount": "{count} 項物料", + "posted": "已過帳", + "noDocuments": "本次未產生 ERP 單據", + "exceptionsTitle": "未產生 ERP 單據", + "exceptionBusinessFailed": "業務失敗", + "exceptionTechnicalFailed": "技術失敗", + "exceptionPrecheckExpired": "預檢失效", + "downloadReceiptFiles": "下載收料來源檔案", + "downloadErpInventory": "下載 ERP 庫存表", + "downloadExceptions": "下載異常 Excel", + "backlogTitle": "待處理異常", + "retryErp": "重新查詢 ERP", + "manualClose": "標記無需繼續處理", + "manualCloseTitle": "標記無需繼續處理", + "manualCloseHint": "關閉後自動排程不再處理;歷史與稽核永久保留。", + "closeReasonPlaceholder": "請輸入關閉原因(必填)", + "confirmClose": "確認關閉", + "cancel": "取消", + "agingNormal": "一般待辦", + "agingWarn": "即將逾期(3 天)", + "agingEscalate": "升級(5 天)", + "agingCritical": "嚴重積壓(7 天+)", + "statusClosed": "已人工關閉", + "resultUnknownReadonly": "唯讀,依 SOP 人工核實", + "noBacklog": "暫無待處理異常", + "sourceSelectTitle": "選擇收料來源實例", + "sourceSelectHint": "DBS、Crane 僅為平台分組;請勾選實際需要處理的來源實例。", + "selectAll": "全選", + "selectEnabledAll": "全選已啟用", + "clearSources": "清空", + "selectedSourceCount": "已選 {count} 個來源實例", + "needSelectSource": "請至少選擇一個已啟用來源實例", + "confirmScopeAndPrecheck": "確認範圍並預檢", + "homeWelcome": "你好,您已進入", + "homeTodayLabel": "今日待辦", + "homeTodayAction": "發起今日調撥預檢", + "homeTodayHint": "選擇來源實例後,系統預設以昨天為業務日期處理可成熟收料。", + "homeHistoryLabel": "歷史待辦", + "homeRecoverable": "可恢復異常", + "homeRecoverableHint": "可重新查詢 ERP 庫存後繼續處理", + "homeClosed": "已人工關閉", + "homeClosedHint": "可查看原因並恢復處理", + "homeUnknown": "結果未知", + "homeUnknownHint": "唯讀,需線下核實 ERP 事實", + "homeBack": "返回首頁", + "retryReceipt": "重試收料 RPA", + "retrying": "重試中…", + "fileReady": "檔案已就緒", + "fileFetching": "抓取中", + "fileFailed": "抓取失敗", + "fileNone": "待抓取", + "needReadyFile": "所選來源存在無收料檔案/或抓取中/或失敗,請先重試收料 RPA", + "selectVisible": "全選可見", + "selectRetryable": "只選可重試", + "batchRetry": "批次重試 RPA", + "selectedRetryableCount": "其中 {count} 個可重試", + "noRetryable": "所選來源均無需重試(已就緒或抓取中)" } }