From 323928626bb8c2eec71977c27e35794217f17e86 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Sat, 1 Aug 2026 13:08:32 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-process-gates):=20=E8=90=BD?= =?UTF-8?q?=E5=9C=B0=E5=85=A8=E9=97=A8=E7=A6=81=E4=B8=AD=E6=96=AD=E6=81=A2?= =?UTF-8?q?=E5=A4=8D=E5=B9=B6=E6=B6=88=E9=99=A4=E5=8F=8C=E7=9C=9F=E7=9B=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断, Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。 Co-authored-by: Cursor --- .env.shared | 7 + backend/app/api/admin/__init__.py | 1 + .../app/api/admin/shipping_process_gate.py | 85 ++ backend/app/api/chat.py | 7 +- backend/app/api/workspace/__init__.py | 6 +- backend/app/api/workspace/shipping_notice.py | 75 ++ .../api/workspace/shipping_process_gate.py | 160 +++ backend/app/jobs/handlers/__init__.py | 13 +- .../jobs/handlers/shipping_process_gate.py | 111 ++ backend/app/jobs/types.py | 6 +- backend/app/models/__init__.py | 8 + backend/app/models/shipping_audit_event.py | 5 +- backend/app/models/shipping_process_gate.py | 274 ++++ .../services/shipping_notice/audit_service.py | 9 +- .../freeze_readiness_service.py | 226 +++- .../shipping_notice/generic_order_gate.py | 30 +- .../inventory_routing_engine.py | 66 +- .../order_auto_freeze_policy.py | 44 +- .../order_build_eligibility_service.py | 464 ++++++- .../order_extraction_run_service.py | 48 +- .../order_review_confirmation_service.py | 10 +- .../process_gate_access_service.py | 205 +++ .../process_gate_api_service.py | 326 +++++ .../shipping_notice/process_gate_bridge.py | 648 +++++++++ .../shipping_notice/process_gate_contract.py | 596 +++++++++ .../process_gate_dependency.py | 177 +++ .../process_gate_error_sanitizer.py | 60 + .../shipping_notice/process_gate_executor.py | 1170 +++++++++++++++++ .../process_gate_job_service.py | 403 ++++++ .../process_gate_projection.py | 404 ++++++ .../process_gate_recovery_service.py | 178 +++ .../shipping_notice/process_gate_service.py | 765 +++++++++++ .../progress_audit_contract.py | 43 +- .../shipping_notice/progress_workflow.py | 41 +- .../app/services/shipping_notice/ui_state.py | 58 +- .../workflow_progress_projection.py | 36 +- ...1f2a4_add_external_reservation_id_alias.py | 72 + ...b4c6_add_shipping_process_gate_recovery.py | 253 ++++ .../tests/test_shipping_process_gate_api.py | 208 +++ .../test_shipping_process_gate_contract.py | 97 ++ ...t_shipping_process_gate_error_sanitizer.py | 29 + ...t_shipping_process_gate_fault_injection.py | 200 +++ .../tests/test_shipping_process_gate_lease.py | 147 +++ .../test_shipping_process_gate_migration.py | 87 ++ .../test_shipping_process_gate_models.py | 191 +++ .../test_shipping_process_gate_requeue.py | 77 ++ .../test_shipping_process_gate_service.py | 371 ++++++ docker-compose.yml | 5 + docs/features/shipping-notice/README.md | 1 + .../process-gate-recovery-acceptance.md | 101 ++ .../process-gate-recovery-contract.md | 266 ++++ docs/features/shipping-notice/technical.md | 52 +- docs/funclist.md | 7 +- .../src/app/router/routes/admin.routes.ts | 8 + .../features/admin/components/AdminNav.vue | 17 +- .../src/features/admin/constants/modules.ts | 3 + .../ShippingProcessGateDiagnosticsPage.vue | 794 +++++++++++ .../admin/shippingConfigNavigation.spec.ts | 5 +- .../src/features/admin/types/admin.types.ts | 1 + .../src/features/admin/views/AdminLayout.vue | 8 +- .../ReviewBuildEligibilityPanel.vue | 37 +- .../shipping/ShippingOrderExtractionCard.vue | 64 +- .../shipping/ShippingWorkflowTimeline.vue | 96 +- .../features/chat/types/shipping.api.types.ts | 198 +++ .../chat/views/ShippingOrderReviewView.vue | 139 +- .../api/process-gates.api.ts | 163 +++ .../ProcessGateRecoveryCard.spec.ts | 53 + .../components/ProcessGateRecoveryCard.vue | 138 ++ .../composables/processGateNavigation.ts | 78 ++ .../useShippingProcessGateRecovery.ts | 132 ++ .../types/process-gate.types.ts | 52 + .../ShippingTaskWorkbench.vue | 33 +- .../TaskProgressTimeline.spec.ts | 44 +- .../TaskProgressTimeline.vue | 30 +- .../shipping-task-center/TaskTodoPanel.vue | 78 +- frontend/src/locales/en/admin.json | 79 +- frontend/src/locales/en/chat.json | 133 +- frontend/src/locales/en/errors.json | 19 +- frontend/src/locales/en/workspace.json | 72 +- frontend/src/locales/th/admin.json | 79 +- frontend/src/locales/th/chat.json | 127 +- frontend/src/locales/th/errors.json | 19 +- frontend/src/locales/th/workspace.json | 72 +- frontend/src/locales/zh-CN/admin.json | 79 +- frontend/src/locales/zh-CN/chat.json | 131 +- frontend/src/locales/zh-CN/errors.json | 19 +- frontend/src/locales/zh-CN/workspace.json | 72 +- frontend/src/locales/zh-TW/admin.json | 79 +- frontend/src/locales/zh-TW/chat.json | 135 +- frontend/src/locales/zh-TW/errors.json | 19 +- frontend/src/locales/zh-TW/workspace.json | 72 +- scripts/healthcheck.sh | 82 +- 92 files changed, 11930 insertions(+), 458 deletions(-) create mode 100644 backend/app/api/admin/shipping_process_gate.py create mode 100644 backend/app/api/workspace/shipping_process_gate.py create mode 100644 backend/app/jobs/handlers/shipping_process_gate.py create mode 100644 backend/app/models/shipping_process_gate.py create mode 100644 backend/app/services/shipping_notice/process_gate_access_service.py create mode 100644 backend/app/services/shipping_notice/process_gate_api_service.py create mode 100644 backend/app/services/shipping_notice/process_gate_bridge.py create mode 100644 backend/app/services/shipping_notice/process_gate_contract.py create mode 100644 backend/app/services/shipping_notice/process_gate_dependency.py create mode 100644 backend/app/services/shipping_notice/process_gate_error_sanitizer.py create mode 100644 backend/app/services/shipping_notice/process_gate_executor.py create mode 100644 backend/app/services/shipping_notice/process_gate_job_service.py create mode 100644 backend/app/services/shipping_notice/process_gate_projection.py create mode 100644 backend/app/services/shipping_notice/process_gate_recovery_service.py create mode 100644 backend/app/services/shipping_notice/process_gate_service.py create mode 100644 backend/migrations/versions/b8c9d0e1f2a4_add_external_reservation_id_alias.py create mode 100644 backend/migrations/versions/d0e1f2a3b4c6_add_shipping_process_gate_recovery.py create mode 100644 backend/tests/test_shipping_process_gate_api.py create mode 100644 backend/tests/test_shipping_process_gate_contract.py create mode 100644 backend/tests/test_shipping_process_gate_error_sanitizer.py create mode 100644 backend/tests/test_shipping_process_gate_fault_injection.py create mode 100644 backend/tests/test_shipping_process_gate_lease.py create mode 100644 backend/tests/test_shipping_process_gate_migration.py create mode 100644 backend/tests/test_shipping_process_gate_models.py create mode 100644 backend/tests/test_shipping_process_gate_requeue.py create mode 100644 backend/tests/test_shipping_process_gate_service.py create mode 100644 docs/features/shipping-notice/process-gate-recovery-acceptance.md create mode 100644 docs/features/shipping-notice/process-gate-recovery-contract.md create mode 100644 frontend/src/features/admin/modules/shipping-process-gates/ShippingProcessGateDiagnosticsPage.vue create mode 100644 frontend/src/features/shipping-process-gates/api/process-gates.api.ts create mode 100644 frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts create mode 100644 frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue create mode 100644 frontend/src/features/shipping-process-gates/composables/processGateNavigation.ts create mode 100644 frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts create mode 100644 frontend/src/features/shipping-process-gates/types/process-gate.types.ts diff --git a/.env.shared b/.env.shared index 06afcd5c..5f03cee7 100644 --- a/.env.shared +++ b/.env.shared @@ -152,6 +152,13 @@ SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=false SHIPPING_NOTICE_WORKER_CONCURRENCY=2 # 通用 Job 回收阈值须高于版面 Worker 360 秒上限,避免并发 Worker 误回收正常长任务。 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=420 +# 门禁 Attempt 租约 / 心跳 / 接管 / 技术重试(与 process_gate_job_service 默认一致)。 +SHIPPING_PROCESS_GATE_LEASE_SECONDS=60 +SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS=15 +SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=120 +SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3 +SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30 +SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800 # 订单行双写/切读:dual 写 + shadow 观察;全量 verify 零差异且观察窗口通过后切 table。 # 回滚:将 READ_MODE 改回 json(或 shadow)即可,本期不删 lines_json。 SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index 34433407..4e7f3844 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -27,5 +27,6 @@ import app.api.admin.shipping_order_schema # noqa: F401 import app.api.admin.shipping_field_assets # noqa: F401 import app.api.admin.shipping_order_document_profiles # noqa: F401 import app.api.admin.shipping_document_layouts # noqa: F401 +import app.api.admin.shipping_process_gate # noqa: F401 __all__ = ['admin_bp'] diff --git a/backend/app/api/admin/shipping_process_gate.py b/backend/app/api/admin/shipping_process_gate.py new file mode 100644 index 00000000..d74c3eb1 --- /dev/null +++ b/backend/app/api/admin/shipping_process_gate.py @@ -0,0 +1,85 @@ +""" +backend/app/api/admin/shipping_process_gate.py + +用途:货代全门禁恢复 Admin API(Execution 列表/诊断、Gate Attempt 运维视图)。 +依赖:admin Blueprint、require_admin、process_gate_api_service、process_gate_recovery_service。 +逻辑:仅 shipping admin(platform admin 角色)可访问;只读诊断与 Attempt 详情,不含用户写路径。 +""" + +from __future__ import annotations + +from flask import g, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.errors import ValidationError +from app.core.response import ok +from app.services.shipping_notice.process_gate_api_service import ( + get_admin_gate_attempt, + get_admin_process_execution, + list_admin_gate_attempts, + list_admin_process_executions, +) +from app.services.shipping_notice.process_gate_recovery_service import get_execution_by_no + + +def _query_int(name: str, default: int) -> int: + """读取可选整数查询参数;非整数抛出统一参数错误。""" + raw = request.args.get(name) + if raw in (None, ''): + return default + try: + return int(raw) + except (TypeError, ValueError) as exc: + raise ValidationError(f'{name} must be an integer') from exc + + +@admin_bp.route('/shipping-notice/process-executions', methods=['GET']) +@require_admin +def admin_list_process_executions(): + """分页返回 Process Execution 管理员摘要列表。""" + page = _query_int('page', 1) + page_size = _query_int('page_size', 25) + if page < 1 or not 1 <= page_size <= 100: + raise ValidationError('page must be positive and page_size must be between 1 and 100') + payload = list_admin_process_executions( + page=page, + page_size=page_size, + status=request.args.get('status'), + gate_code=request.args.get('gate_code'), + blocking_reason_code=request.args.get('blocking_reason_code'), + responsible_party=request.args.get('responsible_party'), + q=request.args.get('q'), + updated_from=request.args.get('updated_from'), + updated_to=request.args.get('updated_to'), + ) + return ok(payload, request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route('/shipping-notice/process-executions/', methods=['GET']) +@require_admin +def admin_get_process_execution(execution_no: str): + """读取单次 Execution 的完整 Gate 诊断投影。""" + execution = get_execution_by_no(execution_no) + payload = get_admin_process_execution(execution) + return ok(payload, request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route( + '/shipping-notice/process-executions//gates//attempts', + methods=['GET'], +) +@require_admin +def admin_list_process_gate_attempts(execution_no: str, gate_code: str): + """返回指定 Gate 的全部 Attempt 摘要(含 Gate 诊断投影)。""" + execution = get_execution_by_no(execution_no) + payload = list_admin_gate_attempts(execution, gate_code) + return ok(payload, request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route('/shipping-notice/process-gate-attempts/', methods=['GET']) +@require_admin +def admin_get_process_gate_attempt(attempt_id: int): + """按主键读取 Attempt 详情及 Execution/Gate 上下文。""" + payload = get_admin_gate_attempt(attempt_id) + return ok(payload, request_id=getattr(g, 'request_id', None)) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index d12d6bfa..aede7159 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -1772,7 +1772,12 @@ def chat_completions(): yield terminal_line except Exception as exc: current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id) - payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'} + payload = { + 'event': 'error', + 'message': '当前服务暂时无法完成回答,请稍后重试。', + 'conversation_id': local_session_id, + 'session_status': 'error', + } yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" for terminal_line in iter_handler_terminal_sse( relay_stream_ctx, diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py index 1b6a4307..40c38148 100644 --- a/backend/app/api/workspace/__init__.py +++ b/backend/app/api/workspace/__init__.py @@ -1,15 +1,17 @@ """ backend/app/api/workspace/__init__.py -用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。 +用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements、process_gate 路由)。 依赖:workspace 各子模块 blueprint。 -逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。 +逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp;process_gate 路由挂载于 workspace_shipping_notice_bp。 """ from app.api.workspace.announcements import workspace_announcements_bp from app.api.workspace.file_check import workspace_file_check_bp from app.api.workspace.schedule import workspace_schedule_bp from app.api.workspace.shipping_notice import workspace_shipping_notice_bp +import app.api.workspace.shipping_process_gate # noqa: F401 + __all__ = [ 'workspace_announcements_bp', 'workspace_file_check_bp', diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 6103e999..940bd565 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -1316,6 +1316,81 @@ def workspace_set_shipping_order_review_inventory_candidates(case_no: str, line_ return _ok(result) +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//draft/inventory-routing/reroute', + methods=['POST'], +) +def workspace_reroute_shipping_order_review_inventory_routing(case_no: str): + """ + 按最新已发布规则重算库存源路由;不重新识别 PDF,不静默覆盖人工决定。 + + 核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。 + """ + user = _require_user() + from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing + + payload = _review_draft_payload( + user_id=user.id, case_no=case_no, action='inventory_routing_rerouted', + ) + result = reroute_inventory_routing( + user_id=user.id, + case_no=case_no, + expected_draft_version=payload.get('expected_draft_version'), + idempotency_key=payload.get('idempotency_key'), + line_key=payload.get('line_key'), + ) + db.session.commit() + return _ok(result) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//draft/lines//inventory-routing/adopt-suggestion', + methods=['POST'], +) +def workspace_adopt_shipping_order_review_inventory_routing_suggestion(case_no: str, line_key: str): + """采用当前规则建议为有效库存源候选。""" + user = _require_user() + from app.services.shipping_notice.order_review_draft_service import adopt_inventory_routing_suggestion + + payload = _review_draft_payload( + user_id=user.id, case_no=case_no, action='inventory_routing_suggestion_adopted', + ) + result = adopt_inventory_routing_suggestion( + user_id=user.id, + case_no=case_no, + line_key=line_key, + expected_draft_version=payload.get('expected_draft_version'), + idempotency_key=payload.get('idempotency_key'), + reason=payload.get('reason'), + ) + db.session.commit() + return _ok(result) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//draft/lines//inventory-routing/keep-manual', + methods=['POST'], +) +def workspace_keep_shipping_order_review_inventory_routing_manual(case_no: str, line_key: str): + """明确保留人工库存源决定并拒绝规则建议。""" + user = _require_user() + from app.services.shipping_notice.order_review_draft_service import keep_manual_inventory_routing + + payload = _review_draft_payload( + user_id=user.id, case_no=case_no, action='inventory_routing_manual_kept', + ) + result = keep_manual_inventory_routing( + user_id=user.id, + case_no=case_no, + line_key=line_key, + expected_draft_version=payload.get('expected_draft_version'), + idempotency_key=payload.get('idempotency_key'), + reason=payload.get('reason'), + ) + db.session.commit() + return _ok(result) + + @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//confirm', methods=['POST']) def workspace_confirm_shipping_order_review_case(case_no: str): """确认一份 PDF 草稿并独立建单;提交后复用 auto_progress 自动推进。""" diff --git a/backend/app/api/workspace/shipping_process_gate.py b/backend/app/api/workspace/shipping_process_gate.py new file mode 100644 index 00000000..c38c4e1c --- /dev/null +++ b/backend/app/api/workspace/shipping_process_gate.py @@ -0,0 +1,160 @@ +""" +backend/app/api/workspace/shipping_process_gate.py + +用途:货代全门禁恢复 Workspace API(Execution 读、Gate 列表、恢复动作、审计事件)。 +依赖:workspace_shipping_notice_bp、process_gate_recovery_service、process_gate_api_service、 + process_gate_access_service、AppError 全局 handler。 +逻辑:薄路由鉴权与 POST 体 forbidden-key 校验;写动作委托 request_gate_action; + 403 时 access_service 写入 process_gate_permission_denied 审计。 +""" + +from __future__ import annotations + +from flask import g, request + +from app import db +from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp +from app.core.errors import ValidationError +from app.services.shipping_notice.process_gate_access_service import assert_execution_visible_to_user +from app.services.shipping_notice.process_gate_api_service import ( + get_workspace_process_execution, + list_workspace_process_gate_audit_events, + list_workspace_process_gates, +) +from app.services.shipping_notice.process_gate_recovery_service import get_execution_by_no, request_gate_action + + +def _query_int(name: str, default: int) -> int: + """读取可选整数查询参数。""" + raw = request.args.get(name) + if raw in (None, ''): + return default + try: + return int(raw) + except (TypeError, ValueError) as exc: + raise ValidationError(f'{name} must be an integer') from exc + + +def _parse_gate_action_body() -> dict: + """ + 校验 POST 恢复动作请求体。 + + 核心逻辑:仅允许 action_code / expected_gate_version / idempotency_key / payload; + 顶层与 payload 均禁止 execution 控制字段。 + + Returns: + 规范化后的 action 参数字典。 + + Raises: + ValidationError: 缺字段或含 forbidden keys。 + """ + body = request.get_json(silent=True) or {} + if body and not isinstance(body, dict): + raise ValidationError('Request body must be an object') + forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql', 'start_gate'} + if forbidden.intersection(set(body.keys())): + raise ValidationError( + 'Client must not submit execution controls', + code='SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN', + ) + action_code = str(body.get('action_code') or '').strip() + if not action_code: + raise ValidationError('action_code is required', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + if body.get('expected_gate_version') is None: + raise ValidationError( + 'expected_gate_version is required', + code='SHIPPING.PROCESS_GATE_ACTION_INVALID', + ) + try: + expected_gate_version = int(body.get('expected_gate_version')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'expected_gate_version must be an integer', + code='SHIPPING.PROCESS_GATE_ACTION_INVALID', + ) from exc + idempotency_key = str(body.get('idempotency_key') or '').strip() + if not idempotency_key: + raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + payload = body.get('payload') + if payload is not None and not isinstance(payload, dict): + raise ValidationError('payload must be an object', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + if isinstance(payload, dict) and forbidden.intersection(set(payload.keys())): + raise ValidationError( + 'Client must not submit execution controls', + code='SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN', + ) + return { + 'action_code': action_code, + 'expected_gate_version': expected_gate_version, + 'idempotency_key': idempotency_key, + 'payload': payload if isinstance(payload, dict) else None, + } + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/process-executions/', + methods=['GET'], +) +def workspace_get_process_execution(execution_no: str): + """读取当前用户可见的 Process Execution 工作台投影。""" + user = _require_user() + execution = get_execution_by_no(execution_no) + assert_execution_visible_to_user(user, execution) + return _ok(get_workspace_process_execution(execution)) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/process-executions//gates', + methods=['GET'], +) +def workspace_list_process_gates(execution_no: str): + """列出 Execution 下全部 Gate 的用户安全投影。""" + user = _require_user() + execution = get_execution_by_no(execution_no) + assert_execution_visible_to_user(user, execution) + return _ok(list_workspace_process_gates(execution)) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/process-executions//gates//actions', + methods=['POST'], +) +def workspace_post_process_gate_action(execution_no: str, gate_code: str): + """ + 请求执行服务端下发的门禁恢复动作。 + + 核心逻辑:校验权限与 POST 契约后调用 request_gate_action;同事务提交。 + """ + user = _require_user() + execution = get_execution_by_no(execution_no) + assert_execution_visible_to_user(user, execution, write=True, gate_code=gate_code) + parsed = _parse_gate_action_body() + result = request_gate_action( + execution_no=execution.execution_no, + gate_code=gate_code, + action_code=parsed['action_code'], + expected_gate_version=parsed['expected_gate_version'], + idempotency_key=parsed['idempotency_key'], + actor_type='admin' if str(user.role or '').lower() == 'admin' else 'user', + actor_id=int(user.id), + payload=parsed['payload'], + ) + db.session.commit() + return _ok(result) + + +@workspace_shipping_notice_bp.route( + '/shipping-notice/process-executions//audit-events', + methods=['GET'], +) +def workspace_list_process_gate_audit_events(execution_no: str): + """分页返回 Execution 关联的 PROCESS_GATE 审计事件(用户可见字段)。""" + user = _require_user() + execution = get_execution_by_no(execution_no) + assert_execution_visible_to_user(user, execution) + payload = list_workspace_process_gate_audit_events( + execution, + page=_query_int('page', 1), + page_size=_query_int('page_size', 50), + ) + return _ok(payload) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 8153e8ac..5621e3e1 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -5,4 +5,15 @@ backend/app/jobs/handlers/__init__.py 逻辑:Wave 2 起在 worker 启动前 import 本包。 """ -from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_document_layout, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401 +from app.jobs.handlers import ( # noqa: F401 + file_check_run, + kb_clean, + kb_dify_sync, + schedule_run, + shipping_document_layout, + shipping_notice_parse, + shipping_notice_run, + shipping_order_extraction, + shipping_process_gate, + wecom_directory_sync, +) diff --git a/backend/app/jobs/handlers/shipping_process_gate.py b/backend/app/jobs/handlers/shipping_process_gate.py new file mode 100644 index 00000000..f6581c0b --- /dev/null +++ b/backend/app/jobs/handlers/shipping_process_gate.py @@ -0,0 +1,111 @@ +""" +backend/app/jobs/handlers/shipping_process_gate.py + +用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。 +依赖:JobContext、process_gate_job_service、jobs.queue finish/fail。 +逻辑:由 shipping worker 领取;技术失败按 5s/30s/120s 退避重新入队; + waiting_external 先结束当前 Job 再延迟入队新 Job(禁止复用仍 running 的 Job); + 成功进入 waiting_external 时调度下一次 poll Attempt。 +""" + +from __future__ import annotations + +from flask import current_app + +from app import db +from app.jobs.context import JobContext +from app.jobs.queue import fail_job, finish_job +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt +from app.services.shipping_notice.process_gate_job_service import ( + claim_and_run_gate_attempt, + enqueue_gate_attempt_job, + schedule_waiting_external_poll, +) + +# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。 +_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120) + + +@register_handler(JobType.SHIPPING_PROCESS_GATE) +def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None: + """ + 执行门禁 Attempt。 + + Args: + ctx: Worker 上下文。 + payload: 须含 attempt_id 与 job_id。 + """ + attempt_id = int(payload.get('attempt_id') or 0) + raw_job_id = payload.get('job_id') + job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None + if attempt_id <= 0 or job is None: + raise RuntimeError('missing_attempt_id_or_job_id') + + owned_attempt = int(job.attempts or 0) + worker_id = str(ctx.extras.get('worker_label') or f'shipping-gate-{job.id}') + try: + result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id) + except Exception as exc: + attempt = db.session.get(ShippingProcessGateAttempt, attempt_id) + gate = None + gate_status = None + if attempt is not None: + gate = db.session.get(ShippingProcessGate, int(attempt.gate_id)) + gate_status = gate.status if gate else None + + # [STEP] 外部等待:先结束当前 Job,再清空 job_id 并延迟入队,避免复用 running Job。 + if gate_status == 'waiting_external': + poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5) + finish_job(job.id, result={'status': 'waiting_external_requeued'}, owned_attempt=owned_attempt) + if attempt is not None: + attempt.job_id = None + db.session.flush() + enqueue_gate_attempt_job( + attempt_id=attempt_id, + delay_seconds=poll, + force_new=True, + ) + db.session.commit() + return + + # [STEP] 技术失败:先 fail 当前 Job,再按退避入队新 Job。 + max_attempts = int(job.max_attempts or 3) + if attempt is not None and owned_attempt < max_attempts: + delay_idx = min(max(owned_attempt - 1, 0), len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1) + delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx] + fail_job( + job.id, + error=str(exc)[:1000], + retryable=False, + owned_attempt=owned_attempt, + ) + attempt.status = 'queued' + attempt.job_id = None + attempt.worker_id = None + attempt.lease_token = None + attempt.lease_expires_at = None + if gate is not None and gate.status == 'running': + gate.status = 'queued' + db.session.flush() + enqueue_gate_attempt_job( + attempt_id=attempt_id, + delay_seconds=delay, + force_new=True, + ) + db.session.commit() + return + + fail_job(job.id, error=str(exc)[:1000], retryable=False, owned_attempt=owned_attempt) + return + + finish_job(job.id, result=result, owned_attempt=owned_attempt) + + # [STEP] 成功落入 waiting_external:调度下一次 poll Attempt(含超时判定)。 + if str((result or {}).get('gate_status') or '') == 'waiting_external': + schedule_waiting_external_poll( + attempt_id=int(attempt_id), + gate_code=str((result or {}).get('gate_code') or ''), + ) + db.session.commit() diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 16715dac..8d99c7c0 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -2,7 +2,8 @@ backend/app/jobs/types.py 用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。 -逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨)。 +逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨); + shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。 """ from __future__ import annotations @@ -18,6 +19,7 @@ class JobType(StrEnum): SHIPPING_NOTICE_PARSE = 'shipping_notice_parse' SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' + SHIPPING_PROCESS_GATE = 'shipping_process_gate' SCHEDULE_RUN = 'schedule_run' FILE_CHECK_RUN = 'file_check_run' WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' @@ -53,7 +55,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'kb': frozenset({'clean', 'path_upload', 'sync_dify'}), 'shipping': frozenset({ 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', - 'shipping_document_layout', + 'shipping_document_layout', 'shipping_process_gate', }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index f5594a52..d26440e7 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -38,6 +38,11 @@ from app.models.shipping_fulfillment import ( ShippingReservation, ShippingUploadAttempt, ) +from app.models.shipping_process_gate import ( + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, +) from app.models.shipping_order_schema import ( ShippingFieldAsset, ShippingOrderExtraction, @@ -261,6 +266,9 @@ __all__ = [ 'ShippingInventoryVerificationLine', 'ShippingExportArtifactLine', 'ShippingUploadAttempt', + 'ShippingProcessExecution', + 'ShippingProcessGate', + 'ShippingProcessGateAttempt', 'ShippingNoticeIntake', 'ShippingNoticeDocument', 'ShippingNoticeCandidate', diff --git a/backend/app/models/shipping_audit_event.py b/backend/app/models/shipping_audit_event.py index f8587cbf..bd54c82d 100644 --- a/backend/app/models/shipping_audit_event.py +++ b/backend/app/models/shipping_audit_event.py @@ -3,7 +3,8 @@ backend/app/models/shipping_audit_event.py 用途:定义货代领域统一、仅追加的审计事件。 依赖:SQLAlchemy Base;Workflow / Run / Task / Intake 等稳定业务编号(软引用)。 -逻辑:各业务服务通过 audit_service 追加事件;事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。 +逻辑:各业务服务通过 audit_service 追加事件;actor_type 含 worker(门禁 Job); + 事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。 进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间; Workflow 阶段以 workflow_id / workflow_item_id / workflow_item_version_id 软引用批次与 PDF 项, 并写入 previous_event_hash / event_hash 哈希链与 diff_json;另含 owner_user_id 与脱敏 @@ -33,7 +34,7 @@ class ShippingAuditEvent(Base): __tablename__ = 'shipping_audit_events' __table_args__ = ( CheckConstraint( - "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')", + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')", name='ck_shipping_audit_events_actor_type', ), CheckConstraint( diff --git a/backend/app/models/shipping_process_gate.py b/backend/app/models/shipping_process_gate.py new file mode 100644 index 00000000..91e3be9b --- /dev/null +++ b/backend/app/models/shipping_process_gate.py @@ -0,0 +1,274 @@ +""" +models/shipping_process_gate.py + +用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。 +依赖:SQLAlchemy Base、WorkflowItem/Version、ReviewCase、ShippingTask、Job; + 状态枚举与 process_gate_contract 对齐。 +逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。 + 由领域服务独占写入;Job 仅调度,WorkflowItem 仅聚合台账。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import ( + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + Text, + UniqueConstraint, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +def _utc_now() -> datetime: + """返回 naive UTC 时间,与仓库现有模型一致。""" + return datetime.utcnow() + + +class ShippingProcessExecution(Base): + """业务执行实例;门禁恢复状态唯一真相,不保存大体量订单原文。""" + + __tablename__ = 'shipping_process_executions' + __table_args__ = ( + UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'), + UniqueConstraint( + 'workflow_item_version_id', + name='uq_shipping_process_executions_workflow_item_version', + ), + CheckConstraint( + "status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')", + name='ck_shipping_process_executions_status', + ), + CheckConstraint('lock_version >= 1', name='ck_shipping_process_executions_lock_version'), + Index( + 'ix_shipping_process_executions_status_updated', + 'status', + 'updated_at', + ), + Index( + 'ix_shipping_process_executions_workflow_item', + 'workflow_item_id', + 'updated_at', + ), + Index( + 'ix_shipping_process_executions_current_gate', + 'current_gate_code', + 'status', + 'updated_at', + ), + Index( + 'ix_shipping_process_executions_review_case', + 'review_case_id', + ), + Index( + 'ix_shipping_process_executions_task', + 'task_id', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + execution_no: Mapped[str] = mapped_column(String(64), nullable=False) + workflow_item_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_workflow_items.id'), nullable=False, + ) + workflow_item_version_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_workflow_item_versions.id'), nullable=False, + ) + review_case_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_review_cases.id'), nullable=True, + ) + task_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_tasks.id'), nullable=True, + ) + status: Mapped[str] = mapped_column( + String(32), nullable=False, default='active', server_default='active', + ) + current_gate_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + last_passed_gate_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + primary_next_action_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + responsible_party: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, + ) + + gates: Mapped[list['ShippingProcessGate']] = relationship( + back_populates='execution', + cascade='all, delete-orphan', + order_by='ShippingProcessGate.sequence_no', + ) + + +class ShippingProcessGate(Base): + """单门禁实例;保存状态、输入指纹、阻断原因与最新 Attempt 指针。""" + + __tablename__ = 'shipping_process_gates' + __table_args__ = ( + UniqueConstraint( + 'execution_id', + 'gate_code', + name='uq_shipping_process_gates_execution_code', + ), + UniqueConstraint( + 'execution_id', + 'sequence_no', + name='uq_shipping_process_gates_execution_sequence', + ), + CheckConstraint( + "status IN (" + "'pending', 'queued', 'running', 'passed', 'blocked_retryable', " + "'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped'" + ")", + name='ck_shipping_process_gates_status', + ), + CheckConstraint('sequence_no >= 1', name='ck_shipping_process_gates_sequence'), + CheckConstraint('evaluation_version >= 1', name='ck_shipping_process_gates_eval_version'), + CheckConstraint('lock_version >= 1', name='ck_shipping_process_gates_lock_version'), + Index( + 'ix_shipping_process_gates_execution_status', + 'execution_id', + 'status', + 'updated_at', + ), + Index( + 'ix_shipping_process_gates_code_status', + 'gate_code', + 'status', + 'updated_at', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + execution_id: Mapped[int] = mapped_column( + ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False, + ) + gate_code: Mapped[str] = mapped_column(String(64), nullable=False) + sequence_no: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column( + String(32), nullable=False, default='pending', server_default='pending', + ) + evaluation_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + blocking_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + blocking_reason_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + recommendation_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + effective_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + next_action_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + # 软指针:避免与 Attempt.gate_id 循环外键;由领域服务保证一致性。 + latest_attempt_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + passed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, + ) + + execution: Mapped[ShippingProcessExecution] = relationship(back_populates='gates') + attempts: Mapped[list['ShippingProcessGateAttempt']] = relationship( + back_populates='gate', + cascade='all, delete-orphan', + order_by='ShippingProcessGateAttempt.attempt_no', + foreign_keys='ShippingProcessGateAttempt.gate_id', + ) + + +class ShippingProcessGateAttempt(Base): + """不可变门禁执行尝试;成功或失败后业务结果不得被后续重试覆盖。""" + + __tablename__ = 'shipping_process_gate_attempts' + __table_args__ = ( + UniqueConstraint( + 'gate_id', + 'attempt_no', + name='uq_shipping_process_gate_attempts_gate_no', + ), + UniqueConstraint( + 'idempotency_key', + name='uq_shipping_process_gate_attempts_idempotency', + ), + CheckConstraint( + "status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled', 'superseded')", + name='ck_shipping_process_gate_attempts_status', + ), + CheckConstraint('attempt_no >= 1', name='ck_shipping_process_gate_attempts_no'), + CheckConstraint( + "trigger_type IN (" + "'auto', 'user_retry', 'user_manual', 'worker_takeover', " + "'upstream_invalidation', 'system_requeue'" + ")", + name='ck_shipping_process_gate_attempts_trigger', + ), + CheckConstraint( + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')", + name='ck_shipping_process_gate_attempts_actor_type', + ), + # 同一 Gate 同时最多一个 queued/running Attempt。 + Index( + 'uq_shipping_process_gate_attempts_one_active', + 'gate_id', + unique=True, + postgresql_where=text("status IN ('queued', 'running')"), + sqlite_where=text("status IN ('queued', 'running')"), + ), + Index( + 'ix_shipping_process_gate_attempts_lease', + 'lease_token', + 'lease_expires_at', + ), + Index( + 'ix_shipping_process_gate_attempts_job', + 'job_id', + ), + Index( + 'ix_shipping_process_gate_attempts_gate_status', + 'gate_id', + 'status', + 'created_at', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + gate_id: Mapped[int] = mapped_column( + ForeignKey('shipping_process_gates.id', ondelete='CASCADE'), nullable=False, + ) + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column( + String(32), nullable=False, default='queued', server_default='queued', + ) + trigger_type: Mapped[str] = mapped_column(String(32), nullable=False, default='auto', server_default='auto') + actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system') + actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False) + input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + input_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + rule_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + rule_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + output_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + output_snapshot_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True) + worker_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + heartbeat_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_summary: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) + + gate: Mapped[ShippingProcessGate] = relationship( + back_populates='attempts', + foreign_keys=[gate_id], + ) diff --git a/backend/app/services/shipping_notice/audit_service.py b/backend/app/services/shipping_notice/audit_service.py index 7e55854a..f5eae865 100644 --- a/backend/app/services/shipping_notice/audit_service.py +++ b/backend/app/services/shipping_notice/audit_service.py @@ -5,11 +5,11 @@ backend/app/services/shipping_notice/audit_service.py 写入 Workflow 软引用与哈希链字段。 依赖:ShippingAuditEvent、progress_audit_contract、audit_snapshot_service(在 append 内导入以避免环)、 SQLAlchemy 会话。 -逻辑:Run、Task、Workflow Item、库存和 Chatflow 服务调用本模块写入状态与决策事实; +逻辑:Run、Task、Workflow Item、库存、门禁 Attempt 和 Chatflow 服务调用本模块写入状态与决策事实; 写入前投影白名单快照 → 计算 diff → 解析同聚合 previous_event_hash → 计算 event_hash; 本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、 - 证据引用、Workflow 软引用(非 session_item)、属主;货代全业务审计事件永久保留 - (retention_expires_at=None),清理 Job 仅处理历史遗留的到期行。IP / User-Agent 仅持久化哈希。 + 证据引用、Workflow 软引用(非 session_item)、属主;actor_type 含 worker(门禁 Job); + 货代全业务审计事件永久保留(retention_expires_at=None),清理 Job 仅处理历史遗留到期行。 """ from __future__ import annotations @@ -245,7 +245,8 @@ def append_shipping_audit_event( resolve_previous_event_hash, ) - allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin'} + # worker:门禁 Attempt / Job 租约路径的执行主体(Phase 4+)。 + allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'} if actor_type not in allowed_actor_types: raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID') if result is not None and result not in {'success', 'failure', 'rejected', 'ignored'}: diff --git a/backend/app/services/shipping_notice/freeze_readiness_service.py b/backend/app/services/shipping_notice/freeze_readiness_service.py index 725cc965..73601b6d 100644 --- a/backend/app/services/shipping_notice/freeze_readiness_service.py +++ b/backend/app/services/shipping_notice/freeze_readiness_service.py @@ -1,10 +1,11 @@ """ -冻结前履约就绪门禁。 +services/shipping_notice/freeze_readiness_service.py -用途:集中检查订单解析、字段裁决、客户、冲突与库存源状态,阻止不完整订单进入不可编辑快照。 -依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及固定履约契约。 -逻辑:order_freeze_service 在创建 Snapshot 前调用;失败统一返回结构化 blocking issues。 - 阶段 5 自动冻结入口接入后,同一服务继续负责把 Run 级自动冻结门禁摘要折叠为冻结阻断原因。 +用途:冻结前履约就绪门禁;输出标准 Gate 结果、稳定原因码与诊断 Finding。 +依赖:订单 Extraction、字段裁决、冲突门禁、固定履约契约、process_gate_contract。 +逻辑:order_freeze_service 在创建 Snapshot 前调用 assert_freeze_readiness; + evaluate_freeze_readiness_gate 供统一 Gate 接线消费; + 自动冻结策略资格/客户范围/场景/紧急停止统一归属 order_freeze_readiness。 """ from __future__ import annotations @@ -13,10 +14,135 @@ from decimal import Decimal, InvalidOperation from typing import Any from app.core.errors import ValidationError -from app.models import ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask +from app.models import ( + ShippingOrderExtraction, + ShippingOrderFieldValue, + ShippingOrderLine, + ShippingTask, +) from app.services.shipping_notice.fulfillment_policy_registry import required_field_configs +from app.services.shipping_notice.process_gate_contract import ( + build_process_finding, + owning_gate_for_reason, +) from app.services.shipping_notice.task_field_gate import open_field_conflict_issues +_OWNING_GATE = 'order_freeze_readiness' + + +def evaluate_freeze_readiness_gate( + *, + task: ShippingTask, + extraction: ShippingOrderExtraction, + configs: dict[str, dict[str, Any]], + freeze_mode: str = 'manual', + auto_freeze_policy: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 评估订单冻结就绪门禁,返回标准 Gate 结果。 + + 核心逻辑:收集 blocking / diagnostic Finding;仅 blocking 决定 passed; + 自动冻结路径额外消费 Run 级 policy 并折叠为唯一 owning_gate 原因。 + + Args: + task / extraction / configs: 冻结上下文。 + freeze_mode: manual | auto。 + auto_freeze_policy: Run 冻结策略摘要。 + + Returns: + passed、status、blocking_reason_code、findings、issues。 + """ + issues: list[dict[str, Any]] = [] + findings: list[dict[str, Any]] = [] + + if extraction.status != 'accepted': + issue = {'reason': 'extraction_not_accepted', 'owning_gate_code': 'order_field_extraction'} + issues.append(issue) + findings.append(_issue_finding(issue, severity='blocking')) + + for conflict in open_field_conflict_issues(task): + item = dict(conflict) + item.setdefault('owning_gate_code', 'field_conflict_resolution') + item.setdefault('reason', item.get('reason') or 'field_conflict') + issues.append(item) + findings.append(_issue_finding(item, severity='blocking')) + + auto_issues = _auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy) + issues.extend(auto_issues) + for item in auto_issues: + findings.append(_issue_finding(item, severity='blocking')) + + required = required_field_configs(extraction.schema_version.definition_json or {}) + required_codes = {'reservation_id', 'part_number', 'qty'} + values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all() + value_map = {(item.line_id, str(item.field_id)): item.value_json for item in values} + lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all() + if not lines: + issue = {'reason': 'missing_order_lines', 'owning_gate_code': 'field_completeness'} + issues.append(issue) + findings.append(_issue_finding(issue, severity='blocking')) + for line in lines: + for code in required_codes: + config = required[code] + key = (line.id, str(config['field_id'])) + value = value_map.get(key) + if value in (None, ''): + issue = { + 'reason': 'required_field_missing', + 'field': code, + 'line_index': line.position, + 'owning_gate_code': 'field_completeness', + } + issues.append(issue) + findings.append(_issue_finding(issue, severity='blocking')) + continue + if code == 'qty': + try: + if Decimal(str(value)) <= 0: + raise InvalidOperation + except (InvalidOperation, ValueError, TypeError): + issue = { + 'reason': 'quantity_not_positive', + 'field': code, + 'line_index': line.position, + 'owning_gate_code': 'field_completeness', + } + issues.append(issue) + findings.append(_issue_finding(issue, severity='blocking')) + # 值已存在即视为可冻结;Decision 细节由 field_* Gate 负责。 + + po_config = configs.get('customer_po_number') + if po_config: + po_key = (None, str(po_config['field_id'])) + if value_map.get(po_key) in (None, ''): + issue = { + 'reason': 'required_field_missing', + 'field': 'customer_po_number', + 'owning_gate_code': 'field_completeness', + } + issues.append(issue) + findings.append(_issue_finding(issue, severity='blocking')) + + # 策略内诊断 Finding 一并透出(若已有)。 + policy = auto_freeze_policy if isinstance(auto_freeze_policy, dict) else {} + for item in policy.get('findings') or []: + if isinstance(item, dict) and item.get('finding_code'): + if not any(f.get('finding_code') == item.get('finding_code') for f in findings): + findings.append(dict(item)) + + blocking = [f for f in findings if f.get('severity') == 'blocking' and f.get('blocks_current_action')] + primary = blocking[0] if blocking else None + passed = not blocking + return { + 'passed': passed, + 'status': 'passed' if passed else 'blocked_manual', + 'gate_code': _OWNING_GATE, + 'blocking_reason_code': (primary or {}).get('reason_code') or (None if passed else 'freeze_not_ready'), + 'findings': findings, + 'issues': issues, + 'next_action_code': None if passed else 'open_order_review', + } + def assert_freeze_readiness( *, @@ -26,44 +152,25 @@ def assert_freeze_readiness( freeze_mode: str = 'manual', auto_freeze_policy: dict[str, Any] | None = None, ) -> None: - """校验当前任务是否可冻结;自动冻结额外消费 Run 级门禁摘要并折叠为统一 issues。""" - issues: list[dict[str, Any]] = [] - if extraction.status != 'accepted': - issues.append({'reason': 'extraction_not_accepted'}) - issues.extend(open_field_conflict_issues(task)) - issues.extend(_auto_freeze_blocking_issues(freeze_mode=freeze_mode, auto_freeze_policy=auto_freeze_policy)) + """ + 校验当前任务是否可冻结;失败抛出结构化 ValidationError。 - required = required_field_configs(extraction.schema_version.definition_json or {}) - required_codes = {'reservation_id', 'part_number', 'qty'} - values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all() - decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).all() - accepted = {(item.line_id, str(item.field_id)): item for item in decisions if item.decision_status in {'accepted', 'corroborated'}} - value_map = {(item.line_id, str(item.field_id)): item.value_json for item in values} - lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all() - if not lines: - issues.append({'reason': 'missing_order_lines'}) - for line in lines: - for code in required_codes: - config = required[code] - key = (line.id, str(config['field_id'])) - value = value_map.get(key) - if value in (None, ''): - issues.append({'reason': 'required_field_missing_or_unreviewed', 'field': code, 'line_index': line.position}) - continue - if code == 'qty': - try: - if Decimal(str(value)) <= 0: - raise InvalidOperation - except (InvalidOperation, ValueError, TypeError): - issues.append({'reason': 'quantity_not_positive', 'field': code, 'line_index': line.position}) - # Header PO is the version identity and cannot be empty or unresolved. - po_config = configs.get('customer_po_number') - if po_config: - po_key = (None, str(po_config['field_id'])) - if value_map.get(po_key) in (None, ''): - issues.append({'reason': 'customer_po_missing_or_unreviewed', 'field': 'customer_po_number'}) - if issues: - raise ValidationError('Order is not ready to freeze', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'issues': issues}) + 核心逻辑:委托 evaluate_freeze_readiness_gate;自动冻结额外消费 Run 级门禁摘要。 + """ + result = evaluate_freeze_readiness_gate( + task=task, + extraction=extraction, + configs=configs, + freeze_mode=freeze_mode, + auto_freeze_policy=auto_freeze_policy, + ) + if result.get('passed'): + return + raise ValidationError( + 'Order is not ready to freeze', + code='SHIPPING.ORDER_FREEZE_BLOCKED', + details={'issues': result.get('issues') or [], 'findings': result.get('findings') or []}, + ) def _auto_freeze_blocking_issues( @@ -77,15 +184,44 @@ def _auto_freeze_blocking_issues( policy = auto_freeze_policy if isinstance(auto_freeze_policy, dict) else {} issues: list[dict[str, Any]] = [] if not policy: - return [{'reason': 'auto_freeze_policy_missing'}] + return [{ + 'reason': 'auto_freeze_policy_missing', + 'owning_gate_code': _OWNING_GATE, + }] if not bool(policy.get('enabled')): issues.append({ 'reason': 'auto_freeze_not_enabled', + 'owning_gate_code': _OWNING_GATE, 'mode': str(policy.get('mode') or '') or None, 'qualification_status': str(policy.get('qualification_status') or '') or None, 'customer_scope_status': str(policy.get('customer_scope_status') or '') or None, }) for code in policy.get('blocking_reason_codes') or []: if str(code).strip(): - issues.append({'reason': 'auto_freeze_blocked', 'blocking_reason_code': str(code)}) + issues.append({ + 'reason': 'auto_freeze_blocked', + 'blocking_reason_code': str(code), + 'owning_gate_code': owning_gate_for_reason(str(code)) or _OWNING_GATE, + }) return issues + + +def _issue_finding(issue: dict[str, Any], *, severity: str) -> dict[str, Any]: + """将内部 issue 转为标准 Finding。""" + reason = str(issue.get('blocking_reason_code') or issue.get('reason') or 'freeze_not_ready') + owning = str(issue.get('owning_gate_code') or owning_gate_for_reason(reason) or _OWNING_GATE) + mapped = owning_gate_for_reason(reason) + stable_reason = reason if mapped else ('freeze_not_ready' if owning == _OWNING_GATE else 'required_field_missing' if owning == 'field_completeness' else 'extraction_incomplete' if owning == 'order_field_extraction' else 'field_conflict' if owning == 'field_conflict_resolution' else 'freeze_not_ready') + return build_process_finding( + finding_code=f'freeze_{reason}', + owning_gate_code=owning, + severity=severity, + reason_code=stable_reason, + field_code=str(issue.get('field') or '') or None, + user_visible=severity == 'blocking', + blocks_current_action=severity == 'blocking', + details={ + **{k: v for k, v in issue.items() if k not in {'reason', 'owning_gate_code'}}, + 'raw_reason': reason, + }, + ) diff --git a/backend/app/services/shipping_notice/generic_order_gate.py b/backend/app/services/shipping_notice/generic_order_gate.py index c4d21f1b..8f998afc 100644 --- a/backend/app/services/shipping_notice/generic_order_gate.py +++ b/backend/app/services/shipping_notice/generic_order_gate.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/generic_order_gate.py 用途:通用确定性解析统一 fail-closed 门禁,产出稳定原因码与完整性摘要。 依赖:generic_order_completeness、generic_order_parser、order_extraction_route_contract。 -逻辑:parse_generic_orders 之后由 order_extraction_workflow 调用;任一阻断条件成立则禁止 generic_deterministic。 +逻辑:parse_generic_orders 之后由 order_extraction_workflow 调用;任一完整性或证据阻断条件成立则禁止 generic_deterministic。 """ from __future__ import annotations @@ -22,7 +22,6 @@ from app.services.shipping_notice.generic_order_parser import ( parse_generic_orders, ) from app.services.shipping_notice.order_extraction_route_contract import GENERIC_GATE_POLICY_VERSION -from app.services.shipping_notice.order_schema.table_contract import TABLE_FIELD_CODES @dataclass(frozen=True) @@ -52,7 +51,7 @@ def evaluate_generic_extraction_gate( unit: Any, ) -> GenericGateResult: """ - 执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与 LLM 字段。 + 执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与必填字段缺失。 核心逻辑: 1. 先构建 completeness 报告; @@ -74,8 +73,6 @@ def evaluate_generic_extraction_gate( stable_codes: list[str] = [] gate_codes.extend(_completeness_gate_codes(completeness)) - gate_codes.extend(_llm_involvement_codes(definition)) - parse_result = parse_generic_orders( candidates=candidates, definition=definition, @@ -141,28 +138,6 @@ def _completeness_gate_codes(report: GenericCompletenessReport) -> list[str]: return _dedupe(codes) -def _llm_involvement_codes(definition: dict[str, Any]) -> list[str]: - """ - 必填字段无法由表格/layout 确定性映射时必须阻断通用路径。 - - 核心逻辑:collection_mode=deterministic_context 的 Header 可来自邮件上下文; - 不在 TABLE_FIELD_CODES 的必填 Line/Header 字段意味着需要 LLM 补全。 - """ - for item in definition.get('fields') or []: - if not isinstance(item, dict) or not item.get('enabled', True) or not item.get('required'): - continue - field_code = str(item.get('field_code') or '') - collection_mode = str(item.get('collection_mode') or 'llm_extraction') - if collection_mode == 'deterministic_context': - continue - scope = str(item.get('scope') or 'line') - if scope == 'header' and field_code not in TABLE_FIELD_CODES: - return ['llm_involvement'] - if scope == 'line' and field_code not in TABLE_FIELD_CODES: - return ['llm_involvement'] - return [] - - def _map_gate_codes_to_stable(codes: list[str]) -> list[str]: """内部 gate 码映射到 STABLE_ROUTE_REASON_CODES 子集。""" mapping = { @@ -174,7 +149,6 @@ def _map_gate_codes_to_stable(codes: list[str]) -> list[str]: 'multiple_customer': 'generic_gate_blocked', 'multiple_business_tables': 'multiple_business_tables', 'missing_data_rows': 'business_table_not_found', - 'llm_involvement': 'generic_gate_blocked', 'html_table_columns_ambiguous': 'generic_gate_blocked', 'html_table_duplicate_field_columns': 'generic_gate_blocked', 'html_table_header_value_contamination': 'generic_gate_blocked', diff --git a/backend/app/services/shipping_notice/inventory_routing_engine.py b/backend/app/services/shipping_notice/inventory_routing_engine.py index 2e207817..3d966fac 100644 --- a/backend/app/services/shipping_notice/inventory_routing_engine.py +++ b/backend/app/services/shipping_notice/inventory_routing_engine.py @@ -5,6 +5,7 @@ services/shipping_notice/inventory_routing_engine.py 依赖:库存路由模型、冻结订单 Snapshot、routing_operators。 逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。 多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。 + 输出附带规则版本与命中规则摘要,供建单前重路由审计与前端展示;可用性过滤由资格服务完成。 """ from __future__ import annotations @@ -27,12 +28,14 @@ class InventoryRoutingResult: status 保留历史取值(resolved/ambiguous/unresolved/conflicted)供任务级裁决兼容; 建单资格请以 can_build / block_reason 为准——ambiguous(多候选)允许建单。 + source_codes 为规则原始候选(未做库存源启停/解析 Profile 过滤)。 """ status: str source_codes: tuple[str, ...] matched_rule_ids: tuple[int, ...] evidence: dict[str, Any] + matched_rules: tuple[dict[str, Any], ...] = () @property def can_build(self) -> bool: @@ -48,6 +51,34 @@ class InventoryRoutingResult: return 'no_inventory_source_candidates' return None + @property + def rule_versions(self) -> tuple[dict[str, Any], ...]: + """命中规则的 code+version 摘要,供重路由审计前后快照。""" + return tuple( + { + 'rule_id': int(item.get('rule_id') or 0), + 'rule_code': str(item.get('rule_code') or ''), + 'version': int(item.get('version') or 0), + } + for item in self.matched_rules + if isinstance(item, dict) + ) + + +def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[dict[str, Any], ...]: + """将命中规则折叠为可审计、可序列化的摘要元组。""" + return tuple( + { + 'rule_id': int(rule.id), + 'rule_code': str(rule.rule_code or ''), + 'version': int(rule.version or 0), + 'priority': int(rule.priority or 0), + 'action_type': str(rule.action_type or ''), + 'scope': str(rule.scope or ''), + } + for rule in rules + ) + def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any: """只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。""" @@ -105,18 +136,30 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr 将同优先级命中规则折叠为候选集合与建单资格。 核心逻辑:add/exclude 合并候选;任一 require_manual_review → conflicted 且不可建单; - 多候选标记 ambiguous 但仍 can_build。 + 多候选标记 ambiguous 但仍 can_build;同时附带规则版本与命中摘要。 """ source_codes: set[str] = set() excluded: set[str] = set() manual = False + matched = _matched_rule_summaries(top_rules) for rule in top_rules: if rule.action_type not in ALLOWED_ACTIONS: return InventoryRoutingResult( 'conflicted', (), tuple(item.id for item in top_rules), - {'reason': 'unsupported_action', 'priority': priority}, + { + 'reason': 'unsupported_action', + 'priority': priority, + 'matched_rules': [rule.rule_code for rule in top_rules], + 'matched_rule_summaries': list(matched), + 'rule_versions': list( + {'rule_id': item['rule_id'], 'rule_code': item['rule_code'], 'version': item['version']} + for item in matched + ), + 'raw_source_codes': [], + }, + matched_rules=matched, ) payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {} codes = {str(code or '').strip().upper() for code in payload.get('source_codes', []) if str(code or '').strip()} @@ -127,12 +170,23 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr else: manual = True source_codes.difference_update(excluded) + ordered = tuple(sorted(source_codes)) status = 'conflicted' if manual else ('resolved' if len(source_codes) == 1 else 'ambiguous' if source_codes else 'unresolved') return InventoryRoutingResult( status, - tuple(sorted(source_codes)), + ordered, tuple(rule.id for rule in top_rules), - {'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]}, + { + 'priority': priority, + 'matched_rules': [rule.rule_code for rule in top_rules], + 'matched_rule_summaries': list(matched), + 'rule_versions': list( + {'rule_id': item['rule_id'], 'rule_code': item['rule_code'], 'version': item['version']} + for item in matched + ), + 'raw_source_codes': list(ordered), + }, + matched_rules=matched, ) @@ -155,7 +209,7 @@ def _evaluate_with_reader(*, scope: str, value_reader, now: datetime | None = No rules = _published_rules(scope=scope, now=moment) matched = [rule for rule in rules if _rule_matches(rule, value_reader=value_reader)] if not matched: - return InventoryRoutingResult('unresolved', (), (), {'matched_rules': []}) + return InventoryRoutingResult('unresolved', (), (), {'matched_rules': [], 'raw_source_codes': [], 'rule_versions': []}) priority = matched[0].priority top_rules = [rule for rule in matched if rule.priority == priority] return _evaluate_matched_rules(top_rules, priority=priority) @@ -176,7 +230,7 @@ def evaluate_inventory_source_rules( now: 测试可注入的评估时间,默认当前 UTC 时间。 Returns: - InventoryRoutingResult: 含 status / source_codes / can_build。 + InventoryRoutingResult: 含 status / source_codes / matched_rules / can_build。 """ scope = 'line' if line is not None else 'task' return _evaluate_with_reader( diff --git a/backend/app/services/shipping_notice/order_auto_freeze_policy.py b/backend/app/services/shipping_notice/order_auto_freeze_policy.py index d8e89012..3aeecc8e 100644 --- a/backend/app/services/shipping_notice/order_auto_freeze_policy.py +++ b/backend/app/services/shipping_notice/order_auto_freeze_policy.py @@ -2,10 +2,12 @@ services/shipping_notice/order_auto_freeze_policy.py 用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。 -依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关。 +依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关; + process_gate_contract(原因唯一归属 order_freeze_readiness)。 逻辑:Run 创建时冻结初始人工确认策略;结果落库后按模板资格、通用 STP 直通路径、 技术失败、预算停止、紧急停止和复核状态刷新门禁摘要。 - 通用路径仅 route_decision=straight_through 可冻结;禁止任何 LLM 路径自动冻结。 + 通用路径仅 route_decision=straight_through 可冻结;禁止任何 LLM 路径自动冻结; + 资格、客户范围、场景范围与紧急停止统一归属 owning_gate=order_freeze_readiness。 """ from __future__ import annotations @@ -20,12 +22,17 @@ from app.models import ( ShippingOrderExtractionRouteDecision, ShippingOrderExtractionRun, ) +from app.services.shipping_notice.process_gate_contract import ( + build_process_finding, + owning_gate_for_reason, +) from app.services.shipping_notice.tool_common import ( extraction_emergency_stop_enabled, generic_auto_freeze_enabled, ) _DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order' +_OWNING_GATE = 'order_freeze_readiness' def build_initial_auto_freeze_policy(*, schema_policy_version: str | None) -> dict[str, Any]: @@ -67,11 +74,14 @@ def evaluate_run_auto_freeze_policy( # [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。 if extraction_emergency_stop_enabled(): blocking_reason_codes.append('extraction_emergency_stop') + findings = [_freeze_finding('extraction_emergency_stop')] policy.update({ 'enabled': False, 'emergency_stop': True, 'freeze_source': None, + 'owning_gate_code': _OWNING_GATE, 'blocking_reason_codes': sorted(set(blocking_reason_codes)), + 'findings': findings, 'evaluated_from_run': True, }) return policy @@ -157,11 +167,15 @@ def evaluate_run_auto_freeze_policy( if requires_customer_confirmation and freeze_source == 'profile_deterministic': blocking_reason_codes.append('customer_confirmation_required') + unique_codes = sorted(set(code for code in blocking_reason_codes if code)) + findings = [_freeze_finding(code) for code in unique_codes] + policy.update({ 'enabled': enabled, 'mode': 'auto_freeze' if enabled else 'manual_confirmation', 'freeze_source': freeze_source, 'emergency_stop': False, + 'owning_gate_code': _OWNING_GATE, 'selected_profile_id': int(selected_route.selected_profile_id) if selected_route and selected_route.selected_profile_id else None, 'selected_profile_code': str(selected_route.selected_profile_code or '') or None if selected_route else None, 'selected_profile_checksum': str(selected_route.selected_profile_checksum or '') or None if selected_route else None, @@ -174,12 +188,36 @@ def evaluate_run_auto_freeze_policy( 'business_scenario': current_business_scenario, 'business_scenario_status': business_scenario_status, 'customer_confirmation_required': requires_customer_confirmation, - 'blocking_reason_codes': sorted(set(code for code in blocking_reason_codes if code)), + 'blocking_reason_codes': unique_codes, + 'findings': findings, 'evaluated_from_run': True, }) return policy +def _freeze_finding(reason_code: str) -> dict[str, Any]: + """ + 将自动冻结原因投影为 order_freeze_readiness 所属 Finding。 + + Args: + reason_code: 稳定阻断原因码。 + + Returns: + 标准 Finding;原因未知时仍归属冻结就绪门禁。 + """ + code = str(reason_code or '').strip() or 'auto_freeze_not_enabled' + owning = owning_gate_for_reason(code) or _OWNING_GATE + return build_process_finding( + finding_code=f'auto_freeze_{code}', + owning_gate_code=owning, + severity='blocking', + reason_code=code, + user_visible=True, + blocks_current_action=True, + details={'message': '自动建单策略尚未放行'}, + ) + + def _route_contract(route: ShippingOrderExtractionRouteDecision) -> dict[str, Any]: """从 candidate_summary_json 尾部提取阶段 0 路由契约摘要。""" items = route.candidate_summary_json if isinstance(route.candidate_summary_json, list) else [] diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index 0963e4bd..e6a8e510 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -2,18 +2,22 @@ services/shipping_notice/order_build_eligibility_service.py 用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及 - 自动建单五门禁(批准模板 / 字段完整 / 证据通过 / 无冲突重复 / 质量门禁)。 + 自动建单内部检查(批准模板 / 字段完整 / 证据 / 冲突重复 / 质量门禁)。 依赖:candidate_validation、field_rules、inventory_routing_engine、inventory_source_repository、 - ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun。 + ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun、 + ShippingInventorySource、process_gate_contract(原因唯一归属)。 逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断; - 人工已选候选(含原因)可覆盖规则零候选;五门禁失败仅阻断自动建单,落入 Review Case, - 不替代人工确认路径的 can_build(库存/Reservation)门禁。 + 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; + 停用或无已发布解析 Profile 的 Source 不进入有效候选; + 旧五门禁不再平行产生用户阻断,失败映射到唯一 owning_gate Finding; + 自动冻结资格/客户范围/场景/紧急停止统一归属 order_freeze_readiness。 """ from __future__ import annotations from typing import Any +from app.models import ShippingInventorySource from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.inventory_routing_engine import ( InventoryRoutingResult, @@ -24,9 +28,13 @@ from app.services.shipping_notice.inventory_source_repository import ( list_database_inventory_sources, ) from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id +from app.services.shipping_notice.process_gate_contract import ( + AUTO_BUILD_LEGACY_GATE_OWNING_MAP, + build_process_finding, +) from app.services.shipping_notice.reservation_id import validated_reservation_id -# 自动建单五门禁稳定键;失败 → 仅 Review Case,禁止 STP 自动建单。 +# 自动建单内部检查键(仅用于 can_auto_create);禁止平行投影为五个用户阻断。 AUTO_BUILD_GATE_KEYS: tuple[str, ...] = ( 'approved_template', 'fields_complete', @@ -35,6 +43,15 @@ AUTO_BUILD_GATE_KEYS: tuple[str, ...] = ( 'quality_gate_passed', ) +# 旧五门 → 稳定原因码(用户可见阻断只折叠到冻结就绪一次)。 +_AUTO_BUILD_GATE_REASON_CODES: dict[str, str] = { + 'approved_template': 'profile_not_auto_freeze_approved', + 'fields_complete': 'required_field_missing', + 'evidence_passed': 'evidence_missing', + 'no_conflict_or_duplicate': 'duplicate_unresolved', + 'quality_gate_passed': 'auto_freeze_not_enabled', +} + def _field_id_maps( *, @@ -76,19 +93,105 @@ def _normalize_manual_codes(raw: Any) -> list[str]: return codes +def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]: + """ + 按最新启停与解析 Profile 状态拆分原始候选。 + + 核心逻辑:仅「已启用 + RPA 可读 + 已发布解析 Profile」进入 available; + 其余进入 unavailable,并给出稳定 reason 码。 + + Args: + codes: 规则或人工给出的库存源编码。 + + Returns: + available / unavailable / unavailable_reasons。 + """ + available: list[str] = [] + unavailable: list[str] = [] + reasons: dict[str, str] = {} + for code in _normalize_manual_codes(codes): + source = ShippingInventorySource.query.filter_by(source_code=code).first() + if source is None: + unavailable.append(code) + reasons[code] = 'source_not_found' + continue + if not bool(source.enabled): + unavailable.append(code) + reasons[code] = 'source_disabled' + continue + runtime = get_database_inventory_source(code, enabled_only=True) + if runtime is None: + unavailable.append(code) + reasons[code] = 'source_runtime_unavailable' + continue + parsing = source.parsing_profile + if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published': + unavailable.append(code) + reasons[code] = 'parsing_profile_unavailable' + continue + available.append(code) + return { + 'available': available, + 'unavailable': unavailable, + 'unavailable_reasons': reasons, + } + + def _validate_enabled_sources(codes: list[str]) -> tuple[list[str], list[str]]: """ - 校验库存源已启用;返回 (valid_codes, invalid_codes)。 + 校验库存源已启用且具备有效解析 Profile;返回 (valid_codes, invalid_codes)。 """ - valid: list[str] = [] - invalid: list[str] = [] - for code in codes: - source = get_database_inventory_source(code) - if source is None: - invalid.append(code) - else: - valid.append(code) - return valid, invalid + classified = classify_inventory_source_codes(codes) + return list(classified['available']), list(classified['unavailable']) + + +def _rule_suggestion_from_result(rule_result: InventoryRoutingResult) -> dict[str, Any]: + """ + 将引擎原始结果折叠为「规则建议」:过滤不可用源后重算建议状态。 + + 核心逻辑:conflicted 保留强制人工语义;其余按可用候选数映射 + resolved / ambiguous / unresolved。 + """ + raw_codes = list(rule_result.source_codes) + classified = classify_inventory_source_codes(raw_codes) + available = list(classified['available']) + unavailable = list(classified['unavailable']) + if rule_result.status == 'conflicted': + suggestion_status = 'conflicted' + suggestion_codes = available + block_reason = 'require_manual_review' + elif not available: + suggestion_status = 'unresolved' + suggestion_codes = [] + block_reason = 'no_inventory_source_candidates' + elif len(available) == 1: + suggestion_status = 'resolved' + suggestion_codes = available + block_reason = None + else: + suggestion_status = 'ambiguous' + suggestion_codes = available + block_reason = None + matched_rules = [dict(item) for item in (getattr(rule_result, 'matched_rules', None) or ())] + rule_versions = [dict(item) for item in (getattr(rule_result, 'rule_versions', None) or ())] + return { + 'source_codes': suggestion_codes, + 'raw_source_codes': raw_codes, + 'unavailable_source_codes': unavailable, + 'unavailable_reasons': dict(classified['unavailable_reasons']), + 'routing_status': suggestion_status, + 'block_reason': block_reason, + 'can_build': bool(suggestion_codes) and suggestion_status != 'conflicted', + 'matched_rule_ids': list(rule_result.matched_rule_ids), + 'matched_rules': matched_rules, + 'rule_versions': rule_versions, + 'evidence': dict(rule_result.evidence), + } + + +def _codes_equal(left: list[str] | tuple[str, ...] | None, right: list[str] | tuple[str, ...] | None) -> bool: + """比较两组库存源编码是否集合相等。""" + return set(_normalize_manual_codes(left)) == set(_normalize_manual_codes(right)) def project_line_inventory_candidates( @@ -101,21 +204,23 @@ def project_line_inventory_candidates( """ 为单条明细投影库存源候选与建单库存门禁。 - 核心逻辑:先跑行级规则;行级 unresolved 时回退任务级规则;人工选择优先于规则零候选。 + 核心逻辑:先跑行级规则;行级 unresolved 时回退任务级规则;人工选择优先于规则建议, + 重路由只更新规则建议、不静默覆盖人工决定;有效候选仅含可用库存源。 Args: fields: 冻结 Schema 字段。 header_by_code / line_by_code: 当前头/行值。 - line_meta: Draft 行上可选的 inventory_routing 人工覆盖。 + line_meta: Draft 行上可选的 inventory_routing 人工覆盖与待确认建议。 Returns: - 含 candidate_inventory_source_codes、can_build、routing_status、证据摘要的字典。 + 含有效候选、原始候选、不可用候选、规则建议与建单门禁的字典。 """ meta = line_meta if isinstance(line_meta, dict) else {} routing_overlay = meta.get('inventory_routing') if isinstance(meta.get('inventory_routing'), dict) else {} manual_codes = _normalize_manual_codes(routing_overlay.get('candidate_inventory_source_codes')) manual_reason = str(routing_overlay.get('manual_reason') or '').strip() selection_mode = str(routing_overlay.get('selection_mode') or '').strip().lower() + stored_pending = bool(routing_overlay.get('suggestion_pending')) header_ids, line_ids = _field_id_maps( fields=fields, header_by_code=header_by_code, line_by_code=line_by_code, @@ -132,56 +237,80 @@ def project_line_inventory_candidates( ) # [STEP 1] 行级有结论优先;否则用任务级规则。 rule_result: InventoryRoutingResult = line_result if line_result.status != 'unresolved' else task_result + suggestion = _rule_suggestion_from_result(rule_result) + + base_fields = { + 'raw_rule_source_codes': list(suggestion['raw_source_codes']), + 'rule_suggestion_source_codes': list(suggestion['source_codes']), + 'unavailable_source_codes': list(suggestion['unavailable_source_codes']), + 'unavailable_reasons': dict(suggestion['unavailable_reasons']), + 'matched_rule_ids': list(suggestion['matched_rule_ids']), + 'matched_rules': list(suggestion['matched_rules']), + 'rule_versions': list(suggestion['rule_versions']), + 'rule_source_codes': list(suggestion['source_codes']), + 'rule_suggestion': { + 'source_codes': list(suggestion['source_codes']), + 'raw_source_codes': list(suggestion['raw_source_codes']), + 'unavailable_source_codes': list(suggestion['unavailable_source_codes']), + 'unavailable_reasons': dict(suggestion['unavailable_reasons']), + 'routing_status': suggestion['routing_status'], + 'matched_rule_ids': list(suggestion['matched_rule_ids']), + 'matched_rules': list(suggestion['matched_rules']), + 'rule_versions': list(suggestion['rule_versions']), + }, + } if selection_mode == 'manual' and manual_codes: valid, invalid = _validate_enabled_sources(manual_codes) + suggestion_pending = stored_pending and not _codes_equal(valid, suggestion['source_codes']) if not manual_reason: return { + **base_fields, 'selection_mode': 'manual', 'candidate_inventory_source_codes': valid, 'routing_status': 'conflicted', 'can_build': False, 'block_reason': 'manual_inventory_source_reason_required', - 'matched_rule_ids': list(rule_result.matched_rule_ids), - 'rule_source_codes': list(rule_result.source_codes), 'invalid_source_codes': invalid, - 'evidence': {'manual_override': True, 'rule': rule_result.evidence}, + 'suggestion_pending': suggestion_pending, + 'evidence': {'manual_override': True, 'rule': suggestion['evidence']}, } if invalid or not valid: return { + **base_fields, 'selection_mode': 'manual', 'candidate_inventory_source_codes': valid, 'routing_status': 'unresolved', 'can_build': False, 'block_reason': 'manual_inventory_source_invalid', - 'matched_rule_ids': list(rule_result.matched_rule_ids), - 'rule_source_codes': list(rule_result.source_codes), 'invalid_source_codes': invalid, - 'evidence': {'manual_override': True, 'rule': rule_result.evidence}, + 'suggestion_pending': suggestion_pending, + 'evidence': {'manual_override': True, 'rule': suggestion['evidence']}, } return { + **base_fields, 'selection_mode': 'manual', 'candidate_inventory_source_codes': valid, 'routing_status': 'resolved' if len(valid) == 1 else 'ambiguous', 'can_build': True, 'block_reason': None, 'manual_reason': manual_reason, - 'matched_rule_ids': list(rule_result.matched_rule_ids), - 'rule_source_codes': list(rule_result.source_codes), 'invalid_source_codes': [], - 'evidence': {'manual_override': True, 'rule': rule_result.evidence}, + 'suggestion_pending': suggestion_pending, + 'evidence': {'manual_override': True, 'rule': suggestion['evidence']}, } + # [STEP 2] 无人工决定:规则建议直接成为有效结果(唯一命中即可建单)。 return { + **base_fields, 'selection_mode': 'rule', - 'candidate_inventory_source_codes': list(rule_result.source_codes), - 'routing_status': rule_result.status, - 'can_build': rule_result.can_build, - 'block_reason': rule_result.block_reason, - 'matched_rule_ids': list(rule_result.matched_rule_ids), - 'rule_source_codes': list(rule_result.source_codes), + 'candidate_inventory_source_codes': list(suggestion['source_codes']), + 'routing_status': suggestion['routing_status'], + 'can_build': bool(suggestion['can_build']), + 'block_reason': suggestion['block_reason'], 'invalid_source_codes': [], - 'evidence': dict(rule_result.evidence), + 'suggestion_pending': False, + 'evidence': dict(suggestion['evidence']), } @@ -193,10 +322,11 @@ def assess_auto_build_gates( run: Any | None = None, ) -> dict[str, Any]: """ - 评估自动建单五门禁;任一失败则只能进入 Review Case,禁止 STP 自动建单。 + 评估自动建单内部五检查;任一失败则只能进入 Review Case,禁止 STP 自动建单。 核心逻辑:批准模板读 Unit 路由;字段完整由调用方汇总;证据/冲突/重复读 Candidate; - 质量门禁读 Run 冻结的 auto_freeze_policy.enabled(经质量批次批准后才为 True)。 + 质量门禁读 Run 冻结的 auto_freeze_policy.enabled。 + 返回 findings 按 owning_gate 去重;冻结资格类原因折叠为单一 order_freeze_readiness 用户阻断。 Args: fields_complete: Schema 必填与建单字段是否已齐备。 @@ -205,7 +335,7 @@ def assess_auto_build_gates( run: 可选 ShippingOrderExtractionRun(含 auto_freeze_policy_json)。 Returns: - gates(五键 bool)、can_auto_create、failed_gates。 + gates、can_auto_create、failed_gates、findings、user_blocking_finding。 """ # [STEP 1] 批准模板:Unit 路由 auto_create_approved,或 Candidate 已 automatic 接受。 route = {} @@ -236,10 +366,16 @@ def assess_auto_build_gates( # [STEP 4] 质量门禁:Run 冻结策略 enabled=True 才视为通过;缺 Run 时视为未通过。 quality_gate_passed = False + policy_blocking_codes: list[str] = [] if run is not None: policy = getattr(run, 'auto_freeze_policy_json', None) if isinstance(policy, dict): quality_gate_passed = bool(policy.get('enabled')) + policy_blocking_codes = [ + str(code).strip() + for code in (policy.get('blocking_reason_codes') or []) + if str(code or '').strip() + ] gates = { 'approved_template': bool(approved_template), @@ -249,10 +385,65 @@ def assess_auto_build_gates( 'quality_gate_passed': bool(quality_gate_passed), } failed = [key for key in AUTO_BUILD_GATE_KEYS if not gates.get(key)] + + # [STEP 5] 映射到 owning_gate Finding;冻结类折叠为一次用户阻断。 + # 优先使用 Run policy 的具体原因码,避免被通用 auto_freeze_not_enabled 抢占。 + findings: list[dict[str, Any]] = [] + freeze_reasons: list[str] = list(policy_blocking_codes) + for key in failed: + owning = AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key, 'order_freeze_readiness') + reason = _AUTO_BUILD_GATE_REASON_CODES.get(key, 'auto_freeze_not_enabled') + if owning == 'order_freeze_readiness': + freeze_reasons.append(reason) + continue + findings.append(build_process_finding( + finding_code=f'auto_build_{key}_failed', + owning_gate_code=owning, + severity='diagnostic', + reason_code=reason, + user_visible=False, + blocks_current_action=False, + details={'legacy_auto_build_gate': key}, + )) + + # 去重保持稳定顺序(policy 原因优先) + seen_freeze: set[str] = set() + freeze_unique: list[str] = [] + for code in freeze_reasons: + if code in seen_freeze: + continue + seen_freeze.add(code) + freeze_unique.append(code) + + user_blocking_finding: dict[str, Any] | None = None + if freeze_unique or any( + key in failed for key in ('approved_template', 'quality_gate_passed') + ): + primary_reason = freeze_unique[0] if freeze_unique else 'auto_freeze_not_enabled' + user_blocking_finding = build_process_finding( + finding_code='auto_freeze_policy_not_approved', + owning_gate_code='order_freeze_readiness', + severity='blocking', + reason_code=primary_reason, + user_visible=True, + blocks_current_action=True, + details={ + 'blocking_reason_codes': freeze_unique, + 'message': '自动建单策略尚未放行', + 'legacy_failed_gates': [ + key for key in failed + if AUTO_BUILD_LEGACY_GATE_OWNING_MAP.get(key) == 'order_freeze_readiness' + ], + }, + ) + findings.append(user_blocking_finding) + return { 'gates': gates, 'failed_gates': failed, 'can_auto_create': not failed, + 'findings': findings, + 'user_blocking_finding': user_blocking_finding, } @@ -268,11 +459,11 @@ def assess_order_build_eligibility( run: Any | None = None, ) -> dict[str, Any]: """ - 汇总整单建单资格与自动建单五门禁。 + 汇总整单建单资格与自动建单内部检查。 核心逻辑:复用 Candidate 基础评估;逐行补有效 Reservation 与库存源候选门禁; - 任一阻断则 can_build=False(人工确认仍可读该门禁);五门禁失败仅置 - can_auto_create=False,强制落入 Review Case,禁止自动建单。 + 任一阻断则 can_build=False(人工确认仍可读该门禁);自动建单失败仅置 + can_auto_create=False,并投影唯一 owning_gate Finding,禁止旧五门禁平行用户阻断。 Args: fields: Schema field_id → 配置。 @@ -280,10 +471,10 @@ def assess_order_build_eligibility( lines: 行 field_code → 值列表(与 line_metas 对齐)。 line_metas: Draft 行原始对象(含 line_key / inventory_routing)。 customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。 - candidate / unit / run: 可选门禁上下文(自动建单五门)。 + candidate / unit / run: 可选门禁上下文(自动建单检查)。 Returns: - can_build、can_auto_create、gates、issues、line_projections、assessment 摘要。 + can_build、can_auto_create、gates、issues、findings、line_projections、assessment 摘要。 """ metas = list(line_metas or []) while len(metas) < len(lines): @@ -295,7 +486,11 @@ def assess_order_build_eligibility( issues: list[dict[str, Any]] = [] if not customer_resolved: - issues.append({'code': 'customer_unresolved', 'severity': 'blocking'}) + issues.append({ + 'code': 'customer_unresolved', + 'severity': 'blocking', + 'owning_gate_code': 'customer_resolution', + }) for index, line in enumerate(lines): raw_line = dict(line) if isinstance(line, dict) else {} @@ -330,6 +525,7 @@ def assess_order_build_eligibility( 'line_key': meta.get('line_key'), 'line_index': index, 'severity': 'blocking', + 'owning_gate_code': 'reservation_validation', }) if not routing.get('can_build'): issues.append({ @@ -337,7 +533,9 @@ def assess_order_build_eligibility( 'line_key': meta.get('line_key'), 'line_index': index, 'severity': 'blocking', + 'owning_gate_code': 'inventory_source_routing', 'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [], + 'unavailable_source_codes': routing.get('unavailable_source_codes') or [], }) assessment = assess_candidate_business_summary({**header_by_code, 'lines': enriched_lines}) @@ -346,9 +544,15 @@ def assess_order_build_eligibility( 'code': str(item.get('code') or 'invalid_order_line'), 'line_index': item.get('line_index'), 'severity': 'blocking', + 'owning_gate_code': 'field_completeness', }) for field_code in assessment.get('missing_required_fields') or []: - issues.append({'code': 'required_field_missing', 'field_code': field_code, 'severity': 'blocking'}) + issues.append({ + 'code': 'required_field_missing', + 'field_code': field_code, + 'severity': 'blocking', + 'owning_gate_code': 'field_completeness', + }) # 有效 Reservation 已在上方按行检查;不再用 line-only process_field_missing 重复阻断。 reservations = [ @@ -357,7 +561,11 @@ def assess_order_build_eligibility( if validated_reservation_id(item.get('effective_reservation_id')) ] if len(reservations) != len(set(reservations)): - issues.append({'code': 'reservation_duplicated_in_order', 'severity': 'blocking'}) + issues.append({ + 'code': 'reservation_duplicated_in_order', + 'severity': 'blocking', + 'owning_gate_code': 'reservation_validation', + }) can_build = ( bool(customer_resolved) @@ -372,7 +580,7 @@ def assess_order_build_eligibility( and not assessment.get('invalid_lines') and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues) ) - # [STEP] 五门禁:失败只阻断自动建单,不改写人工确认 can_build。 + # [STEP] 自动建单检查:失败只阻断自动建单;用户投影折叠到唯一 owning_gate。 gate_result = assess_auto_build_gates( fields_complete=fields_complete and can_build, candidate=candidate, @@ -380,13 +588,18 @@ def assess_order_build_eligibility( run=run, ) can_auto_create = bool(can_build and gate_result.get('can_auto_create')) - if not gate_result.get('can_auto_create'): - for gate_key in gate_result.get('failed_gates') or []: - issues.append({ - 'code': f'auto_build_gate_{gate_key}', - 'severity': 'auto_create_blocking', - 'gate': gate_key, - }) + findings = list(gate_result.get('findings') or []) + # 禁止再写 auto_build_gate_* 平行用户阻断;仅保留一条冻结就绪用户 Finding。 + user_finding = gate_result.get('user_blocking_finding') + if user_finding and can_build and not can_auto_create: + issues.append({ + 'code': 'auto_freeze_policy_not_approved', + 'severity': 'auto_create_blocking', + 'owning_gate_code': 'order_freeze_readiness', + 'reason_code': user_finding.get('reason_code'), + 'finding_code': user_finding.get('finding_code'), + 'message': '自动建单策略尚未放行', + }) enabled_codes = [ str(item.get('source_code') or '').strip().upper() @@ -398,6 +611,8 @@ def assess_order_build_eligibility( 'can_auto_create': can_auto_create, 'gates': dict(gate_result.get('gates') or {}), 'failed_gates': list(gate_result.get('failed_gates') or []), + 'findings': findings, + 'user_blocking_finding': user_finding, 'status': 'ready' if can_build else 'needs_review', 'issues': issues, 'line_projections': line_projections, @@ -440,10 +655,153 @@ def apply_manual_inventory_candidates( valid, invalid = _validate_enabled_sources(codes) if invalid or not valid: raise ValueError('manual_inventory_source_invalid') + previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {} overlay = { 'selection_mode': 'manual', 'candidate_inventory_source_codes': valid, 'manual_reason': text, + # 人工改选后清除待确认建议,避免静默与旧建议混用。 + 'suggestion_pending': False, + } + if isinstance(previous.get('rule_suggestion'), dict): + overlay['rule_suggestion'] = previous.get('rule_suggestion') + line_meta['inventory_routing'] = overlay + return overlay + + +def apply_rule_suggestion_as_effective( + *, + line_meta: dict[str, Any], + suggestion: dict[str, Any], + reason: str, +) -> dict[str, Any]: + """ + 将规则建议采用为当前有效候选(明确动作,非静默覆盖)。 + + 核心逻辑:写入 selection_mode=rule 的有效编码;记录 adopt 动作语义与原因; + 清除 suggestion_pending。 + + Args: + line_meta: Draft 行对象。 + suggestion: 规则建议片段(须含 source_codes)。 + reason: 采用原因或动作说明。 + + Returns: + 更新后的 inventory_routing。 + + Raises: + ValueError: 建议无效。 + """ + codes = _normalize_manual_codes(suggestion.get('source_codes')) + text = str(reason or '').strip() or 'adopt_rule_suggestion' + if not codes: + raise ValueError('rule_suggestion_empty') + valid, invalid = _validate_enabled_sources(codes) + if invalid or not valid: + raise ValueError('rule_suggestion_invalid') + overlay = { + 'selection_mode': 'rule', + 'candidate_inventory_source_codes': valid, + 'manual_reason': text, + 'adopted_from_rule': True, + 'suggestion_pending': False, + 'rule_suggestion': { + 'source_codes': valid, + 'raw_source_codes': list(suggestion.get('raw_source_codes') or valid), + 'unavailable_source_codes': list(suggestion.get('unavailable_source_codes') or []), + 'unavailable_reasons': dict(suggestion.get('unavailable_reasons') or {}), + 'routing_status': str( + suggestion.get('routing_status') or ('resolved' if len(valid) == 1 else 'ambiguous') + ), + 'matched_rule_ids': list(suggestion.get('matched_rule_ids') or []), + 'matched_rules': list(suggestion.get('matched_rules') or []), + 'rule_versions': list(suggestion.get('rule_versions') or []), + }, } line_meta['inventory_routing'] = overlay return overlay + + +def mark_keep_manual_inventory_decision( + *, + line_meta: dict[str, Any], + reason: str, +) -> dict[str, Any]: + """ + 明确保留人工库存源决定并拒绝当前规则建议。 + + Args: + line_meta: Draft 行对象(须已有 manual 覆盖)。 + reason: 保留原因或动作说明。 + + Returns: + 更新后的 inventory_routing。 + + Raises: + ValueError: 当前无人工决定。 + """ + previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {} + if str(previous.get('selection_mode') or '').strip().lower() != 'manual': + raise ValueError('manual_inventory_decision_missing') + codes = _normalize_manual_codes(previous.get('candidate_inventory_source_codes')) + if not codes: + raise ValueError('manual_inventory_decision_missing') + text = str(reason or '').strip() or 'keep_manual_inventory_decision' + overlay = { + **previous, + 'selection_mode': 'manual', + 'candidate_inventory_source_codes': codes, + 'suggestion_pending': False, + 'rejected_rule_suggestion': previous.get('rule_suggestion'), + 'keep_manual_reason': text[:500], + } + line_meta['inventory_routing'] = overlay + return overlay + + +def attach_rule_suggestion_without_override( + *, + line_meta: dict[str, Any], + suggestion: dict[str, Any], +) -> dict[str, Any]: + """ + 重路由后写入规则建议;若存在人工决定则不覆盖有效候选。 + + 核心逻辑:人工决定存在时仅更新 rule_suggestion 与 suggestion_pending; + 无人工决定时清除残留覆盖层,有效结果由实时规则投影得出。 + + Args: + line_meta: Draft 行对象。 + suggestion: 最新规则建议。 + + Returns: + 更新后的 inventory_routing;无人工决定时返回空 dict。 + """ + previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {} + suggestion_payload = { + 'source_codes': list(suggestion.get('source_codes') or []), + 'raw_source_codes': list(suggestion.get('raw_source_codes') or []), + 'unavailable_source_codes': list(suggestion.get('unavailable_source_codes') or []), + 'unavailable_reasons': dict(suggestion.get('unavailable_reasons') or {}), + 'routing_status': str(suggestion.get('routing_status') or 'unresolved'), + 'matched_rule_ids': list(suggestion.get('matched_rule_ids') or []), + 'matched_rules': list(suggestion.get('matched_rules') or []), + 'rule_versions': list(suggestion.get('rule_versions') or []), + } + selection_mode = str(previous.get('selection_mode') or '').strip().lower() + manual_codes = _normalize_manual_codes(previous.get('candidate_inventory_source_codes')) + if selection_mode == 'manual' and manual_codes: + pending = not _codes_equal(manual_codes, suggestion_payload['source_codes']) + overlay = { + **previous, + 'selection_mode': 'manual', + 'candidate_inventory_source_codes': manual_codes, + 'rule_suggestion': suggestion_payload, + 'suggestion_pending': pending, + } + line_meta['inventory_routing'] = overlay + return overlay + + if previous: + line_meta.pop('inventory_routing', None) + return {} diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index 84ab2077..f010a587 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -4,11 +4,11 @@ backend/app/services/shipping_notice/order_extraction_run_service.py 用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。 依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务、 order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、 - workflow_ledger_service(物化后幂等建 WorkflowItem)。 + workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)。 逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run; 同会话跨上传批次的完整附件内容指纹相同时,复用活跃或待处理 Workflow Item,避免重复 Workflow; progress_ready_extraction_unit 供 Worker 在每 PDF candidate_ready 后立即落库并推进; - Document 物化后立即 ensure WorkflowItem,使版面阶段即有 Item(解决 Run>0 / Item=0)。 + Document 物化后立即 ensure WorkflowItem 与 Process Execution,使版面阶段即有 Item 与 Gate。 """ from __future__ import annotations @@ -407,11 +407,9 @@ def _build_snapshot( and isinstance(document.order_extraction_result_json, dict) else None ) - # [STEP 1] 按本 Run 冻结 Schema 重建正文补充事实。上传阶段的预解析 - # 可能使用较早 Schema;优先复用 Intake 保存的 HTML 表,避免表格展平后丢失列关系。 - if document.document_type == 'email_body' and ( - not isinstance(email_supplement, dict) or not list(email_supplement.get('rows') or []) - ): + # [STEP 1] 按本 Run 冻结 Schema 重建正文补充事实。上传阶段的部分解析 + # 可能使用较早 Schema,不能因已有部分行而遮蔽新增表头别名。 + if document.document_type == 'email_body': intake = next((item for item in intakes if int(item.id) == int(document.intake_id)), None) structured = intake.structured_result_json if intake and isinstance(intake.structured_result_json, dict) else {} email = structured.get('email') if isinstance(structured.get('email'), dict) else {} @@ -422,13 +420,14 @@ def _build_snapshot( content_hash=str(document.content_hash or ''), schema_definition=dict(schema_version.definition_json or {}), ) - else: + elif not isinstance(email_supplement, dict) or not list(email_supplement.get('rows') or []): email_supplement = parse_email_allocation_text( body_text=str(document.extracted_text or ''), content_hash=str(document.content_hash or ''), schema_definition=dict(schema_version.definition_json or {}), ) - email_supplement['document_id'] = int(document.id) + if isinstance(email_supplement, dict): + email_supplement['document_id'] = int(document.id) documents_by_intake[document.intake_id].append({ 'document_id': document.id, 'document_type': document.document_type, @@ -682,6 +681,32 @@ def ensure_workflow_items_for_run( actor_id=run.user_id, reason='ensure_workflow_items_for_run', ) + # [STEP] 幂等创建 Process Execution;Gate 为业务真相,Workflow 仅聚合。 + try: + from app.services.shipping_notice.process_gate_bridge import ( + ensure_execution_for_workflow_item, + sync_early_pipeline_gates, + ) + + execution = ensure_execution_for_workflow_item( + item, + actor_type='system', + actor_id=run.user_id, + start_gate_code='document_materialization', + ) + if execution is not None: + sync_early_pipeline_gates( + execution=execution, + layouts_ready=not layouts_pending, + actor_type='system', + actor_id=run.user_id, + ) + except Exception: + _LOGGER.exception( + 'ensure process execution failed run_no=%s item_id=%s', + run.run_no, + getattr(item, 'id', None), + ) items.append(item) except Exception: _LOGGER.exception( @@ -1032,6 +1057,7 @@ def create_order_extraction_run( reparse_comment: str | None = None, selected_document_id: int | None = None, reparse_case_no: str | None = None, + reparse_attempt_no: int = 0, ) -> tuple[ShippingOrderExtractionRun, bool]: """ 创建订单抽取 Run;相同服务器快照幂等复用,不同输入抢占同一 Intake 时返回冲突。 @@ -1046,6 +1072,7 @@ def create_order_extraction_run( reparse_reason/reparse_comment: 用户选择的重识别原因及可选备注,仅用于审计。 selected_document_id: 指定时只冻结该附件;仅供 PDF 级重识别使用,禁止扩大为同邮件全量附件。 reparse_case_no: 可选来源复核 Case 编号;仅作为 PDF 级版本谱系的冻结审计标识。 + reparse_attempt_no: 同一 Case 失败后的重试序号;只参与幂等边界,不改变来源版本谱系。 Returns: `(run, reused)`;Run 与通用 Job 在同一事务创建。 """ @@ -1137,6 +1164,8 @@ def create_order_extraction_run( 'document_id': int(selected_document_id), 'source_case_no': str(reparse_case_no or '').strip().upper() or None, } + if int(reparse_attempt_no or 0) > 0: + snapshot['review_reparse']['attempt_no'] = int(reparse_attempt_no) snapshot_hash = _sha256(snapshot) idempotency_key = _sha256({ 'user_id': user.id, @@ -1150,6 +1179,7 @@ def create_order_extraction_run( 'reparse_of_run_id': reparse_of_run.id if reparse_of_run is not None else None, 'selected_document_id': selected_document_id, 'reparse_case_no': str(reparse_case_no or '').strip().upper() or None, + 'reparse_attempt_no': int(reparse_attempt_no or 0), }) existing = _run_by_idempotency_key(idempotency_key) if existing is not None: diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 5c119aff..0ff7e7df 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -4,12 +4,12 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py 用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。 依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、stp_inventory_freeze、 customer_auto_resolution、fulfillment_audit、order_review_progress_bridge、 - workflow_ledger_service、progress_workflow.auto_progress。 + workflow_ledger_service、progress_workflow.auto_progress、process_gate_bridge。 逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与 可自动确认的客户;物化人工 Candidate 与 accepted Extraction(保留派生 field_lineage); 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 - building_order(不关闭);API commit 后触发 auto_progress(库存源已冻结时跳过 - inventory_source_review),止于 manual_upload_pending。 + building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, + 避免重复冻结资格阻断;API commit 后触发 auto_progress,止于 manual_upload_pending。 """ from __future__ import annotations @@ -896,6 +896,10 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A actor_type='user', actor_id=user_id, ) + # [STEP] 统一门禁:绑定 Task,推进至 task_creation,避免重复冻结资格阻断。 + from app.services.shipping_notice.process_gate_bridge import sync_execution_after_review_confirm + + sync_execution_after_review_confirm(case=case, task=task, actor_id=int(user_id)) log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None}) db.session.flush() workflow_refs = _workflow_refs_for_case(case) diff --git a/backend/app/services/shipping_notice/process_gate_access_service.py b/backend/app/services/shipping_notice/process_gate_access_service.py new file mode 100644 index 00000000..0d13d30c --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_access_service.py @@ -0,0 +1,205 @@ +""" +services/shipping_notice/process_gate_access_service.py + +用途:全门禁恢复 API 的可见性与写权限校验,并在 403 时写入 process_gate_permission_denied 审计。 +依赖:ShippingProcessExecution、ShippingTask、ShippingOrderReviewCase、 + ShippingNoticeWorkflowItem / ShippingNoticeWorkflow、User.agents、fulfillment_audit。 +逻辑:Workspace 路由调用 assert_execution_visible_to_user;读路径允许 owner / admin / + 同 Workflow.owner_agent 授权人员;写路径仅 owner / admin;Admin 路由由 @require_admin 保护; + 拒绝访问时记录审计后抛出 ForbiddenError(SHIPPING.PROCESS_GATE_PERMISSION_DENIED)。 +""" + +from __future__ import annotations + +from app import db +from app.core.errors import ForbiddenError +from app.models import ( + ShippingNoticeWorkflow, + ShippingNoticeWorkflowItem, + ShippingOrderReviewCase, + ShippingProcessExecution, + ShippingTask, + User, +) +from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit + + +def is_shipping_admin(user: User) -> bool: + """货代管理员:当前仓库以 platform admin 角色表示 shipping admin 能力。""" + return str(getattr(user, 'role', '') or '').lower() == 'admin' + + +def resolve_execution_owner_user_ids(execution: ShippingProcessExecution) -> set[int]: + """ + 解析 Execution 关联的业务属主用户 ID 集合。 + + 核心逻辑:Task 创建者、Review Case owner、WorkflowItem owner 任一匹配即视为 owner。 + """ + owners: set[int] = set() + if execution.task_id is not None: + task = db.session.get(ShippingTask, int(execution.task_id)) + if task is not None and task.user_id is not None: + owners.add(int(task.user_id)) + if execution.review_case_id is not None: + case = db.session.get(ShippingOrderReviewCase, int(execution.review_case_id)) + if case is not None and case.owner_user_id is not None: + owners.add(int(case.owner_user_id)) + item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id)) + if item is not None and item.owner_user_id is not None: + owners.add(int(item.owner_user_id)) + return owners + + +def user_has_agent_authorization(user: User, execution: ShippingProcessExecution) -> bool: + """ + 判断用户是否为 Workflow 所属 Agent 的授权人员(契约「其他授权人员」只读路径)。 + + 核心逻辑:经 WorkflowItem → ShippingNoticeWorkflow.owner_agent_id, + 若该 Agent 落在 user.agents 中即视为授权;未绑定 Agent 时不开放此路径。 + + Args: + user: 当前登录用户。 + execution: 目标 Execution。 + + Returns: + True 表示可只读查看;不等于可恢复写权限。 + """ + item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id)) + if item is None or item.workflow_id is None: + return False + workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id)) + if workflow is None or workflow.owner_agent_id is None: + return False + agent_id = int(workflow.owner_agent_id) + agents = getattr(user, 'agents', None) or [] + for agent in agents: + if agent is not None and int(getattr(agent, 'id', 0) or 0) == agent_id: + return True + return False + + +def user_may_read_execution(user: User, execution: ShippingProcessExecution) -> bool: + """ + 当前用户是否可读 Execution。 + + 核心逻辑:admin / owner / 同 Agent 授权人员。 + """ + if is_shipping_admin(user): + return True + if int(user.id) in resolve_execution_owner_user_ids(execution): + return True + return user_has_agent_authorization(user, execution) + + +def user_may_write_execution(user: User, execution: ShippingProcessExecution) -> bool: + """ + 当前用户是否可对 Execution 发起恢复写操作。 + + 核心逻辑:仅 admin 或业务 owner;授权人员默认只读。 + """ + if is_shipping_admin(user): + return True + return int(user.id) in resolve_execution_owner_user_ids(execution) + + +def user_may_access_execution(user: User, execution: ShippingProcessExecution) -> bool: + """ + 兼容旧调用:等价于可读权限。 + + 写路径请使用 user_may_write_execution 或 assert_execution_visible_to_user(write=True)。 + """ + return user_may_read_execution(user, execution) + + +def assert_execution_visible_to_user( + user: User, + execution: ShippingProcessExecution, + *, + write: bool = False, + gate_code: str | None = None, +) -> None: + """ + 校验 Workspace 用户对 Execution 的读/写权限。 + + Args: + user: 当前登录用户。 + execution: 目标 Execution。 + write: True 表示 POST 恢复等写路径(仅 owner/admin);False 为读路径 + (owner/admin/同 Agent 授权人员)。 + gate_code: 可选,用于权限拒绝审计上下文。 + + Raises: + ForbiddenError: 无权访问,并已写入 process_gate_permission_denied 审计。 + """ + allowed = user_may_write_execution(user, execution) if write else user_may_read_execution(user, execution) + if allowed: + return + _record_permission_denied( + user=user, + execution=execution, + gate_code=gate_code, + write=write, + ) + raise ForbiddenError( + 'Process gate access denied', + code='SHIPPING.PROCESS_GATE_PERMISSION_DENIED', + ) + + +def _record_permission_denied( + *, + user: User, + execution: ShippingProcessExecution, + gate_code: str | None, + write: bool, +) -> None: + """ + 写入 process_gate_permission_denied 审计并提交。 + + 核心逻辑:权限拒绝必须落库;审计失败向上抛出(禁止静默忽略后仍返回普通 403)。 + """ + item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id)) + task_no = None + if execution.task_id is not None: + task = db.session.get(ShippingTask, int(execution.task_id)) + task_no = str(task.task_no) if task is not None else None + record_fulfillment_audit( + event_type='process_gate_permission_denied', + aggregate_type='process_execution', + aggregate_id=str(execution.execution_no), + action='write' if write else 'read', + actor_type='user', + actor_id=int(user.id), + workflow_item_id=str(item.item_no) if item is not None else None, + task_no=task_no, + result='rejected', + error_code='SHIPPING.PROCESS_GATE_PERMISSION_DENIED', + metadata={ + 'execution_no': execution.execution_no, + 'gate_code': str(gate_code or ''), + 'write': bool(write), + }, + source='process_gate', + strict=True, + ) + # [STEP] 403 路径不会走到业务成功提交,此处单独提交以保证拒绝审计落库。 + db.session.commit() + + +def execution_audit_scope_keys(execution: ShippingProcessExecution) -> dict[str, str | None]: + """ + 构造 Execution 相关审计查询键。 + + Returns: + workflow_item_id(item_no)、task_no、execution_no 前缀等。 + """ + item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id)) + task_no = None + if execution.task_id is not None: + task = db.session.get(ShippingTask, int(execution.task_id)) + task_no = str(task.task_no) if task is not None else None + return { + 'workflow_item_id': str(item.item_no) if item is not None else None, + 'task_no': task_no, + 'execution_no': str(execution.execution_no), + } diff --git a/backend/app/services/shipping_notice/process_gate_api_service.py b/backend/app/services/shipping_notice/process_gate_api_service.py new file mode 100644 index 00000000..2d38426d --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_api_service.py @@ -0,0 +1,326 @@ +""" +services/shipping_notice/process_gate_api_service.py + +用途:Phase 5 统一恢复 API 的查询与序列化(Workspace / Admin 共用)。 +依赖:ShippingProcessExecution/Gate/Attempt、process_gate_projection、process_gate_access_service、 + audit_query_service、progress_audit_contract。 +逻辑:Workspace 路由委托用户安全投影;Admin 路由返回诊断投影与 Attempt 列表; + 审计事件按 Execution 关联键过滤 PROCESS_GATE_AUDIT_EVENT_TYPES。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from sqlalchemy import or_ + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + ShippingAuditEvent, + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, + ShippingTask, +) +from app.services.shipping_notice.audit_query_service import serialize_shipping_audit_event +from app.services.shipping_notice.process_gate_access_service import execution_audit_scope_keys +from app.services.shipping_notice.process_gate_projection import ( + project_admin_gate_diagnostics, + project_workbench_gate_summary, + serialize_gate_attempt, + serialize_process_execution, + serialize_process_gate, +) +from app.services.shipping_notice.progress_audit_contract import PROCESS_GATE_AUDIT_EVENT_TYPES + + +def _parse_iso_datetime(value: str | None, *, field: str) -> datetime | None: + """解析可选 ISO8601 时间;非法值抛 ValidationError。""" + raw = str(value or '').strip() + if not raw: + return None + try: + return datetime.fromisoformat(raw.replace('Z', '+00:00')).replace(tzinfo=None) + except ValueError as exc: + raise ValidationError(f'{field} must be ISO8601 datetime') from exc + + +def _snapshot_key_diff(before: Any, after: Any) -> dict[str, Any]: + """ + 计算两个快照字典的浅层键差,供管理员 Attempt Diff 使用。 + + Returns: + added / removed / changed 键列表;非 dict 输入返回 empty。 + """ + left = before if isinstance(before, dict) else {} + right = after if isinstance(after, dict) else {} + left_keys = set(left.keys()) + right_keys = set(right.keys()) + changed = sorted( + key for key in (left_keys & right_keys) + if left.get(key) != right.get(key) + ) + return { + 'added': sorted(right_keys - left_keys), + 'removed': sorted(left_keys - right_keys), + 'changed': changed, + } + + +def serialize_execution_admin_summary(execution: ShippingProcessExecution) -> dict[str, Any]: + """管理员列表行:不含 Gate 正文快照;附当前 Gate 阻断原因便于筛选回显。""" + current_gate = None + if execution.current_gate_code: + current_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code=str(execution.current_gate_code), + ).first() + task_no = None + if execution.task_id is not None: + task = db.session.get(ShippingTask, int(execution.task_id)) + task_no = str(task.task_no) if task is not None else None + return { + 'execution_no': execution.execution_no, + 'status': execution.status, + 'current_gate_code': execution.current_gate_code, + 'primary_next_action_code': execution.primary_next_action_code, + 'responsible_party': execution.responsible_party, + 'blocking_reason_code': current_gate.blocking_reason_code if current_gate else None, + 'task_no': task_no, + 'workflow_item_id': int(execution.workflow_item_id), + 'workflow_item_version_id': int(execution.workflow_item_version_id), + 'review_case_id': int(execution.review_case_id) if execution.review_case_id else None, + 'task_id': int(execution.task_id) if execution.task_id else None, + 'lock_version': int(execution.lock_version), + 'updated_at': execution.updated_at.isoformat() if execution.updated_at else None, + } + + +def list_admin_process_executions( + *, + page: int = 1, + page_size: int = 25, + status: str | None = None, + gate_code: str | None = None, + blocking_reason_code: str | None = None, + responsible_party: str | None = None, + q: str | None = None, + updated_from: str | None = None, + updated_to: str | None = None, +) -> dict[str, Any]: + """ + 分页列出 Process Execution 管理员摘要(支持运维筛选)。 + + Args: + page / page_size: 分页。 + status: Execution 状态。 + gate_code: 当前 Gate 编码。 + blocking_reason_code: 当前 Gate 阻断原因码。 + responsible_party: 责任方。 + q: 模糊搜索 execution_no / task_no。 + updated_from / updated_to: 更新时间闭区间(ISO8601)。 + + Returns: + items / total / page / page_size。 + """ + safe_page = max(1, int(page or 1)) + safe_page_size = min(100, max(1, int(page_size or 25))) + query = ShippingProcessExecution.query + if status: + query = query.filter(ShippingProcessExecution.status == str(status).strip()) + if gate_code: + query = query.filter(ShippingProcessExecution.current_gate_code == str(gate_code).strip()) + if responsible_party: + query = query.filter( + ShippingProcessExecution.responsible_party == str(responsible_party).strip(), + ) + if blocking_reason_code: + reason = str(blocking_reason_code).strip() + query = ( + query.join( + ShippingProcessGate, + db.and_( + ShippingProcessGate.execution_id == ShippingProcessExecution.id, + ShippingProcessGate.gate_code == ShippingProcessExecution.current_gate_code, + ), + ) + .filter(ShippingProcessGate.blocking_reason_code == reason) + ) + start_at = _parse_iso_datetime(updated_from, field='updated_from') + end_at = _parse_iso_datetime(updated_to, field='updated_to') + if start_at is not None: + query = query.filter(ShippingProcessExecution.updated_at >= start_at) + if end_at is not None: + query = query.filter(ShippingProcessExecution.updated_at <= end_at) + keyword = str(q or '').strip() + if keyword: + like = f'%{keyword}%' + task_ids = [ + int(row.id) + for row in ShippingTask.query.filter(ShippingTask.task_no.ilike(like)).limit(200).all() + ] + filters = [ShippingProcessExecution.execution_no.ilike(like)] + if task_ids: + filters.append(ShippingProcessExecution.task_id.in_(task_ids)) + query = query.filter(or_(*filters)) + total = query.count() + rows = ( + query.order_by(ShippingProcessExecution.updated_at.desc(), ShippingProcessExecution.id.desc()) + .offset((safe_page - 1) * safe_page_size) + .limit(safe_page_size) + .all() + ) + return { + 'items': [serialize_execution_admin_summary(row) for row in rows], + 'total': total, + 'page': safe_page, + 'page_size': safe_page_size, + } + + +def get_workspace_process_execution(execution: ShippingProcessExecution) -> dict[str, Any]: + """Workspace GET execution:工作台安全投影。""" + return project_workbench_gate_summary(execution) + + +def list_workspace_process_gates(execution: ShippingProcessExecution) -> dict[str, Any]: + """Workspace GET gates:用户安全 Gate 列表。""" + payload = serialize_process_execution(execution, include_diagnostics=False) + return { + 'execution_no': payload.get('execution_no'), + 'gates': payload.get('gates') or [], + } + + +def list_workspace_process_gate_audit_events( + execution: ShippingProcessExecution, + *, + page: int = 1, + page_size: int = 50, +) -> dict[str, Any]: + """ + 按 Execution 关联键分页返回 PROCESS_GATE 审计事件(用户可见字段,不含敏感快照正文)。 + + Args: + execution: 已校验可见性的 Execution。 + page / page_size: 分页参数。 + + Returns: + items / total / page / page_size。 + """ + safe_page = max(1, int(page or 1)) + safe_page_size = min(100, max(1, int(page_size or 50))) + scope = execution_audit_scope_keys(execution) + prefix = f"{scope['execution_no']}:" + filters = [ShippingAuditEvent.event_type.in_(tuple(PROCESS_GATE_AUDIT_EVENT_TYPES))] + association_filters = [ShippingAuditEvent.aggregate_id.like(f'{prefix}%')] + if scope.get('workflow_item_id'): + association_filters.append( + ShippingAuditEvent.workflow_item_id == scope['workflow_item_id'], + ) + if scope.get('task_no'): + association_filters.append(ShippingAuditEvent.task_no == scope['task_no']) + query = ShippingAuditEvent.query.filter(*filters).filter(or_(*association_filters)) + total = query.count() + rows = ( + query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc()) + .offset((safe_page - 1) * safe_page_size) + .limit(safe_page_size) + .all() + ) + return { + 'items': [serialize_shipping_audit_event(row, include_snapshots=False) for row in rows], + 'total': total, + 'page': safe_page, + 'page_size': safe_page_size, + } + + +def get_admin_process_execution(execution: ShippingProcessExecution) -> dict[str, Any]: + """Admin GET execution:完整诊断投影。""" + return project_admin_gate_diagnostics(execution) + + +def _gate_for_execution(execution: ShippingProcessExecution, gate_code: str) -> ShippingProcessGate: + """按 execution + gate_code 定位 Gate;不存在抛 NotFound。""" + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code=str(gate_code or '').strip(), + ).first() + if gate is None: + raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + return gate + + +def list_admin_gate_attempts( + execution: ShippingProcessExecution, + gate_code: str, +) -> dict[str, Any]: + """Admin GET gate attempts:按 attempt_no 降序返回 Attempt 摘要与相对上一 Attempt 的浅 Diff。""" + gate = _gate_for_execution(execution, gate_code) + attempts = ( + ShippingProcessGateAttempt.query + .filter_by(gate_id=int(gate.id)) + .order_by(ShippingProcessGateAttempt.attempt_no.desc()) + .all() + ) + # 同时返回 items(契约)与 attempts(前端兼容别名),避免管理端空列表。 + serialized: list[dict[str, Any]] = [] + ascending = list(reversed(attempts)) + previous: ShippingProcessGateAttempt | None = None + by_id_diff: dict[int, dict[str, Any]] = {} + for item in ascending: + if previous is not None: + by_id_diff[int(item.id)] = { + 'previous_attempt_no': int(previous.attempt_no), + 'input': _snapshot_key_diff(previous.input_snapshot_json, item.input_snapshot_json), + 'output': _snapshot_key_diff(previous.output_snapshot_json, item.output_snapshot_json), + 'input_hash_changed': previous.input_snapshot_hash != item.input_snapshot_hash, + 'output_hash_changed': previous.output_snapshot_hash != item.output_snapshot_hash, + } + previous = item + for item in attempts: + row = serialize_gate_attempt(item, include_snapshots=True) or {} + row['snapshot_diff'] = by_id_diff.get(int(item.id)) + row['audit_query'] = { + 'execution_no': execution.execution_no, + 'gate_code': gate.gate_code, + 'attempt_id': int(item.id), + 'event_type_prefix': 'process_gate_', + } + serialized.append(row) + return { + 'execution_no': execution.execution_no, + 'gate_code': gate.gate_code, + 'gate': serialize_process_gate(gate, include_diagnostics=True), + 'items': serialized, + 'attempts': serialized, + } + + +def get_admin_gate_attempt(attempt_id: int) -> dict[str, Any]: + """ + Admin GET attempt by id:含 Gate / Execution 上下文与 Attempt 摘要。 + + Raises: + NotFoundError: Attempt 不存在。 + """ + attempt = db.session.get(ShippingProcessGateAttempt, int(attempt_id)) + if attempt is None: + raise NotFoundError( + 'Process gate attempt not found', + code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND', + ) + 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') + execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) + payload = serialize_gate_attempt(attempt) or {} + payload['gate_code'] = gate.gate_code if gate else None + payload['execution_no'] = execution.execution_no if execution else None + if gate is not None: + payload['gate_status'] = gate.status + payload['gate_evaluation_version'] = int(gate.evaluation_version) + return payload diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py new file mode 100644 index 00000000..b75d885e --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -0,0 +1,648 @@ +""" +services/shipping_notice/process_gate_bridge.py + +用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、 + 将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。 +依赖:process_gate_service、process_gate_contract、ShippingProcessExecution、 + ShippingNoticeWorkflowItem、ShippingOrderReviewCase、ShippingTask。 +逻辑:由 order_extraction_run_service / order_review_confirmation_service / + order_review_draft_service / progress_workflow / process_gate_executor 调用; + 禁止业务代码直接改 Gate.status。 +""" + +from __future__ import annotations + +import hashlib +import json +import logging +from typing import Any + +from app.models import ( + ShippingNoticeWorkflowItem, + ShippingOrderReviewCase, + ShippingProcessExecution, + ShippingProcessGate, + ShippingTask, +) +from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES +from app.services.shipping_notice.process_gate_service import ( + bind_execution_task, + ensure_execution_for_workflow_version, + sync_gate_from_business_result, +) + +_LOGGER = logging.getLogger(__name__) + + +def _stable_fingerprint(value: Any) -> str: + """对业务输入快照生成稳定指纹。""" + encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(encoded.encode('ascii')).hexdigest() + + +def ensure_execution_for_workflow_item( + item: ShippingNoticeWorkflowItem, + *, + review_case_id: int | None = None, + task_id: int | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, + start_gate_code: str = 'document_materialization', +) -> ShippingProcessExecution | None: + """ + 为 WorkflowItem 当前 Version 幂等创建 Process Execution。 + + 核心逻辑:无 current_version_id 时跳过;已存在则绑定 case/task 指针。 + + Args: + item: WorkflowItem。 + review_case_id / task_id: 可选业务指针。 + actor_type / actor_id: 创建审计主体。 + start_gate_code: 首个待执行门禁。 + + Returns: + Execution;无法创建时 None。 + """ + version_id = getattr(item, 'current_version_id', None) + if version_id is None: + return None + case_id = review_case_id + if case_id is None and getattr(item, 'current_case_id', None): + case_id = int(item.current_case_id) + return ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version_id), + review_case_id=int(case_id) if case_id else None, + task_id=int(task_id) if task_id else None, + actor_type=actor_type, + actor_id=actor_id, + start_gate_code=start_gate_code, + ) + + +def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExecution | None: + """ + 按 ReviewCase 查找绑定的 Execution(优先 review_case_id,其次 WorkflowItem Version)。 + + Returns: + 最新匹配的 Execution 或 None。 + """ + by_case = ( + ShippingProcessExecution.query + .filter_by(review_case_id=int(case.id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if by_case is not None: + return by_case + from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case + + item = find_item_by_current_case(case_id=int(case.id)) + if item is None or not item.current_version_id: + return None + return ( + ShippingProcessExecution.query + .filter_by(workflow_item_version_id=int(item.current_version_id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + + +def find_execution_for_task(task: ShippingTask) -> ShippingProcessExecution | None: + """按 Task 查找绑定的 Execution。""" + return ( + ShippingProcessExecution.query + .filter_by(task_id=int(task.id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + + +def apply_gate_outcome( + *, + execution: ShippingProcessExecution, + gate_code: str, + passed: bool, + effective_result: dict[str, Any] | None = None, + recommendation: dict[str, Any] | None = None, + blocking_reason_code: str | None = None, + blocking_reason_json: dict[str, Any] | None = None, + input_fingerprint: str | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, + idempotency_key: str | None = None, + invalidate_change_type: str | None = None, + force: bool = False, + outcome: str | None = None, +) -> ShippingProcessGate | None: + """ + 将业务评估结果写入指定 Gate;已通过且输入指纹未变时跳过。 + + 核心逻辑:指纹写入 effective_result_json.input_fingerprint; + passed 且指纹相同则不重跑;可选在通过后失效下游。 + + Args: + execution: 目标 Execution。 + gate_code: 契约内门禁码。 + passed: 是否通过。 + effective_result / recommendation / blocking_*: 结果载荷。 + input_fingerprint: 可选输入指纹;缺省时对 effective_result 计算。 + actor_type / actor_id: 操作主体。 + idempotency_key: 幂等键。 + invalidate_change_type: 通过后失效类型(覆盖默认)。 + force: True 时忽略指纹跳过。 + outcome: 可选显式结果(waiting_external 等);缺省由 passed 推导。 + + Returns: + 更新后的 Gate;未知 gate_code 返回 None。 + """ + code = str(gate_code or '').strip() + if code not in PROCESS_GATE_CODES: + _LOGGER.warning('apply_gate_outcome ignored unknown gate_code=%s', code) + return None + + result_payload = dict(effective_result or {}) + fingerprint = str(input_fingerprint or '').strip() or _stable_fingerprint(result_payload) + result_payload['input_fingerprint'] = fingerprint + + gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code=code) + .first() + ) + if ( + not force + and gate is not None + and gate.status == 'passed' + and isinstance(gate.effective_result_json, dict) + and str(gate.effective_result_json.get('input_fingerprint') or '') == fingerprint + ): + return gate + + key = str(idempotency_key or '').strip() or f'bridge:{execution.execution_no}:{code}:{fingerprint[:16]}' + return sync_gate_from_business_result( + execution_no=str(execution.execution_no), + gate_code=code, + passed=passed, + effective_result_json=result_payload, + recommendation_json=recommendation, + blocking_reason_code=blocking_reason_code, + blocking_reason_json=blocking_reason_json, + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=key, + invalidate_change_type=invalidate_change_type, + allow_repass=True, + outcome=outcome, + ) + + +def mark_gates_passed_through( + *, + execution: ShippingProcessExecution, + through_gate_code: str, + actor_type: str = 'system', + actor_id: str | int | None = None, + reason: str = 'upstream_satisfied', +) -> list[str]: + """ + 将 sequence 不大于 through_gate_code 且仍为 pending/skipped 的门禁标记为 passed。 + + 核心逻辑:用于人工确认建单后一次性推进到 task_creation;已阻断门禁不静默覆盖。 + + Returns: + 实际推进的 gate_code 列表。 + """ + from app.services.shipping_notice.process_gate_contract import get_process_gate_definition + + target_seq = int(get_process_gate_definition(through_gate_code)['sequence_no']) + advanced: list[str] = [] + gates = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id)) + .order_by(ShippingProcessGate.sequence_no.asc()) + .all() + ) + for gate in gates: + if int(gate.sequence_no) > target_seq: + break + if gate.status in {'passed', 'skipped'}: + continue + if gate.status not in {'pending', 'blocked_manual', 'blocked_retryable', 'invalidated', 'queued'}: + continue + # 仅放行人工确认可覆盖的冻结就绪与前置 pending;技术失败不覆盖。 + if gate.status == 'failed_terminal': + continue + apply_gate_outcome( + execution=execution, + gate_code=gate.gate_code, + passed=True, + effective_result={ + 'findings': [], + 'manual_confirmation': True, + 'reason': reason, + }, + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'manual-pass:{execution.execution_no}:{gate.gate_code}:{gate.evaluation_version}', + force=True, + ) + advanced.append(gate.gate_code) + return advanced + + +def sync_execution_after_review_confirm( + *, + case: ShippingOrderReviewCase, + task: ShippingTask, + actor_id: int, +) -> ShippingProcessExecution | None: + """ + 人工确认建单后:绑定 Task、推进至 task_creation 通过,避免重复冻结阻断。 + + 核心逻辑:确保 Execution 存在;bind_execution_task;将前置门禁与 + order_freeze_readiness / task_creation 标为 passed(人工确认语义)。 + + Returns: + 更新后的 Execution;无法定位时 None。 + """ + from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case + + item = find_item_by_current_case(case_id=int(case.id)) + execution = find_execution_for_case(case) + if execution is None and item is not None: + execution = ensure_execution_for_workflow_item( + item, + review_case_id=int(case.id), + task_id=int(task.id), + actor_type='user', + actor_id=actor_id, + start_gate_code='document_materialization', + ) + if execution is None: + return None + + if execution.review_case_id is None: + execution.review_case_id = int(case.id) + bind_execution_task( + execution_no=str(execution.execution_no), + task_id=int(task.id), + actor_type='user', + actor_id=actor_id, + ) + mark_gates_passed_through( + execution=execution, + through_gate_code='task_creation', + actor_type='user', + actor_id=actor_id, + reason='review_confirmed', + ) + # [STEP] 建单后立即按 Task 状态投影履约门禁,避免 13–19 长期停留 pending。 + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='user', + actor_id=actor_id, + ) + return execution + + +def sync_inventory_routing_gate_for_case( + *, + case: ShippingOrderReviewCase, + passed: bool, + actor_id: int, + details: dict[str, Any] | None = None, + blocking_reason_code: str | None = None, +) -> ShippingProcessGate | None: + """ + 将库存源路由业务结果同步到 inventory_source_routing Gate。 + + Returns: + 更新后的 Gate;无 Execution 时尝试创建后同步。 + """ + from app.services.shipping_notice.workflow_ledger_service import find_item_by_current_case + + execution = find_execution_for_case(case) + if execution is None: + item = find_item_by_current_case(case_id=int(case.id)) + if item is None: + return None + execution = ensure_execution_for_workflow_item( + item, + review_case_id=int(case.id), + actor_type='user', + actor_id=actor_id, + ) + if execution is None: + return None + if execution.review_case_id is None: + execution.review_case_id = int(case.id) + + return apply_gate_outcome( + execution=execution, + gate_code='inventory_source_routing', + passed=passed, + effective_result={ + 'findings': [] if passed else [{ + 'finding_code': 'inventory_source_routing_blocked', + 'owning_gate_code': 'inventory_source_routing', + 'severity': 'blocking', + 'reason_code': blocking_reason_code or 'no_inventory_source_candidates', + 'user_visible': True, + 'blocks_current_action': True, + }], + 'details': details or {}, + }, + blocking_reason_code=None if passed else (blocking_reason_code or 'no_inventory_source_candidates'), + actor_type='user', + actor_id=actor_id, + idempotency_key=f'inv-route:{case.case_no}:{case.current_draft.draft_version if case.current_draft else 0}', + invalidate_change_type='inventory_source_changed' if passed else None, + force=True, + ) + + +def sync_early_pipeline_gates( + *, + execution: ShippingProcessExecution, + layouts_ready: bool, + profile_routed: bool = True, + extraction_ok: bool = True, + blocked_fields: list[str] | None = None, + findings: list[dict[str, Any]] | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, +) -> None: + """ + 同步抽取流水线早期门禁(文档/版面/路由/抽取/完整性)。 + + 核心逻辑:按布尔与 blocked_fields 写入 passed/blocked;诊断 Finding 写入 + effective_result 但不单独阻断非关键字段。 + """ + apply_gate_outcome( + execution=execution, + gate_code='document_materialization', + passed=True, + effective_result={'findings': [], 'stage': 'materialized'}, + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'early:doc:{execution.execution_no}', + ) + apply_gate_outcome( + execution=execution, + gate_code='layout_parsing', + passed=layouts_ready, + effective_result={'findings': [], 'layouts_ready': layouts_ready}, + blocking_reason_code=None if layouts_ready else 'layout_parse_failed', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'early:layout:{execution.execution_no}:{layouts_ready}', + force=True, + ) + if not layouts_ready: + return + apply_gate_outcome( + execution=execution, + gate_code='document_profile_routing', + passed=profile_routed, + effective_result={'findings': [], 'routed': profile_routed}, + blocking_reason_code=None if profile_routed else 'profile_not_matched', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'early:profile:{execution.execution_no}:{profile_routed}', + force=True, + ) + if not profile_routed: + return + apply_gate_outcome( + execution=execution, + gate_code='order_field_extraction', + passed=extraction_ok, + effective_result={'findings': list(findings or []), 'extraction_ok': extraction_ok}, + blocking_reason_code=None if extraction_ok else 'extraction_incomplete', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'early:extract:{execution.execution_no}:{extraction_ok}', + force=True, + ) + blocked = [str(x).strip() for x in (blocked_fields or []) if str(x).strip()] + apply_gate_outcome( + execution=execution, + gate_code='field_completeness', + passed=not blocked, + effective_result={ + 'findings': [ + item for item in (findings or []) + if isinstance(item, dict) and str(item.get('owning_gate_code') or '') == 'field_completeness' + ], + 'blocked_fields': blocked, + }, + blocking_reason_code=None if not blocked else 'required_field_missing', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'early:complete:{execution.execution_no}:{",".join(sorted(blocked)) or "ok"}', + force=True, + ) + + +def sync_fulfillment_gates_from_task( + *, + execution: ShippingProcessExecution, + actor_type: str = 'system', + actor_id: str | int | None = None, +) -> None: + """ + 按 ShippingTask 履约状态同步 inventory_preparation→manual_upload_handoff 门禁。 + + 核心逻辑:将 process_status / export_file_path / match 相关字段投影为 Gate 结果; + 仅阻断当前业务真实卡住的第一道履约门禁,已满足的上游门禁标为 passed。 + 由 auto_progress 与 Gate 恢复执行器在履约动作后调用。 + + Args: + execution: 已绑定 task_id 的 Execution。 + actor_type / actor_id: 操作主体。 + """ + if not execution.task_id: + return + task = ShippingTask.query.get(int(execution.task_id)) + if task is None: + return + + from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed + from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + + status = str(task.process_status or '').strip() + match_status = str(task.match_status or '').strip() + has_export = bool(str(task.export_file_path or '').strip()) + has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0 + inv_file = active_inventory_file_for_task(task) + mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False))) + # [STEP 1] 优先读匹配/短缺实体;process_status 仅作库存准备与上传阶段辅助。 + done_statuses = {'uploaded', 'closed'} + post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses} + sufficiency_ok = match_completed(task) + shortage = (not sufficiency_ok) and ( + match_status in {'unfulfillable', 'partial'} + or bool(task.shortage_json) + or status == 'shortage_review' + ) + match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in { + 'matched', 'waiting_upload', 'upload_failed', *done_statuses, + } + # 仅当存在活跃库存文件且未确认映射时阻断;无文件但已有解析行视为映射已由 Profile 固化。 + mapping_needed = ( + inv_file is not None + and not mapping_confirmed + and status not in {'matched', 'waiting_upload', 'upload_failed', *done_statuses} + ) + + apply_gate_outcome( + execution=execution, + gate_code='task_creation', + passed=True, + effective_result={'findings': [], 'task_no': task.task_no}, + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:task:{execution.execution_no}:{task.id}', + force=True, + ) + + # [STEP 2] inventory_preparation + if status == 'waiting_inventory': + apply_gate_outcome( + execution=execution, + gate_code='inventory_preparation', + passed=False, + outcome='waiting_external', + effective_result={'findings': [], 'process_status': status}, + blocking_reason_code='inventory_preparation_waiting', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}', + force=True, + ) + return + inv_prep_passed = status in post_inventory or has_inventory_lines + apply_gate_outcome( + execution=execution, + gate_code='inventory_preparation', + passed=inv_prep_passed, + outcome=None if inv_prep_passed else 'blocked_retryable', + effective_result={ + 'findings': [], + 'process_status': status, + 'has_inventory_lines': has_inventory_lines, + }, + blocking_reason_code=None if inv_prep_passed else 'inventory_preparation_failed', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:invprep:{execution.execution_no}:{status}:{inv_prep_passed}', + force=True, + ) + if not inv_prep_passed: + return + + # [STEP 3] inventory_field_mapping — 以 mapping_confirmed 为准 + apply_gate_outcome( + execution=execution, + gate_code='inventory_field_mapping', + passed=not mapping_needed, + outcome='blocked_manual' if mapping_needed else None, + effective_result={ + 'findings': [], + 'mapping_confirmed': mapping_confirmed, + 'inventory_file_id': int(inv_file.id) if inv_file else None, + }, + blocking_reason_code='inventory_mapping_required' if mapping_needed else None, + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:map:{execution.execution_no}:{mapping_confirmed}:{mapping_needed}', + force=True, + ) + if mapping_needed: + return + + # [STEP 4] inventory_matching — 以 match_status 为准 + apply_gate_outcome( + execution=execution, + gate_code='inventory_matching', + passed=match_passed, + outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None, + effective_result={'findings': [], 'match_status': match_status or None}, + blocking_reason_code=None if match_passed else 'inventory_match_failed', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:match:{execution.execution_no}:{match_status or status}', + force=True, + ) + if not match_passed: + return + + # [STEP 5] inventory_sufficiency — 以 match_completed / shortage_json 为准 + apply_gate_outcome( + execution=execution, + gate_code='inventory_sufficiency', + passed=sufficiency_ok, + outcome='blocked_manual' if shortage else None, + effective_result={ + 'findings': [], + 'match_status': match_status or None, + 'shortage': task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None, + }, + blocking_reason_code=None if sufficiency_ok else 'inventory_insufficient', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}', + force=True, + ) + if not sufficiency_ok: + return + + # [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离 + excel_error = excel_gate_error(task) + excel_ready = excel_error is None + apply_gate_outcome( + execution=execution, + gate_code='excel_readiness', + passed=excel_ready, + effective_result={'findings': [], 'excel_gate_error': excel_error}, + blocking_reason_code=None if excel_ready else 'excel_not_ready', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:excelready:{execution.execution_no}:{excel_ready}', + force=True, + ) + if not excel_ready: + return + + artifact_ok = has_export or status in done_statuses + apply_gate_outcome( + execution=execution, + gate_code='artifact_generation', + passed=artifact_ok, + effective_result={'findings': [], 'has_export': has_export}, + blocking_reason_code=None if artifact_ok else 'artifact_generation_failed', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:artifact:{execution.execution_no}:{has_export}:{status}', + force=True, + ) + if not artifact_ok: + return + + # [STEP 7] manual_upload_handoff + uploaded = status in done_statuses + apply_gate_outcome( + execution=execution, + gate_code='manual_upload_handoff', + passed=uploaded, + outcome=None if uploaded else ( + 'waiting_external' if status == 'waiting_upload' else 'blocked_manual' + ), + effective_result={'findings': [], 'process_status': status}, + blocking_reason_code=None if uploaded else 'manual_upload_pending', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}', + force=True, + ) diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py new file mode 100644 index 00000000..ad7c57ea --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -0,0 +1,596 @@ +""" +services/shipping_notice/process_gate_contract.py + +用途:冻结货代发货通知全链路业务门禁(Gate)契约:编码、状态、恢复动作、 + 阻断原因、责任方、Finding 严重级别、原因码唯一归属与字段阻断资格; + 作为 Execution/Gate/Attempt 与前后端类型的唯一代码源。 +依赖:无外部 IO;被 process_gate_dependency、领域服务、API、前端类型与文档引用。 +逻辑:本模块只冻结名称与规则,不执行业务;后续阶段接线时禁止前端或 Job 私自发明门禁码; + 同一根因只允许一个 owning_gate 产生用户阻断 Finding。 +""" + +from __future__ import annotations + +from typing import Any, Final + + +# 契约版本;投影、OpenAPI 与 i18n 必须与此对齐。 +PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v1' + +# Finding 严重级别:仅 blocking 可改变 Gate 状态;diagnostic 供管理员诊断。 +PROCESS_GATE_FINDING_SEVERITIES: Final[frozenset[str]] = frozenset({ + 'blocking', + 'diagnostic', +}) + +PROCESS_GATE_STATUSES: Final[frozenset[str]] = frozenset({ + 'pending', + 'queued', + 'running', + 'passed', + 'blocked_retryable', + 'blocked_manual', + 'waiting_external', + 'failed_terminal', + 'invalidated', + 'skipped', +}) + +PROCESS_GATE_TERMINAL_STATUSES: Final[frozenset[str]] = frozenset({ + 'passed', + 'failed_terminal', + 'skipped', +}) + +PROCESS_GATE_RECOVERABLE_STATUSES: Final[frozenset[str]] = frozenset({ + 'blocked_retryable', + 'blocked_manual', + 'waiting_external', + 'invalidated', + 'failed_terminal', +}) + +PROCESS_GATE_RESPONSIBLE_PARTIES: Final[frozenset[str]] = frozenset({ + 'system', + 'worker', + 'owner', + 'admin', + 'external', +}) + +PROCESS_GATE_TRIGGER_TYPES: Final[frozenset[str]] = frozenset({ + 'auto', + 'user_retry', + 'user_manual', + 'worker_takeover', + 'upstream_invalidation', + 'system_requeue', +}) + +PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( + { + 'gate_code': 'document_materialization', + 'sequence_no': 1, + 'label': '文档和附件可用性', + 'responsible_party': 'system', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'rematerialize_document', + 'failed_terminal': None, + }, + }, + { + 'gate_code': 'layout_parsing', + 'sequence_no': 2, + 'label': 'PDF 版面解析', + 'responsible_party': 'worker', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_layout_parsing', + 'failed_terminal': None, + }, + }, + { + 'gate_code': 'document_profile_routing', + 'sequence_no': 3, + 'label': 'Profile/模板路由', + 'responsible_party': 'system', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'reroute_document_profile', + 'blocked_manual': 'open_profile_review', + }, + }, + { + 'gate_code': 'order_field_extraction', + 'sequence_no': 4, + 'label': '订单字段抽取', + 'responsible_party': 'worker', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_order_extraction', + 'blocked_manual': 'open_order_review', + }, + }, + { + 'gate_code': 'field_completeness', + 'sequence_no': 5, + 'label': '必填字段完整性', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_manual': 'edit_order_fields', + }, + }, + { + 'gate_code': 'reservation_validation', + 'sequence_no': 6, + 'label': 'Reservation 格式和证据', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'revalidate_reservation', + 'blocked_manual': 'edit_reservation', + }, + }, + { + 'gate_code': 'customer_resolution', + 'sequence_no': 7, + 'label': '客户身份识别', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_customer_resolution', + 'blocked_manual': 'confirm_customer', + }, + }, + { + 'gate_code': 'duplicate_detection', + 'sequence_no': 8, + 'label': '重复订单/修订判断', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_duplicate_detection', + 'blocked_manual': 'adjudicate_duplicate', + }, + }, + { + 'gate_code': 'field_conflict_resolution', + 'sequence_no': 9, + 'label': '字段冲突', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_manual': 'resolve_field_conflicts', + }, + }, + { + 'gate_code': 'inventory_source_routing', + 'sequence_no': 10, + 'label': '库存源路由', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_with_latest_rules', + 'blocked_manual': 'open_inventory_source_review', + }, + }, + { + 'gate_code': 'order_freeze_readiness', + 'sequence_no': 11, + 'label': '订单冻结资格', + 'responsible_party': 'system', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'recheck_freeze_readiness', + 'blocked_manual': 'open_order_review', + }, + }, + { + 'gate_code': 'task_creation', + 'sequence_no': 12, + 'label': 'ShippingTask 创建', + 'responsible_party': 'system', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_task_creation', + }, + }, + { + 'gate_code': 'inventory_preparation', + 'sequence_no': 13, + 'label': '库存文件或快照准备', + 'responsible_party': 'worker', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_inventory_preparation', + 'waiting_external': 'poll_inventory_preparation', + 'blocked_manual': 'upload_inventory_file', + }, + }, + { + 'gate_code': 'inventory_field_mapping', + 'sequence_no': 14, + 'label': '库存字段映射', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_inventory_field_mapping', + 'blocked_manual': 'confirm_inventory_field_mapping', + }, + }, + { + 'gate_code': 'inventory_matching', + 'sequence_no': 15, + 'label': 'Reservation + 料号匹配', + 'responsible_party': 'worker', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'retry_inventory_matching', + 'blocked_manual': 'open_inventory_match_review', + }, + }, + { + 'gate_code': 'inventory_sufficiency', + 'sequence_no': 16, + 'label': '库存满足性', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'recheck_inventory_sufficiency', + 'blocked_manual': 'open_shortage_review', + }, + }, + { + 'gate_code': 'excel_readiness', + 'sequence_no': 17, + 'label': 'Excel 生成资格', + 'responsible_party': 'system', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'recheck_excel_readiness', + }, + }, + { + 'gate_code': 'artifact_generation', + 'sequence_no': 18, + 'label': 'Excel Artifact', + 'responsible_party': 'worker', + 'recoverable': True, + 'default_next_actions': { + 'blocked_retryable': 'regenerate_excel_artifact', + }, + }, + { + 'gate_code': 'manual_upload_handoff', + 'sequence_no': 19, + 'label': '人工上传交接', + 'responsible_party': 'owner', + 'recoverable': True, + 'default_next_actions': { + 'blocked_manual': 'regenerate_manual_upload_todo', + 'waiting_external': None, + }, + }, +) + +PROCESS_GATE_CODES: Final[tuple[str, ...]] = tuple( + str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS +) + +PROCESS_GATE_CODE_SET: Final[frozenset[str]] = frozenset(PROCESS_GATE_CODES) + +PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ + 'rematerialize_document', + 'retry_layout_parsing', + 'reroute_document_profile', + 'open_profile_review', + 'retry_order_extraction', + 'open_order_review', + 'edit_order_fields', + 'revalidate_reservation', + 'edit_reservation', + 'retry_customer_resolution', + 'confirm_customer', + 'retry_duplicate_detection', + 'adjudicate_duplicate', + 'resolve_field_conflicts', + 'retry_with_latest_rules', + 'open_inventory_source_review', + 'adopt_rule_suggestion', + 'keep_manual_inventory_decision', + 'recheck_freeze_readiness', + 'retry_task_creation', + 'retry_inventory_preparation', + 'poll_inventory_preparation', + 'upload_inventory_file', + 'retry_inventory_field_mapping', + 'confirm_inventory_field_mapping', + 'retry_inventory_matching', + 'open_inventory_match_review', + 'recheck_inventory_sufficiency', + 'open_shortage_review', + 'recheck_excel_readiness', + 'regenerate_excel_artifact', + 'regenerate_manual_upload_todo', +}) + +PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ + 'document_unavailable', + 'layout_parse_failed', + 'profile_ambiguous', + 'profile_drift', + 'profile_not_matched', + 'extraction_incomplete', + 'evidence_missing', + 'required_field_missing', + 'reservation_invalid', + 'customer_unresolved', + 'customer_ambiguous', + 'duplicate_unresolved', + 'field_conflict', + 'cross_source_conflict', + 'no_inventory_source_candidates', + 'require_manual_review', + 'inventory_source_unavailable', + 'freeze_not_ready', + 'profile_not_auto_freeze_approved', + 'profile_manual_confirmation_required', + 'profile_auto_freeze_qualification_missing', + 'profile_auto_freeze_suspended', + 'customer_confirmation_required', + 'customer_scope_unmatched', + 'customer_scope_not_configured', + 'customer_scope_out_of_scope', + 'multiple_customers_detected', + 'multiple_profiles_detected', + 'business_scenario_unmatched', + 'business_scenario_not_configured', + 'business_scenario_out_of_scope', + 'extraction_emergency_stop', + 'generic_auto_freeze_disabled', + 'llm_path_cannot_auto_freeze', + 'auto_freeze_not_enabled', + 'technical_failure_present', + 'unit_review_required', + 'budget_stopped', + 'review_required', + 'run_failed', + 'run_cancelled', + 'pending_orders_present', + 'task_creation_failed', + 'inventory_preparation_failed', + 'inventory_preparation_waiting', + 'inventory_mapping_required', + 'inventory_match_failed', + 'inventory_insufficient', + 'excel_not_ready', + 'artifact_generation_failed', + 'manual_upload_pending', + 'gate_invalidated', + 'lease_conflict', + 'version_conflict', + 'not_recoverable', +}) + +# 原因码 → 唯一 owning_gate;同一根因禁止多门禁平行产生用户阻断。 +PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { + 'document_unavailable': 'document_materialization', + 'layout_parse_failed': 'layout_parsing', + 'profile_ambiguous': 'document_profile_routing', + 'profile_drift': 'document_profile_routing', + 'profile_not_matched': 'document_profile_routing', + 'extraction_incomplete': 'order_field_extraction', + 'evidence_missing': 'order_field_extraction', + 'required_field_missing': 'field_completeness', + 'reservation_invalid': 'reservation_validation', + 'customer_unresolved': 'customer_resolution', + 'customer_ambiguous': 'customer_resolution', + 'duplicate_unresolved': 'duplicate_detection', + 'field_conflict': 'field_conflict_resolution', + 'cross_source_conflict': 'field_conflict_resolution', + 'no_inventory_source_candidates': 'inventory_source_routing', + 'require_manual_review': 'inventory_source_routing', + 'inventory_source_unavailable': 'inventory_source_routing', + 'freeze_not_ready': 'order_freeze_readiness', + 'profile_not_auto_freeze_approved': 'order_freeze_readiness', + 'profile_manual_confirmation_required': 'order_freeze_readiness', + 'profile_auto_freeze_qualification_missing': 'order_freeze_readiness', + 'profile_auto_freeze_suspended': 'order_freeze_readiness', + 'customer_confirmation_required': 'order_freeze_readiness', + 'customer_scope_unmatched': 'order_freeze_readiness', + 'customer_scope_not_configured': 'order_freeze_readiness', + 'customer_scope_out_of_scope': 'order_freeze_readiness', + 'multiple_customers_detected': 'order_freeze_readiness', + 'multiple_profiles_detected': 'order_freeze_readiness', + 'business_scenario_unmatched': 'order_freeze_readiness', + 'business_scenario_not_configured': 'order_freeze_readiness', + 'business_scenario_out_of_scope': 'order_freeze_readiness', + 'extraction_emergency_stop': 'order_freeze_readiness', + 'generic_auto_freeze_disabled': 'order_freeze_readiness', + 'llm_path_cannot_auto_freeze': 'order_freeze_readiness', + 'auto_freeze_not_enabled': 'order_freeze_readiness', + 'technical_failure_present': 'order_freeze_readiness', + 'unit_review_required': 'order_freeze_readiness', + 'budget_stopped': 'order_freeze_readiness', + 'review_required': 'order_freeze_readiness', + 'run_failed': 'order_freeze_readiness', + 'run_cancelled': 'order_freeze_readiness', + 'pending_orders_present': 'order_freeze_readiness', + 'task_creation_failed': 'task_creation', + 'inventory_preparation_failed': 'inventory_preparation', + 'inventory_preparation_waiting': 'inventory_preparation', + 'inventory_mapping_required': 'inventory_field_mapping', + 'inventory_match_failed': 'inventory_matching', + 'inventory_insufficient': 'inventory_sufficiency', + 'excel_not_ready': 'excel_readiness', + 'artifact_generation_failed': 'artifact_generation', + 'manual_upload_pending': 'manual_upload_handoff', +} + +# 旧自动建单五门禁键 → 唯一 owning_gate(禁止平行用户投影)。 +AUTO_BUILD_LEGACY_GATE_OWNING_MAP: Final[dict[str, str]] = { + 'approved_template': 'order_freeze_readiness', + 'fields_complete': 'field_completeness', + 'evidence_passed': 'order_field_extraction', + 'no_conflict_or_duplicate': 'duplicate_detection', + 'quality_gate_passed': 'order_freeze_readiness', +} + +PROCESS_EXECUTION_STATUSES: Final[frozenset[str]] = frozenset({ + 'active', + 'blocked', + 'waiting_external', + 'completed', + 'cancelled', + 'failed', +}) + +PROCESS_GATE_ATTEMPT_STATUSES: Final[frozenset[str]] = frozenset({ + 'queued', + 'running', + 'succeeded', + 'failed', + 'cancelled', + 'superseded', +}) + + +def get_process_gate_definition(gate_code: str) -> dict[str, Any]: + """ + 按 gate_code 返回门禁定义副本。 + + Args: + gate_code: 稳定门禁编码。 + + Returns: + 定义字典。 + + Raises: + KeyError: 未知门禁码。 + """ + code = str(gate_code or '').strip() + for item in PROCESS_GATE_DEFINITIONS: + if item['gate_code'] == code: + return dict(item) + raise KeyError(f'unknown process gate: {code}') + + +def primary_next_action_for_gate(*, gate_code: str, status: str) -> str | None: + """ + 返回指定门禁状态下的唯一主要恢复动作;无动作返回 None。 + + 核心逻辑:每种状态最多一个主要 next_action;前端禁止本地推导。 + """ + definition = get_process_gate_definition(gate_code) + actions = definition.get('default_next_actions') if isinstance(definition.get('default_next_actions'), dict) else {} + value = actions.get(str(status or '').strip()) + return str(value) if value else None + + +def owning_gate_for_reason(reason_code: str) -> str | None: + """ + 返回阻断/诊断原因码的唯一 owning_gate;未知原因返回 None。 + + Args: + reason_code: 稳定原因码。 + + Returns: + gate_code 或 None。 + """ + code = str(reason_code or '').strip() + return PROCESS_GATE_REASON_OWNING_GATE.get(code) + + +def field_quality_may_block(*, required: bool = False, auto_create_key_field: bool = False) -> bool: + """ + 字段质量问题是否允许阻断当前动作。 + + 核心逻辑:仅 required 或 auto_create_key_field 可阻断;否则只允许 diagnostic Finding。 + """ + return bool(required) or bool(auto_create_key_field) + + +def build_process_finding( + *, + finding_code: str, + owning_gate_code: str, + severity: str, + reason_code: str, + field_code: str | None = None, + decision_id: int | None = None, + user_visible: bool | None = None, + blocks_current_action: bool | None = None, + details: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 构造标准 Finding 结构。 + + Args: + finding_code: Finding 稳定编码。 + owning_gate_code: 唯一所属门禁。 + severity: blocking | diagnostic。 + reason_code: 原因码(须能映射到 owning_gate)。 + field_code / decision_id: 可选字段定位。 + user_visible / blocks_current_action: 缺省由 severity 推导。 + details: 管理员诊断附加信息。 + + Returns: + Finding 字典。 + """ + sev = str(severity or '').strip() + if sev not in PROCESS_GATE_FINDING_SEVERITIES: + raise ValueError(f'invalid finding severity: {sev}') + gate = str(owning_gate_code or '').strip() + if gate not in PROCESS_GATE_CODE_SET: + raise ValueError(f'unknown owning_gate_code: {gate}') + visible = bool(user_visible) if user_visible is not None else sev == 'blocking' + blocks = bool(blocks_current_action) if blocks_current_action is not None else sev == 'blocking' + payload: dict[str, Any] = { + 'finding_code': str(finding_code), + 'owning_gate_code': gate, + 'severity': sev, + 'reason_code': str(reason_code or '').strip(), + 'field_code': str(field_code).strip() if field_code else None, + 'decision_id': int(decision_id) if decision_id is not None else None, + 'user_visible': visible, + 'blocks_current_action': blocks, + } + if details: + payload['details'] = dict(details) + return payload + + +def assert_process_gate_contract_integrity() -> None: + """ + 校验契约内无重复 gate_code、动作与状态闭环,以及原因码唯一归属。 + + Raises: + AssertionError: 契约不一致。 + """ + codes = [str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS] + assert len(codes) == len(set(codes)), 'duplicate process gate_code' + sequences = [int(item['sequence_no']) for item in PROCESS_GATE_DEFINITIONS] + assert sequences == sorted(sequences), 'process gate sequence_no must be ascending' + assert set(sequences) == set(range(1, len(sequences) + 1)), 'process gate sequence_no must be contiguous' + for item in PROCESS_GATE_DEFINITIONS: + assert item['responsible_party'] in PROCESS_GATE_RESPONSIBLE_PARTIES + actions = item.get('default_next_actions') or {} + assert isinstance(actions, dict) + for status, action in actions.items(): + assert status in PROCESS_GATE_STATUSES + if action is not None: + assert action in PROCESS_GATE_ACTION_CODES + if item.get('recoverable'): + assert any(value for value in actions.values()), f'{item["gate_code"]} missing recovery action' + + # [STEP] 原因码唯一归属:每个 reason 恰好一个 owning gate,且 gate 必须存在。 + for reason, gate in PROCESS_GATE_REASON_OWNING_GATE.items(): + assert reason in PROCESS_GATE_BLOCKING_REASON_CODES, f'reason {reason} missing from blocking codes' + assert gate in PROCESS_GATE_CODE_SET, f'reason {reason} owns unknown gate {gate}' + owned_reasons = list(PROCESS_GATE_REASON_OWNING_GATE.keys()) + assert len(owned_reasons) == len(set(owned_reasons)), 'duplicate reason ownership' + + for legacy_key, gate in AUTO_BUILD_LEGACY_GATE_OWNING_MAP.items(): + assert gate in PROCESS_GATE_CODE_SET, f'legacy auto-build key {legacy_key} maps to unknown gate' diff --git a/backend/app/services/shipping_notice/process_gate_dependency.py b/backend/app/services/shipping_notice/process_gate_dependency.py new file mode 100644 index 00000000..fbe20116 --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_dependency.py @@ -0,0 +1,177 @@ +""" +services/shipping_notice/process_gate_dependency.py + +用途:冻结门禁依赖图与上游输入变化时的下游精确失效范围。 +依赖:process_gate_contract.PROCESS_GATE_CODE_SET。 +逻辑:由门禁恢复服务在提交 Attempt 结果或上游字段变化时调用;前端禁止本地推导失效范围。 +""" + +from __future__ import annotations + +from typing import Final + +from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET, PROCESS_GATE_CODES + + +# 上游变化类型 → 必须失效的下游门禁(不含变化源自身)。 +PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { + 'pdf_or_extraction_changed': ( + 'field_completeness', + 'reservation_validation', + 'customer_resolution', + 'duplicate_detection', + 'field_conflict_resolution', + 'inventory_source_routing', + 'order_freeze_readiness', + 'task_creation', + 'inventory_preparation', + 'inventory_field_mapping', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'reservation_changed': ( + 'duplicate_detection', + 'order_freeze_readiness', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'part_number_changed': ( + 'order_freeze_readiness', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'quantity_changed': ( + 'order_freeze_readiness', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'customer_changed': ( + 'duplicate_detection', + 'order_freeze_readiness', + 'task_creation', + 'inventory_preparation', + 'inventory_field_mapping', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'inventory_source_changed': ( + 'inventory_preparation', + 'inventory_field_mapping', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'inventory_file_changed': ( + 'inventory_field_mapping', + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'inventory_field_mapping_changed': ( + 'inventory_matching', + 'inventory_sufficiency', + 'excel_readiness', + 'artifact_generation', + 'manual_upload_handoff', + ), + 'excel_regeneration_only': ( + 'artifact_generation', + 'manual_upload_handoff', + ), +} + +# 显式前置依赖:gate 必须等待这些上游 passed(或 skipped)。 +PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = { + 'layout_parsing': ('document_materialization',), + 'document_profile_routing': ('layout_parsing',), + 'order_field_extraction': ('document_profile_routing',), + 'field_completeness': ('order_field_extraction',), + 'reservation_validation': ('field_completeness',), + 'customer_resolution': ('reservation_validation',), + 'duplicate_detection': ('customer_resolution',), + 'field_conflict_resolution': ('duplicate_detection',), + 'inventory_source_routing': ('field_conflict_resolution',), + 'order_freeze_readiness': ('inventory_source_routing',), + 'task_creation': ('order_freeze_readiness',), + 'inventory_preparation': ('task_creation',), + 'inventory_field_mapping': ('inventory_preparation',), + 'inventory_matching': ('inventory_field_mapping',), + 'inventory_sufficiency': ('inventory_matching',), + 'excel_readiness': ('inventory_sufficiency',), + 'artifact_generation': ('excel_readiness',), + 'manual_upload_handoff': ('artifact_generation',), +} + + +def compute_invalidated_gates(change_type: str) -> tuple[str, ...]: + """ + 计算上游变化必须失效的下游门禁列表(保序、去重)。 + + Args: + change_type: PROCESS_GATE_INVALIDATION_RULES 键。 + + Returns: + 下游 gate_code 元组;未知变化类型返回空元组。 + """ + key = str(change_type or '').strip() + gates = PROCESS_GATE_INVALIDATION_RULES.get(key, ()) + ordered = [code for code in PROCESS_GATE_CODES if code in set(gates)] + return tuple(ordered) + + +def prerequisites_for(gate_code: str) -> tuple[str, ...]: + """ + 返回指定门禁的直接前置依赖。 + + Args: + gate_code: 门禁编码。 + + Returns: + 前置 gate_code 元组。 + """ + code = str(gate_code or '').strip() + return tuple(PROCESS_GATE_PREREQUISITES.get(code, ())) + + +def assert_process_gate_dependency_integrity() -> None: + """ + 校验依赖图与失效规则仅引用已知门禁,且无环。 + + Raises: + AssertionError: 依赖图不一致。 + """ + for gate_code, deps in PROCESS_GATE_PREREQUISITES.items(): + assert gate_code in PROCESS_GATE_CODE_SET, f'unknown gate in prerequisites: {gate_code}' + for dep in deps: + assert dep in PROCESS_GATE_CODE_SET, f'unknown prerequisite {dep} for {gate_code}' + assert PROCESS_GATE_CODES.index(dep) < PROCESS_GATE_CODES.index(gate_code), ( + f'prerequisite {dep} must precede {gate_code}' + ) + for change_type, gates in PROCESS_GATE_INVALIDATION_RULES.items(): + for gate_code in gates: + assert gate_code in PROCESS_GATE_CODE_SET, ( + f'unknown gate {gate_code} in invalidation rule {change_type}' + ) + # 仅重新生成 Excel 不得失效库存匹配。 + excel_only = set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only']) + assert 'inventory_matching' not in excel_only + assert 'artifact_generation' in excel_only diff --git a/backend/app/services/shipping_notice/process_gate_error_sanitizer.py b/backend/app/services/shipping_notice/process_gate_error_sanitizer.py new file mode 100644 index 00000000..d2ded683 --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_error_sanitizer.py @@ -0,0 +1,60 @@ +""" +services/shipping_notice/process_gate_error_sanitizer.py + +用途:门禁 Attempt / blocking_reason / 投影中的异常摘要统一脱敏与截断。 +依赖:标准库 re。 +逻辑:由 process_gate_executor / process_gate_service / process_gate_projection 在写入或 + 对外序列化前调用;剥离 URL、连接串、路径、凭据片段后截断,避免外部系统异常泄漏。 +""" + +from __future__ import annotations + +import re + +_URL_RE = re.compile(r'https?://[^\s\'\"]+', re.IGNORECASE) +_CONN_RE = re.compile( + r'(?:postgres(?:ql)?|mysql|mssql|oracle|redis|amqp|mongodb)://[^\s\'\"]+', + re.IGNORECASE, +) +_DSN_RE = re.compile( + r'(?:password|pwd|secret|token|api[_-]?key|access[_-]?key)\s*[=:]\s*[^\s,;\'\"]+', + re.IGNORECASE, +) +_WIN_PATH_RE = re.compile(r'[A-Za-z]:\\[^\s\'\"]+') +_UNIX_PATH_RE = re.compile(r'(?:/[\w.\-]+){2,}') +_IPV4_RE = re.compile(r'\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{2,5})?\b') +_BEARER_RE = re.compile(r'(?i)\b(?:bearer|authorization)\s+[A-Za-z0-9._\-+=/]+') + + +def sanitize_gate_error_text(value: object | None, *, max_len: int = 500) -> str | None: + """ + 将异常/工具错误文本脱敏并截断,供 Attempt.error_summary 与诊断投影使用。 + + 核心逻辑:依次遮蔽 URL、连接串、凭据键值、文件系统路径、IPv4 与 Bearer; + 再压缩空白并截断到 max_len。空输入返回 None。 + + Args: + value: 原始错误对象或字符串。 + max_len: 最大保留字符数(默认 500,Attempt 持久化可用更大上限)。 + + Returns: + 脱敏后的摘要;无有效内容时 None。 + """ + if value is None: + return None + text = str(value).strip() + if not text: + return None + # [STEP 1] 遮蔽高风险片段,避免连接串 / 路径 / Token 落库或下发。 + text = _URL_RE.sub('[url]', text) + text = _CONN_RE.sub('[connection]', text) + text = _DSN_RE.sub(lambda m: f"{m.group(0).split('=')[0].split(':')[0]}=[redacted]", text) + text = _BEARER_RE.sub('[auth]', text) + text = _WIN_PATH_RE.sub('[path]', text) + text = _UNIX_PATH_RE.sub('[path]', text) + text = _IPV4_RE.sub('[host]', text) + text = re.sub(r'\s+', ' ', text).strip() + limit = max(32, int(max_len or 500)) + if len(text) > limit: + text = text[: limit - 1].rstrip() + '…' + return text diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py new file mode 100644 index 00000000..38b63ddc --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -0,0 +1,1170 @@ +""" +services/shipping_notice/process_gate_executor.py + +用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。 +依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、 + inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 + document_layout.lifecycle、process_gate_contract、process_gate_bridge。 +逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态; + 库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 workflow; + 人工入口动作返回 navigation 提示,保持 blocked_manual。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +from app.core.errors import ValidationError +from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt +from app.services.shipping_notice.process_gate_contract import ( + get_process_gate_definition, + owning_gate_for_reason, +) +from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text +from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running + + +# 可同步完成、不依赖长时 Worker 副作用的动作。 +_SYNC_ACTIONS: frozenset[str] = frozenset({ + 'adopt_rule_suggestion', + 'keep_manual_inventory_decision', + 'retry_with_latest_rules', + 'recheck_freeze_readiness', + 'open_order_review', + 'open_inventory_source_review', + 'open_profile_review', + 'edit_order_fields', + 'edit_reservation', + 'confirm_customer', + 'adjudicate_duplicate', + 'resolve_field_conflicts', + 'open_inventory_match_review', + 'open_shortage_review', + 'upload_inventory_file', + 'confirm_inventory_field_mapping', + 'regenerate_manual_upload_todo', +}) + +# 人工入口:前端应导航,不把业务状态改为 passed。 +_NAVIGATION_ACTIONS: frozenset[str] = frozenset({ + 'open_order_review', + 'open_inventory_source_review', + 'open_profile_review', + 'edit_order_fields', + 'edit_reservation', + 'confirm_customer', + 'adjudicate_duplicate', + 'resolve_field_conflicts', + 'open_inventory_match_review', + 'open_shortage_review', + 'upload_inventory_file', + 'confirm_inventory_field_mapping', +}) + + +def action_requires_async_worker(action_code: str) -> bool: + """判断动作是否必须由 Gate Worker 异步执行。""" + return str(action_code or '').strip() not in _SYNC_ACTIONS + + +def is_navigation_action(action_code: str) -> bool: + """是否为前端导航型人工入口动作。""" + return str(action_code or '').strip() in _NAVIGATION_ACTIONS + + +def execute_queued_attempt( + *, + attempt: ShippingProcessGateAttempt, + worker_id: str | None = None, + lease_token: str | None = None, + lease_expires_at=None, +) -> ShippingProcessGate: + """ + 执行已排队 Attempt:标记 running → 调用适配器 → complete_gate_attempt。 + + Args: + attempt: 活动 Attempt(queued/running)。 + worker_id: Worker 标识;同步路径可为 system。 + lease_token / lease_expires_at: 可选租约;Worker 路径由 claim 注入。 + + Returns: + 更新后的 Gate。 + """ + if attempt.status != 'running' or not attempt.lease_token: + mark_attempt_running( + attempt_id=int(attempt.id), + worker_id=worker_id or 'system-sync', + lease_token=lease_token, + lease_expires_at=lease_expires_at, + ) + gate = ShippingProcessGate.query.get(int(attempt.gate_id)) + if gate is None: + raise ValidationError('Process gate missing for attempt', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + execution = ShippingProcessExecution.query.get(int(gate.execution_id)) + if execution is None: + raise ValidationError('Process execution missing', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND') + + snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {} + action = str(snapshot.get('action_code') or gate.next_action_code or '').strip() + payload = snapshot.get('payload') if isinstance(snapshot.get('payload'), dict) else {} + + outcome = _dispatch_action( + execution=execution, + gate=gate, + action_code=action, + payload=payload, + ) + return complete_gate_attempt( + attempt_id=int(attempt.id), + outcome=str(outcome.get('outcome') or 'blocked_retryable'), + blocking_reason_code=outcome.get('blocking_reason_code'), + blocking_reason_json=outcome.get('blocking_reason_json'), + recommendation_json=outcome.get('recommendation_json'), + effective_result_json=outcome.get('effective_result_json'), + output_snapshot=outcome.get('output_snapshot') or outcome, + error_code=outcome.get('error_code'), + error_summary=outcome.get('error_summary'), + invalidate_change_type=outcome.get('invalidate_change_type'), + ) + + +def _dispatch_action( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + action_code: str, + payload: dict[str, Any], +) -> dict[str, Any]: + """按动作码分发到真实业务适配器。""" + handlers: dict[str, Callable[..., dict[str, Any]]] = { + 'retry_with_latest_rules': _handle_inventory_reroute, + 'adopt_rule_suggestion': _handle_adopt_suggestion, + 'keep_manual_inventory_decision': _handle_keep_manual, + 'recheck_freeze_readiness': _handle_recheck_freeze, + 'rematerialize_document': _handle_rematerialize_document, + 'retry_layout_parsing': _handle_retry_layout_parsing, + 'reroute_document_profile': _handle_reroute_document_profile, + 'retry_order_extraction': _handle_retry_order_extraction, + 'revalidate_reservation': _handle_recheck_task_gates, + 'retry_customer_resolution': _handle_recheck_task_gates, + 'retry_duplicate_detection': _handle_recheck_task_gates, + 'retry_task_creation': _handle_retry_task_creation, + 'retry_inventory_preparation': _handle_retry_inventory_preparation, + 'poll_inventory_preparation': _handle_retry_inventory_preparation, + 'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping, + 'retry_inventory_matching': _handle_retry_inventory_matching, + 'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency, + 'recheck_excel_readiness': _handle_recheck_excel_readiness, + 'regenerate_excel_artifact': _handle_regenerate_excel, + 'regenerate_manual_upload_todo': _handle_regenerate_manual_upload_todo, + 'open_order_review': _manual_open('open_order_review', 'order_freeze_readiness'), + 'open_inventory_source_review': _manual_open('open_inventory_source_review', 'inventory_source_routing'), + 'open_profile_review': _manual_open('open_profile_review', 'document_profile_routing'), + 'edit_order_fields': _manual_open('edit_order_fields', 'field_completeness'), + 'edit_reservation': _manual_open('edit_reservation', 'reservation_validation'), + 'confirm_customer': _manual_open('confirm_customer', 'customer_resolution'), + 'adjudicate_duplicate': _manual_open('adjudicate_duplicate', 'duplicate_detection'), + 'resolve_field_conflicts': _manual_open('resolve_field_conflicts', 'field_conflict_resolution'), + 'open_inventory_match_review': _manual_open('open_inventory_match_review', 'inventory_matching'), + 'open_shortage_review': _manual_open('open_shortage_review', 'inventory_sufficiency'), + 'upload_inventory_file': _manual_open('upload_inventory_file', 'inventory_preparation'), + 'confirm_inventory_field_mapping': _manual_open( + 'confirm_inventory_field_mapping', 'inventory_field_mapping', + ), + } + handler = handlers.get(action_code) + if handler is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': gate.blocking_reason_code or 'not_recoverable', + 'blocking_reason_json': { + 'action_code': action_code, + 'message': '未注册的恢复动作', + }, + 'effective_result_json': { + 'findings': [], + 'action_code': action_code, + 'error': 'unknown_action', + }, + 'output_snapshot': {'action_code': action_code, 'payload': payload}, + 'error_code': 'SHIPPING.PROCESS_GATE_ACTION_INVALID', + 'error_summary': f'unknown action {action_code}', + } + # [STEP] 校验动作归属当前 Gate(契约 default_next_actions 或库存附属动作)。 + _assert_action_belongs_to_gate(gate_code=gate.gate_code, action_code=action_code) + return handler(execution=execution, gate=gate, payload=payload) + + +def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None: + """ + 校验动作码属于目标 Gate。 + + Raises: + ValidationError: 动作与门禁不匹配。 + """ + definition = get_process_gate_definition(gate_code) + allowed = { + str(value) + for value in (definition.get('default_next_actions') or {}).values() + if value + } + if gate_code == 'inventory_source_routing': + allowed |= { + 'adopt_rule_suggestion', + 'keep_manual_inventory_decision', + 'retry_with_latest_rules', + } + nav_owning = { + 'open_order_review': {'order_freeze_readiness', 'order_field_extraction'}, + 'open_inventory_source_review': {'inventory_source_routing'}, + 'open_profile_review': {'document_profile_routing'}, + 'edit_order_fields': {'field_completeness'}, + 'edit_reservation': {'reservation_validation'}, + 'confirm_customer': {'customer_resolution'}, + 'adjudicate_duplicate': {'duplicate_detection'}, + 'resolve_field_conflicts': {'field_conflict_resolution'}, + 'open_inventory_match_review': {'inventory_matching'}, + 'open_shortage_review': {'inventory_sufficiency'}, + 'upload_inventory_file': {'inventory_preparation'}, + 'confirm_inventory_field_mapping': {'inventory_field_mapping'}, + 'regenerate_manual_upload_todo': {'manual_upload_handoff'}, + } + if action_code in allowed: + return + if action_code in nav_owning and gate_code in nav_owning[action_code]: + return + raise ValidationError( + 'Action does not belong to this gate', + code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', + details={'gate_code': gate_code, 'action_code': action_code, 'allowed': sorted(allowed)}, + ) + + +def _manual_open(action: str, owning_gate: str) -> Callable[..., dict[str, Any]]: + """人工入口动作:保持 blocked_manual,并返回 navigation 提示供前端跳转。""" + + def _inner(*, execution: ShippingProcessExecution, gate: ShippingProcessGate, payload: dict[str, Any]) -> dict[str, Any]: + if gate.gate_code != owning_gate and not ( + action == 'open_order_review' + and gate.gate_code in {'order_freeze_readiness', 'order_field_extraction'} + ): + raise ValidationError( + 'Action does not belong to this gate', + code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', + details={'gate_code': gate.gate_code, 'action_code': action}, + ) + reason = gate.blocking_reason_code or 'freeze_not_ready' + if owning_gate_for_reason(str(reason)) is None: + reason = 'freeze_not_ready' if owning_gate == 'order_freeze_readiness' else reason + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': reason, + 'blocking_reason_json': { + 'action_code': action, + 'message': '请前往业务页面完成人工处理', + 'navigation': True, + 'payload': payload, + }, + 'recommendation_json': { + 'navigation_action': action, + 'dispatch_mode': 'navigate', + }, + 'effective_result_json': { + 'findings': [{ + 'finding_code': f'manual_{action}', + 'owning_gate_code': owning_gate, + 'severity': 'blocking', + 'reason_code': reason, + 'user_visible': True, + 'blocks_current_action': True, + }], + 'navigation_action': action, + }, + 'output_snapshot': { + 'action_code': action, + 'execution_no': execution.execution_no, + 'dispatch_mode': 'navigate', + }, + } + + return _inner + + +def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) -> dict[str, Any]: + """构造履约 workflow 所需 payload。""" + from app.models import ShippingTask + + task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + raise ValidationError('Execution has no bound task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND') + return { + 'task_id': str(task.task_no), + 'source': 'process_gate', + 'operator_id': payload.get('actor_user_id') or payload.get('user_id'), + } + + +def _tool_outcome( + *, + action_code: str, + response: dict[str, Any], + passed_statuses: set[str] | None = None, + waiting_statuses: set[str] | None = None, + invalidate_change_type: str | None = None, + blocking_reason_code: str | None = None, +) -> dict[str, Any]: + """将 tool_response 风格结果映射为 Gate Attempt outcome。""" + status = str((response or {}).get('status') or '').strip().lower() + passed_statuses = passed_statuses or {'ok', 'success', 'passed'} + waiting_statuses = waiting_statuses or {'waiting', 'waiting_external'} + if status in passed_statuses: + outcome = 'passed' + elif status in waiting_statuses: + outcome = 'waiting_external' + elif status in {'needs_human', 'blocked', 'failed'}: + outcome = 'blocked_manual' if status == 'needs_human' else 'blocked_retryable' + else: + outcome = 'blocked_retryable' + return { + 'outcome': outcome, + 'blocking_reason_code': None if outcome == 'passed' else ( + blocking_reason_code or str((response or {}).get('error_code') or 'gate_invalidated')[:64] + ), + 'blocking_reason_json': {'tool_status': status, 'message': (response or {}).get('message')}, + 'effective_result_json': { + 'findings': [], + 'tool_status': status, + 'action_code': action_code, + }, + 'output_snapshot': {'action_code': action_code, 'response_keys': list((response or {}).keys())}, + 'invalidate_change_type': invalidate_change_type if outcome == 'passed' else None, + 'error_summary': None if outcome == 'passed' else str((response or {}).get('message') or '')[:2000] or None, + } + + +def _handle_rematerialize_document( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 重新物化/确认文档可用性。 + + 核心逻辑:检查 WorkflowItem 当前文档与资产是否可用;必要时对 Run 重跑输入物化; + 仅同步 document_materialization,禁止伪造版面/Profile/抽取通过。 + """ + from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeWorkflowItem, ShippingOrderExtractionRun + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + item = ShippingNoticeWorkflowItem.query.get(int(execution.workflow_item_id)) + if item is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'document_unavailable', + 'effective_result_json': {'findings': [], 'error': 'workflow_item_missing'}, + 'output_snapshot': {'action_code': 'rematerialize_document'}, + } + + # [STEP 1] 若绑定抽取 Run,尝试按计划重新物化输入文档(不触发 PDF 重识别以外的抽取)。 + rematerialized = False + if item.current_run_no: + run = ShippingOrderExtractionRun.query.filter_by(run_no=str(item.current_run_no)).first() + if run is not None: + try: + from app.services.shipping_notice.order_extraction_run_service import ( + materialize_order_extraction_run_inputs, + ) + materialize_order_extraction_run_inputs(run=run) + rematerialized = True + except Exception as exc: + safe = sanitize_gate_error_text(exc, max_len=500) or 'materialize_failed' + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'document_unavailable', + 'blocking_reason_json': {'message': safe}, + 'effective_result_json': {'findings': [], 'error': 'materialize_failed'}, + 'output_snapshot': { + 'action_code': 'rematerialize_document', + 'error': sanitize_gate_error_text(exc, max_len=200), + }, + 'error_summary': sanitize_gate_error_text(exc, max_len=2000), + } + + # [STEP 2] 校验当前文档与资产真实可用。 + document = None + if item.current_document_id: + document = ShippingNoticeDocument.query.get(int(item.current_document_id)) + asset_ok = False + if document is not None and document.asset_id: + asset = FileAsset.query.get(int(document.asset_id)) + asset_ok = asset is not None and bool(str(getattr(asset, 'storage_key', None) or '').strip()) + + docs_ok = document is not None and asset_ok + apply_gate_outcome( + execution=execution, + gate_code='document_materialization', + passed=docs_ok, + effective_result={ + 'findings': [] if docs_ok else [{ + 'finding_code': 'document_unavailable', + 'owning_gate_code': 'document_materialization', + 'severity': 'blocking', + 'reason_code': 'document_unavailable', + 'user_visible': True, + 'blocks_current_action': True, + }], + 'document_id': int(document.id) if document else None, + 'rematerialized': rematerialized, + }, + blocking_reason_code=None if docs_ok else 'document_unavailable', + actor_type='system', + actor_id=payload.get('actor_user_id'), + idempotency_key=f'remat:{execution.execution_no}:{docs_ok}:{item.current_document_id or 0}', + force=True, + ) + if not docs_ok: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'document_unavailable', + 'effective_result_json': {'findings': [], 'document_missing': True}, + 'output_snapshot': {'action_code': 'rematerialize_document', 'passed': False}, + } + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'action_code': 'rematerialize_document', 'document_id': int(document.id)}, + 'output_snapshot': {'action_code': 'rematerialize_document', 'document_id': int(document.id)}, + } + + +def _handle_retry_layout_parsing( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重试 PDF 版面解析:排程 layout Job。""" + from app.models import ShippingNoticeDocument, ShippingNoticeWorkflowItem + from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts + + item = ShippingNoticeWorkflowItem.query.get(int(execution.workflow_item_id)) + if item is None or not item.current_document_id: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'layout_parse_failed', + 'effective_result_json': {'findings': [], 'error': 'document_missing'}, + 'output_snapshot': {'action_code': 'retry_layout_parsing'}, + } + document = ShippingNoticeDocument.query.get(int(item.current_document_id)) + if document is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'layout_parse_failed', + 'effective_result_json': {'findings': [], 'error': 'document_missing'}, + 'output_snapshot': {'action_code': 'retry_layout_parsing'}, + } + created_by = payload.get('actor_user_id') + schedule_document_layouts([document], created_by_id=int(created_by) if created_by else None) + return { + 'outcome': 'waiting_external', + 'blocking_reason_code': 'layout_parse_failed', + 'blocking_reason_json': {'message': '版面解析已重新排队'}, + 'effective_result_json': {'findings': [], 'queued': True}, + 'output_snapshot': {'action_code': 'retry_layout_parsing', 'document_id': int(document.id)}, + } + + +def _handle_reroute_document_profile( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 独立重路由 Profile:仅依据已有 RouteDecision / 布局结果重评,禁止重新识别 PDF。 + + 核心逻辑:读取 Run 上最新路由决策;已选中 Profile 则通过本门禁; + 歧义/未匹配则 blocked_manual,引导 open_profile_review。 + """ + from app.models import ( + ShippingNoticeWorkflowItem, + ShippingOrderExtractionRouteDecision, + ShippingOrderExtractionRun, + ) + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + item = ShippingNoticeWorkflowItem.query.get(int(execution.workflow_item_id)) + if item is None or not item.current_run_no: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'profile_not_matched', + 'recommendation_json': {'navigation_action': 'open_profile_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'error': 'run_missing'}, + 'output_snapshot': {'action_code': 'reroute_document_profile'}, + } + run = ShippingOrderExtractionRun.query.filter_by(run_no=str(item.current_run_no)).first() + if run is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'profile_not_matched', + 'recommendation_json': {'navigation_action': 'open_profile_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'error': 'run_missing'}, + 'output_snapshot': {'action_code': 'reroute_document_profile'}, + } + decisions = ( + ShippingOrderExtractionRouteDecision.query + .filter_by(run_id=int(run.id)) + .order_by(ShippingOrderExtractionRouteDecision.id.desc()) + .limit(20) + .all() + ) + selected: list[str] = [] + ambiguous = False + for decision in decisions: + match_status = str(decision.match_status or '') + profile = str(decision.selected_profile_code or '').strip() + reasons = decision.fallback_reason_codes_json if isinstance(decision.fallback_reason_codes_json, list) else [] + if match_status in {'ambiguous', 'no_match', 'layout_drift', 'evidence_insufficient'} or str(decision.decision or '') == 'review_required': + ambiguous = True + if any('ambiguous' in str(code).lower() for code in reasons): + ambiguous = True + if profile and match_status in {'unique_match', 'selected_by_score'}: + selected.append(profile) + routed = bool(selected) and not ambiguous and len(set(selected)) == 1 + reason_code = None if routed else ( + 'profile_ambiguous' if ambiguous or len(set(selected)) > 1 else 'profile_not_matched' + ) + apply_gate_outcome( + execution=execution, + gate_code='document_profile_routing', + passed=routed, + outcome=None if routed else 'blocked_manual', + effective_result={ + 'findings': [] if routed else [{ + 'finding_code': 'document_profile_routing_blocked', + 'owning_gate_code': 'document_profile_routing', + 'severity': 'blocking', + 'reason_code': reason_code, + 'user_visible': True, + 'blocks_current_action': True, + }], + 'selected_profiles': selected, + 'reroute_only': True, + }, + blocking_reason_code=reason_code, + actor_type='system', + actor_id=payload.get('actor_user_id'), + idempotency_key=f'profile-reroute:{execution.execution_no}:{",".join(sorted(set(selected))) or "none"}', + force=True, + ) + if routed: + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'selected_profile': selected[0]}, + 'output_snapshot': {'action_code': 'reroute_document_profile', 'selected_profile': selected[0]}, + 'invalidate_change_type': 'document_profile_changed', + } + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': reason_code, + 'recommendation_json': {'navigation_action': 'open_profile_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'navigation_action': 'open_profile_review'}, + 'output_snapshot': {'action_code': 'reroute_document_profile', 'selected_profiles': selected}, + } + + +def _handle_retry_order_extraction( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重试订单抽取 Run(仅 order_field_extraction 门禁)。""" + from app.models import ShippingNoticeWorkflowItem + from app.services.shipping_notice.order_extraction_run_service import retry_order_extraction_run + + item = ShippingNoticeWorkflowItem.query.get(int(execution.workflow_item_id)) + if item is None or not item.current_run_no: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'extraction_incomplete', + 'effective_result_json': {'findings': [], 'error': 'run_missing'}, + 'output_snapshot': {'action_code': 'retry_order_extraction'}, + } + user_id = int(payload.get('actor_user_id') or item.owner_user_id or 0) + run, _replay = retry_order_extraction_run(user_id=user_id, run_no=str(item.current_run_no)) + return { + 'outcome': 'waiting_external' if str(run.status or '') in {'queued', 'running', 'extracting'} else 'passed', + 'blocking_reason_code': None if str(run.status or '') not in {'queued', 'running', 'extracting'} else 'extraction_incomplete', + 'effective_result_json': {'findings': [], 'run_no': run.run_no, 'run_status': run.status}, + 'output_snapshot': {'action_code': 'retry_order_extraction', 'run_no': run.run_no}, + 'invalidate_change_type': 'pdf_or_extraction_changed', + } + + +def _handle_retry_task_creation( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 重试 Task 创建:已绑定则通过;否则尝试 confirm_review_case 真实建单。 + """ + from app.models import ShippingOrderReviewCase + from app.services.shipping_notice.process_gate_service import bind_execution_task + + if execution.task_id: + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'task_id': int(execution.task_id)}, + 'output_snapshot': {'action_code': 'retry_task_creation', 'already_bound': True}, + } + case = ShippingOrderReviewCase.query.get(int(execution.review_case_id)) if execution.review_case_id else None + if case is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'task_creation_failed', + 'blocking_reason_json': {'message': '缺少复核 Case,无法自动建单'}, + 'recommendation_json': {'navigation_action': 'open_order_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'navigation_action': 'open_order_review'}, + 'output_snapshot': {'action_code': 'retry_task_creation'}, + } + if case.status == 'confirmed' and case.confirmed_task_id: + bind_execution_task( + execution_no=str(execution.execution_no), + task_id=int(case.confirmed_task_id), + actor_type='system', + actor_id=payload.get('actor_user_id'), + ) + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'task_id': int(case.confirmed_task_id)}, + 'output_snapshot': {'action_code': 'retry_task_creation', 'bound_existing': True}, + } + + draft = case.current_draft + user_id = int(payload.get('actor_user_id') or case.owner_user_id or 0) + if user_id <= 0 or draft is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'task_creation_failed', + 'recommendation_json': {'navigation_action': 'open_order_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'navigation_action': 'open_order_review'}, + 'output_snapshot': {'action_code': 'retry_task_creation', 'need_draft': True}, + } + try: + from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case + + result = confirm_review_case( + user_id=user_id, + case_no=str(case.case_no), + expected_draft_version=int(draft.draft_version), + idempotency_key=str( + payload.get('idempotency_key') + or f'gate-retry-task:{execution.execution_no}:{gate.evaluation_version}' + ), + warning_acknowledgements=payload.get('warning_acknowledgements') or [], + confirm_note='process_gate_retry_task_creation', + ) + task_no = (result or {}).get('task_no') + if task_no: + from app.models import ShippingTask + + task = ShippingTask.query.filter_by(task_no=str(task_no)).first() + if task is not None: + bind_execution_task( + execution_no=str(execution.execution_no), + task_id=int(task.id), + actor_type='system', + actor_id=user_id, + ) + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'task_no': task_no}, + 'output_snapshot': {'action_code': 'retry_task_creation', 'task_no': task_no}, + } + except Exception as exc: + safe = sanitize_gate_error_text(exc, max_len=500) or 'task_creation_failed' + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'task_creation_failed', + 'blocking_reason_json': {'message': safe}, + 'recommendation_json': {'navigation_action': 'open_order_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'navigation_action': 'open_order_review'}, + 'output_snapshot': { + 'action_code': 'retry_task_creation', + 'error': sanitize_gate_error_text(exc, max_len=200), + }, + 'error_summary': sanitize_gate_error_text(exc, max_len=2000), + } + + +def _handle_retry_inventory_preparation( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重试/轮询库存准备。""" + from app.services.shipping_notice.inventory_workflow import ensure_inventory + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + response = ensure_inventory(_task_payload(execution, payload)) + outcome = _tool_outcome( + action_code='retry_inventory_preparation', + response=response, + waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'}, + blocking_reason_code='inventory_preparation_failed', + ) + sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) + return outcome + + +def _handle_retry_inventory_field_mapping( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 重试库存字段映射:检查活跃库存文件 mapping_confirmed / 已解析行,不重跑库存准备。 + """ + from app.models import ShippingTask + from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'inventory_mapping_required', + 'recommendation_json': { + 'navigation_action': 'confirm_inventory_field_mapping', + 'dispatch_mode': 'navigate', + }, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'retry_inventory_field_mapping'}, + } + inv_file = active_inventory_file_for_task(task) + mapped = bool( + inv_file is not None + and bool(getattr(inv_file, 'mapping_confirmed', False)) + and ( + isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0 + ) + ) + apply_gate_outcome( + execution=execution, + gate_code='inventory_field_mapping', + passed=mapped, + outcome=None if mapped else 'blocked_manual', + effective_result={ + 'findings': [], + 'mapping_confirmed': bool(getattr(inv_file, 'mapping_confirmed', False)) if inv_file else False, + 'inventory_file_id': int(inv_file.id) if inv_file else None, + }, + blocking_reason_code=None if mapped else 'inventory_mapping_required', + actor_type='system', + actor_id=payload.get('actor_user_id'), + idempotency_key=f'inv-map:{execution.execution_no}:{mapped}:{getattr(inv_file, "id", 0)}', + force=True, + ) + if mapped: + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'mapping_confirmed': True}, + 'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': True}, + } + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'inventory_mapping_required', + 'recommendation_json': { + 'navigation_action': 'confirm_inventory_field_mapping', + 'dispatch_mode': 'navigate', + }, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': False}, + } + + +def _handle_retry_inventory_matching( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重试库存匹配(仅 inventory_matching)。""" + from app.services.shipping_notice.fulfillment_workflow import match_inventory + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + response = match_inventory(_task_payload(execution, payload)) + outcome = _tool_outcome( + action_code='retry_inventory_matching', + response=response, + blocking_reason_code='inventory_match_failed', + invalidate_change_type=None, + ) + sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) + return outcome + + +def _handle_recheck_inventory_sufficiency( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """独立库存满足性复核:读取 match_status / shortage_json,不重跑匹配。""" + from app.models import ShippingTask + from app.services.shipping_notice.fulfillment_workflow import match_completed + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'inventory_insufficient', + 'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency'}, + } + sufficient = match_completed(task) + shortage = task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None + apply_gate_outcome( + execution=execution, + gate_code='inventory_sufficiency', + passed=sufficient, + outcome=None if sufficient else 'blocked_manual', + effective_result={ + 'findings': [], + 'match_status': task.match_status, + 'shortage': shortage, + }, + blocking_reason_code=None if sufficient else 'inventory_insufficient', + actor_type='system', + actor_id=payload.get('actor_user_id'), + idempotency_key=f'inv-suff:{execution.execution_no}:{task.match_status}:{sufficient}', + force=True, + ) + if sufficient: + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'match_status': task.match_status}, + 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True}, + } + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'inventory_insufficient', + 'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'shortage': shortage}, + 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': False}, + } + + +def _handle_recheck_excel_readiness( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """Excel 生成资格检查:只跑 excel_gate_error,不生成 Artifact。""" + from app.models import ShippingTask + from app.services.shipping_notice.fulfillment_workflow import excel_gate_error + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'excel_not_ready', + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'recheck_excel_readiness'}, + } + gate_error = excel_gate_error(task) + ready = gate_error is None + apply_gate_outcome( + execution=execution, + gate_code='excel_readiness', + passed=ready, + effective_result={'findings': [], 'excel_gate_error': gate_error}, + blocking_reason_code=None if ready else 'excel_not_ready', + actor_type='system', + actor_id=payload.get('actor_user_id'), + idempotency_key=f'excel-ready:{execution.execution_no}:{ready}:{task.match_status}', + force=True, + ) + if ready: + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'ready': True}, + 'output_snapshot': {'action_code': 'recheck_excel_readiness', 'passed': True}, + } + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'excel_not_ready', + 'blocking_reason_json': {'message': gate_error}, + 'effective_result_json': {'findings': [], 'excel_gate_error': gate_error}, + 'output_snapshot': {'action_code': 'recheck_excel_readiness', 'passed': False}, + } + + +def _handle_regenerate_excel( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重新生成 Excel Artifact(artifact_generation 门禁)。""" + from app.services.shipping_notice.fulfillment_workflow import generate_excel + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + response = generate_excel(_task_payload(execution, payload)) + outcome = _tool_outcome( + action_code='regenerate_excel_artifact', + response=response, + blocking_reason_code='artifact_generation_failed', + ) + sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) + return outcome + + +def _handle_regenerate_manual_upload_todo( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重生人工上传待办:同步 Workflow 阶段为 manual_upload_pending。""" + from app.models import ShippingTask + from app.services.shipping_notice.workflow_ledger_service import sync_workflow_item_stage_for_task + + task = ShippingTask.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + return _manual_open('regenerate_manual_upload_todo', 'manual_upload_handoff')( + execution=execution, gate=gate, payload=payload, + ) + sync_workflow_item_stage_for_task( + task_no=str(task.task_no), + lifecycle_status='manual_upload_pending', + event_code='manual_upload_pending', + actor_type='user', + actor_id=payload.get('actor_user_id'), + payload={'task_no': task.task_no, 'source': 'process_gate'}, + ) + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'manual_upload_pending', + 'blocking_reason_json': {'message': '请下载 Excel 并在货代平台上传后登记凭据'}, + 'recommendation_json': {'navigation_action': 'regenerate_manual_upload_todo', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': [], 'navigation_action': 'regenerate_manual_upload_todo'}, + 'output_snapshot': {'action_code': 'regenerate_manual_upload_todo', 'task_no': task.task_no}, + } + + +def _handle_recheck_task_gates( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """通用:按当前 Task/复核状态重同步履约前门禁。""" + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + if not execution.task_id: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': gate.blocking_reason_code or 'review_required', + 'recommendation_json': {'navigation_action': 'open_order_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'recheck', 'need_review': True}, + } + sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) + refreshed = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code=gate.gate_code, + ).first() + if refreshed and refreshed.status == 'passed': + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'rechecked': True}, + 'output_snapshot': {'action_code': 'recheck', 'passed': True}, + } + return { + 'outcome': 'blocked_manual' if (refreshed and refreshed.status == 'blocked_manual') else 'blocked_retryable', + 'blocking_reason_code': (refreshed.blocking_reason_code if refreshed else gate.blocking_reason_code), + 'effective_result_json': {'findings': [], 'rechecked': True}, + 'output_snapshot': {'action_code': 'recheck'}, + } + + +def _handle_inventory_reroute( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """委托复核 Draft 库存源重路由。""" + from app.models import ShippingOrderReviewCase + from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing + + if gate.gate_code != 'inventory_source_routing': + raise ValidationError( + 'Action does not belong to this gate', + code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', + ) + case = ShippingOrderReviewCase.query.get(int(execution.review_case_id or 0)) + if case is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'no_inventory_source_candidates', + 'blocking_reason_json': {'error': 'review_case_required'}, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'retry_with_latest_rules'}, + } + user_id = int(payload.get('actor_user_id') or payload.get('user_id') or 0) + if user_id <= 0: + raise ValidationError('actor_user_id required for inventory reroute', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + result = reroute_inventory_routing( + user_id=user_id, + case_no=str(case.case_no), + expected_draft_version=payload.get('expected_draft_version'), + idempotency_key=str(payload.get('idempotency_key') or f'gate-reroute-{gate.id}-{gate.evaluation_version}'), + line_key=str(payload.get('line_key') or '').strip() or None, + ) + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'routing': {'case_no': case.case_no}}, + 'output_snapshot': {'action_code': 'retry_with_latest_rules', 'result_keys': list((result or {}).keys())}, + 'invalidate_change_type': 'inventory_source_changed', + } + + +def _handle_adopt_suggestion( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """采用规则建议为有效库存源候选。""" + from app.models import ShippingOrderReviewCase + from app.services.shipping_notice.order_review_draft_service import adopt_inventory_routing_suggestion + + if gate.gate_code != 'inventory_source_routing': + raise ValidationError( + 'Action does not belong to this gate', + code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', + ) + case = ShippingOrderReviewCase.query.get(int(execution.review_case_id or 0)) + if case is None: + raise ValidationError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') + line_key = str(payload.get('line_key') or '').strip() + user_id = int(payload.get('actor_user_id') or payload.get('user_id') or 0) + if not line_key or user_id <= 0: + raise ValidationError('line_key and actor_user_id required', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + result = adopt_inventory_routing_suggestion( + user_id=user_id, + case_no=str(case.case_no), + line_key=line_key, + expected_draft_version=payload.get('expected_draft_version'), + idempotency_key=str(payload.get('idempotency_key') or f'gate-adopt-{gate.id}-{line_key}'), + reason=str(payload.get('reason') or 'gate_recovery_adopt'), + ) + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'adopt': {'line_key': line_key}}, + 'output_snapshot': {'action_code': 'adopt_rule_suggestion', 'result_keys': list((result or {}).keys())}, + 'invalidate_change_type': 'inventory_source_changed', + } + + +def _handle_keep_manual( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """保留人工库存源决定。""" + from app.models import ShippingOrderReviewCase + from app.services.shipping_notice.order_review_draft_service import keep_manual_inventory_routing + + if gate.gate_code != 'inventory_source_routing': + raise ValidationError( + 'Action does not belong to this gate', + code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', + ) + case = ShippingOrderReviewCase.query.get(int(execution.review_case_id or 0)) + if case is None: + raise ValidationError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') + line_key = str(payload.get('line_key') or '').strip() + user_id = int(payload.get('actor_user_id') or payload.get('user_id') or 0) + if not line_key or user_id <= 0: + raise ValidationError('line_key and actor_user_id required', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + result = keep_manual_inventory_routing( + user_id=user_id, + case_no=str(case.case_no), + line_key=line_key, + expected_draft_version=payload.get('expected_draft_version'), + idempotency_key=str(payload.get('idempotency_key') or f'gate-keep-{gate.id}-{line_key}'), + reason=str(payload.get('reason') or 'gate_recovery_keep_manual'), + ) + return { + 'outcome': 'passed', + 'effective_result_json': {'findings': [], 'keep_manual': {'line_key': line_key}}, + 'output_snapshot': {'action_code': 'keep_manual_inventory_decision', 'result_keys': list((result or {}).keys())}, + } + + +def _handle_recheck_freeze( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """重新评估冻结就绪;有 Task+Extraction 时走标准 Gate 评估。""" + from app.models import ShippingOrderExtraction, ShippingTask + from app.services.shipping_notice.freeze_readiness_service import evaluate_freeze_readiness_gate + + if not execution.task_id: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'freeze_not_ready', + 'blocking_reason_json': {'message': '自动建单策略尚未放行', 'need_task': True}, + 'recommendation_json': {'navigation_action': 'open_order_review', 'dispatch_mode': 'navigate'}, + 'effective_result_json': { + 'findings': [{ + 'finding_code': 'auto_freeze_policy_not_approved', + 'owning_gate_code': 'order_freeze_readiness', + 'severity': 'blocking', + 'reason_code': 'auto_freeze_not_enabled', + 'user_visible': True, + 'blocks_current_action': True, + }], + 'navigation_action': 'open_order_review', + }, + 'output_snapshot': {'action_code': 'recheck_freeze_readiness'}, + } + task = ShippingTask.query.get(int(execution.task_id)) + extraction = None + if task is not None and task.order_extraction_id: + extraction = ShippingOrderExtraction.query.get(int(task.order_extraction_id)) + if task is None or extraction is None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'freeze_not_ready', + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'recheck_freeze_readiness', 'missing': True}, + } + result = evaluate_freeze_readiness_gate( + task=task, + extraction=extraction, + configs={}, + freeze_mode=str(payload.get('freeze_mode') or 'manual'), + auto_freeze_policy=payload.get('auto_freeze_policy') if isinstance(payload.get('auto_freeze_policy'), dict) else None, + ) + return { + 'outcome': 'passed' if result.get('passed') else 'blocked_manual', + 'blocking_reason_code': result.get('blocking_reason_code'), + 'blocking_reason_json': {'issues': result.get('issues')}, + 'effective_result_json': {'findings': result.get('findings') or []}, + 'output_snapshot': result, + } diff --git a/backend/app/services/shipping_notice/process_gate_job_service.py b/backend/app/services/shipping_notice/process_gate_job_service.py new file mode 100644 index 00000000..8903d846 --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_job_service.py @@ -0,0 +1,403 @@ +""" +services/shipping_notice/process_gate_job_service.py + +用途:门禁 Attempt 的 Job 入队、租约心跳、陈旧租约接管、外部等待轮询与 Worker 执行入口。 +依赖:app.jobs.queue、JobType、ShippingProcessGateAttempt、process_gate_executor、 + process_gate_service、fulfillment_audit。 +逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用 + claim_and_run_gate_attempt;重试/轮询使用 force_new 避免复用 running Job; + waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见。 +""" + +from __future__ import annotations + +import logging +import threading +import uuid +from datetime import datetime, timedelta +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import ConflictError, NotFoundError +from app.jobs.queue import enqueue +from app.jobs.types import JobType +from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt +from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit +from app.services.shipping_notice.process_gate_executor import execute_queued_attempt +from app.services.shipping_notice.process_gate_service import mark_attempt_running + +_LOGGER = logging.getLogger(__name__) + +# 与发货通知共用 domain,便于 shipping worker 一并领取。 +SHIPPING_PROCESS_GATE_JOB_DOMAIN = 'shipping_notice' + + +def _utc_now() -> datetime: + """naive UTC。""" + return datetime.utcnow() + + +def _lease_seconds() -> int: + """租约时长(秒),默认 60。""" + return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_LEASE_SECONDS', 60) or 60), 15) + + +def _takeover_seconds() -> int: + """接管阈值(秒),默认 120。""" + return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS', 120) or 120), 30) + + +def _heartbeat_seconds() -> int: + """心跳间隔(秒),默认 15。""" + return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS', 15) or 15), 5) + + +def enqueue_gate_attempt_job( + *, + attempt_id: int, + created_by_id: int | None = None, + delay_seconds: int = 0, + force_new: bool = False, +) -> int: + """ + 为 Attempt 入队 Gate Job,并回写 attempt.job_id。 + + 核心逻辑:默认仅对 queued 去重,绝不复用仍 running 的同 business_ref Job; + force_new 时使用带时间戳的 business_ref,保证重试/轮询一定新建可领取 Job。 + + Args: + attempt_id: Attempt 主键。 + created_by_id: 可选创建人。 + delay_seconds: 延迟入队秒数。 + force_new: True 时强制新建 Job(重试/外部等待轮询)。 + + Returns: + Job 主键。 + """ + 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') + if attempt.job_id and not force_new: + return int(attempt.job_id) + + scheduled_at = None + if delay_seconds and int(delay_seconds) > 0: + scheduled_at = _utc_now() + timedelta(seconds=int(delay_seconds)) + + max_attempts = int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3) + # [STEP] force_new 用独立 business_ref,避免与刚结束/仍残留的 Job 去重冲突。 + if force_new: + business_ref = f'attempt:{int(attempt.id)}:r{_utc_now().strftime("%Y%m%d%H%M%S")}:{uuid.uuid4().hex[:8]}' + else: + business_ref = f'attempt:{int(attempt.id)}' + job_id = enqueue( + JobType.SHIPPING_PROCESS_GATE, + {'attempt_id': int(attempt.id)}, + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + business_ref=business_ref, + created_by_id=created_by_id, + message='等待执行门禁恢复 Attempt', + max_attempts=max(max_attempts, 1), + scheduled_at=scheduled_at, + # 仅匹配 queued:禁止复用仍 running 的旧 Job(重试场景)。 + dedupe_statuses=('queued',), + dedupe_active=not force_new, + commit=False, + ) + attempt.job_id = int(job_id) + db.session.flush() + return int(job_id) + + +def schedule_waiting_external_poll( + *, + attempt_id: int, + gate_code: str | None = None, +) -> int | None: + """ + waiting_external 成功后调度下一次 poll Attempt;超时则转入 blocked_manual。 + + 核心逻辑:读取 Gate.effective_result_json.waiting_since;超过 + SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS(默认 1800)则不再入队, + 而是将 Gate 置为 blocked_manual 并写入超时原因。 + + Returns: + 新 Job id;超时或无需调度时 None。 + """ + from app.services.shipping_notice.process_gate_contract import primary_next_action_for_gate + from app.services.shipping_notice.process_gate_service import queue_gate_attempt, complete_gate_attempt + + finished = db.session.get(ShippingProcessGateAttempt, int(attempt_id)) + if finished is None: + return None + gate = db.session.get(ShippingProcessGate, int(finished.gate_id)) + if gate is None or gate.status != 'waiting_external': + return None + + effective = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {} + waiting_since_raw = effective.get('waiting_since') + now = _utc_now() + if waiting_since_raw: + try: + waiting_since = datetime.fromisoformat(str(waiting_since_raw)) + except ValueError: + waiting_since = gate.updated_at or now + else: + waiting_since = gate.updated_at or now + effective = {**effective, 'waiting_since': waiting_since.isoformat()} + gate.effective_result_json = effective + db.session.flush() + + timeout_sec = max( + int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS', 1800) or 1800), + 60, + ) + if (now - waiting_since).total_seconds() >= timeout_sec: + # [STEP] 超时:创建 Attempt 将 Gate 转为人工阻断,停止无限轮询。 + execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) + if execution is None: + return None + poll_attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code=gate.gate_code, + trigger_type='auto', + actor_type='system', + actor_id='external-wait-timeout', + idempotency_key=f'wait-timeout:{gate.id}:{gate.evaluation_version}', + input_snapshot={ + 'action_code': primary_next_action_for_gate( + gate_code=gate.gate_code, status='blocked_manual', + ) or 'open_order_review', + 'payload': {'reason': 'external_wait_timeout'}, + }, + ) + if poll_attempt.status in {'queued', 'running'}: + mark_attempt_running(attempt_id=int(poll_attempt.id), worker_id='system-timeout') + complete_gate_attempt( + attempt_id=int(poll_attempt.id), + outcome='blocked_manual', + blocking_reason_code=gate.blocking_reason_code or 'gate_invalidated', + blocking_reason_json={ + 'message': '外部等待超时,请人工处理', + 'waiting_since': waiting_since.isoformat(), + 'timeout_seconds': timeout_sec, + }, + effective_result_json={ + 'findings': [], + 'external_wait_timeout': True, + 'waiting_since': waiting_since.isoformat(), + }, + output_snapshot={'action_code': 'external_wait_timeout'}, + ) + return None + + poll_seconds = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5) + action = gate.next_action_code or primary_next_action_for_gate( + gate_code=gate.gate_code, status='waiting_external', + ) + if not action: + action = 'poll_inventory_preparation' + execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) + if execution is None: + return None + poll_attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code=gate.gate_code, + trigger_type='auto', + actor_type='system', + actor_id='external-wait-poll', + idempotency_key=f'wait-poll:{gate.id}:{gate.evaluation_version}:{int(now.timestamp())}', + input_snapshot={'action_code': action, 'payload': {'poll': True}}, + ) + if poll_attempt.status not in {'queued', 'running'}: + return int(poll_attempt.job_id) if poll_attempt.job_id else None + return enqueue_gate_attempt_job( + attempt_id=int(poll_attempt.id), + delay_seconds=poll_seconds, + force_new=True, + ) + + +def heartbeat_gate_attempt( + *, + attempt_id: int, + worker_id: str, + lease_token: str, +) -> ShippingProcessGateAttempt: + """ + 续租并刷新心跳;不写业务审计。 + + Raises: + ConflictError: 租约不匹配。 + """ + 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') + if attempt.status != 'running': + raise ConflictError('Attempt is not running', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE') + if str(attempt.lease_token or '') != str(lease_token or '') or str(attempt.worker_id or '') != str(worker_id or ''): + raise ConflictError('Lease token mismatch', code='SHIPPING.PROCESS_GATE_LEASE_CONFLICT') + now = _utc_now() + attempt.heartbeat_at = now + attempt.lease_expires_at = now + timedelta(seconds=_lease_seconds()) + # [STEP] 立即提交,使其他 Worker 的接管扫描能看到最新心跳。 + db.session.commit() + return attempt + + +def recover_stale_gate_attempts(*, worker_id: str) -> list[int]: + """ + 回收心跳超时的 running Attempt:释放租约并重新入队。 + + 核心逻辑:heartbeat_at 超过接管阈值则标记可接管,写入审计并 enqueue 新 Job。 + + Returns: + 被接管的 attempt_id 列表。 + """ + cutoff = _utc_now() - timedelta(seconds=_takeover_seconds()) + query = ( + ShippingProcessGateAttempt.query + .filter( + ShippingProcessGateAttempt.status == 'running', + ShippingProcessGateAttempt.heartbeat_at.isnot(None), + ShippingProcessGateAttempt.heartbeat_at < cutoff, + ) + .limit(20) + ) + # 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: + 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() + record_fulfillment_audit( + event_type='process_gate_lease_taken_over', + aggregate_type='process_gate_attempt', + aggregate_id=str(attempt.id), + 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}, + source='process_gate', + ) + db.session.flush() + enqueue_gate_attempt_job(attempt_id=int(attempt.id)) + taken.append(int(attempt.id)) + return taken + + +def claim_and_run_gate_attempt( + *, + attempt_id: int, + worker_id: str, +) -> dict[str, Any]: + """ + Worker 领取 Attempt 租约并执行 execute_queued_attempt。 + + 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: + raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND') + if attempt.status not in {'queued', 'running'}: + return { + 'attempt_id': int(attempt.id), + 'status': attempt.status, + 'skipped': True, + } + + lease_token = uuid.uuid4().hex + now = _utc_now() + lease_expires = now + timedelta(seconds=_lease_seconds()) + mark_attempt_running( + 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() + db.session.refresh(attempt) + + # [STEP] 长任务周期心跳:独立线程续租,避免超过接管阈值被双执行。 + app = current_app._get_current_object() + stop_heartbeat = threading.Event() + hb_attempt_id = int(attempt.id) + hb_worker = str(worker_id)[:64] + hb_token = lease_token + hb_interval = _heartbeat_seconds() + + def _heartbeat_loop() -> None: + while not stop_heartbeat.wait(hb_interval): + try: + with app.app_context(): + heartbeat_gate_attempt( + attempt_id=hb_attempt_id, + worker_id=hb_worker, + lease_token=hb_token, + ) + except Exception: + _LOGGER.exception( + 'process_gate heartbeat failed attempt_id=%s worker=%s', + hb_attempt_id, + hb_worker, + ) + + hb_thread = threading.Thread( + target=_heartbeat_loop, + name=f'gate-hb-{hb_attempt_id}', + daemon=True, + ) + hb_thread.start() + try: + gate = execute_queued_attempt( + attempt=attempt, + worker_id=worker_id, + lease_token=lease_token, + lease_expires_at=lease_expires, + ) + return { + 'attempt_id': int(attempt_id), + 'gate_code': gate.gate_code, + 'gate_status': gate.status, + 'skipped': False, + 'heartbeat_interval_seconds': hb_interval, + } + finally: + stop_heartbeat.set() + hb_thread.join(timeout=max(hb_interval, 2)) diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py new file mode 100644 index 00000000..70063e63 --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -0,0 +1,404 @@ +""" +services/shipping_notice/process_gate_projection.py + +用途:将 Execution / Gate / Attempt 投影为前后端共享的只读恢复视图。 +依赖:ShippingProcessExecution/Gate/Attempt、process_gate_contract。 +逻辑:Chat、复核台与任务中心读取用户安全投影;管理员诊断中心读取完整投影; + 用户端同一时间最多一个阻断 + 一个主要恢复动作;诊断 Finding 不进入用户阻断。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ( + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, +) +from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_RECOVERABLE_STATUSES, + get_process_gate_definition, + primary_next_action_for_gate, +) +from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text + +# 前端仅导航、不 POST 的人工入口动作(与 process_gate_executor._SYNC_ACTIONS 子集对齐)。 +_PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS: frozenset[str] = frozenset({ + 'open_order_review', + 'open_inventory_source_review', + 'open_profile_review', + 'edit_order_fields', + 'edit_reservation', + 'confirm_customer', + 'adjudicate_duplicate', + 'resolve_field_conflicts', + 'open_inventory_match_review', + 'open_shortage_review', + 'confirm_inventory_field_mapping', +}) + +_PROCESS_GATE_TASK_NAVIGATION_ACTIONS: frozenset[str] = frozenset({ + 'upload_inventory_file', +}) + +_ACTION_NAVIGATION_FOCUS: dict[str, str] = { + 'open_profile_review': 'draft', + 'open_order_review': 'draft', + 'edit_order_fields': 'draft', + 'edit_reservation': 'draft', + 'confirm_customer': 'draft', + 'adjudicate_duplicate': 'draft', + 'resolve_field_conflicts': 'evidence', + 'open_inventory_source_review': 'draft', + 'open_inventory_match_review': 'draft', + 'open_shortage_review': 'draft', + 'confirm_inventory_field_mapping': 'draft', + 'upload_inventory_file': 'manual_upload', +} + + +def serialize_gate_attempt( + attempt: ShippingProcessGateAttempt | None, + *, + include_snapshots: bool = False, +) -> dict[str, Any] | None: + """ + 序列化 Attempt 摘要。 + + Args: + attempt: Attempt 行。 + include_snapshots: True 时附带输入/输出快照 JSON(管理员诊断用)。 + """ + if attempt is None: + return None + payload = { + 'id': int(attempt.id), + 'attempt_no': int(attempt.attempt_no), + 'status': attempt.status, + 'trigger_type': attempt.trigger_type, + 'actor_type': attempt.actor_type, + 'actor_id': attempt.actor_id, + 'idempotency_key': attempt.idempotency_key, + 'job_id': int(attempt.job_id) if attempt.job_id else None, + 'worker_id': attempt.worker_id, + 'lease_expires_at': attempt.lease_expires_at.isoformat() if attempt.lease_expires_at else None, + 'heartbeat_at': attempt.heartbeat_at.isoformat() if attempt.heartbeat_at else None, + 'started_at': attempt.started_at.isoformat() if attempt.started_at else None, + 'finished_at': attempt.finished_at.isoformat() if attempt.finished_at else None, + 'error_code': attempt.error_code, + # 读路径再脱敏一次,兼容历史未清洗数据。 + 'error_summary': sanitize_gate_error_text(attempt.error_summary, max_len=2000), + 'input_snapshot_hash': attempt.input_snapshot_hash, + 'rule_snapshot_hash': attempt.rule_snapshot_hash, + 'output_snapshot_hash': attempt.output_snapshot_hash, + } + if include_snapshots: + payload['input_snapshot'] = attempt.input_snapshot_json + payload['rule_snapshot'] = attempt.rule_snapshot_json + payload['output_snapshot'] = attempt.output_snapshot_json + return payload + + +def _findings_from_gate(gate: ShippingProcessGate) -> list[dict[str, Any]]: + """从 Gate.effective_result_json 提取 Finding 列表。""" + payload = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {} + raw = payload.get('findings') if isinstance(payload.get('findings'), list) else [] + return [dict(item) for item in raw if isinstance(item, dict)] + + +def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bool = True) -> dict[str, Any]: + """ + 序列化单门禁投影。 + + Args: + gate: 门禁行。 + include_diagnostics: False 时仅保留用户可见 blocking Finding。 + """ + definition = get_process_gate_definition(gate.gate_code) + latest = None + if gate.latest_attempt_id: + latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id)) + findings = _findings_from_gate(gate) + if not include_diagnostics: + findings = [ + item for item in findings + if item.get('severity') == 'blocking' and item.get('user_visible', True) + ] + return { + 'gate_code': gate.gate_code, + 'sequence_no': int(gate.sequence_no), + 'label': definition.get('label'), + 'status': gate.status, + 'evaluation_version': int(gate.evaluation_version), + 'input_fingerprint': gate.input_fingerprint, + 'blocking_reason_code': gate.blocking_reason_code, + 'blocking_reason': gate.blocking_reason_json if include_diagnostics else ( + {'reason_code': gate.blocking_reason_code} if gate.blocking_reason_code else None + ), + 'recommendation': gate.recommendation_json if include_diagnostics else None, + 'effective_result': gate.effective_result_json if include_diagnostics else None, + 'findings': findings, + 'next_action_code': gate.next_action_code, + 'responsible_party': definition.get('responsible_party'), + 'recoverable': bool(definition.get('recoverable')), + 'passed_at': gate.passed_at.isoformat() if gate.passed_at else None, + 'invalidated_at': gate.invalidated_at.isoformat() if gate.invalidated_at else None, + 'latest_attempt': serialize_gate_attempt(latest) if include_diagnostics else ( + {'attempt_no': latest.attempt_no, 'status': latest.status} if latest else None + ), + } + + +def serialize_process_execution( + execution: ShippingProcessExecution, + *, + include_diagnostics: bool = True, +) -> dict[str, Any]: + """ + 序列化 Execution 恢复投影。 + + Returns: + 含当前门禁、主动作与全部门禁轨道的字典。 + """ + gates = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id)) + .order_by(ShippingProcessGate.sequence_no.asc()) + .all() + ) + serialized = [ + serialize_process_gate(gate, include_diagnostics=include_diagnostics) + for gate in gates + ] + current = next( + (item for item in serialized if item.get('gate_code') == execution.current_gate_code), + None, + ) + return { + 'execution_no': execution.execution_no, + 'status': execution.status, + 'current_gate_code': execution.current_gate_code, + 'last_passed_gate_code': execution.last_passed_gate_code, + 'primary_next_action_code': execution.primary_next_action_code, + 'responsible_party': execution.responsible_party, + 'lock_version': int(execution.lock_version), + 'workflow_item_id': int(execution.workflow_item_id), + 'workflow_item_version_id': int(execution.workflow_item_version_id), + 'review_case_id': int(execution.review_case_id) if execution.review_case_id else None, + 'task_id': int(execution.task_id) if execution.task_id else None, + 'current_gate': current, + 'gates': serialized, + 'updated_at': execution.updated_at.isoformat() if execution.updated_at else None, + } + + +def _execution_navigation_refs(execution: ShippingProcessExecution) -> dict[str, Any]: + """ + 解析 Execution 关联的业务编号,供前端 router 深链。 + + Returns: + case_no / review_case_no / review_run_no / task_no。 + """ + case_no = None + review_run_no = None + task_no = None + if execution.review_case_id: + from app.models import ShippingOrderReviewCase + + case = ShippingOrderReviewCase.query.get(int(execution.review_case_id)) + if case is not None: + case_no = str(case.case_no) + run = getattr(case, 'run', None) + if run is not None and getattr(run, 'run_no', None): + review_run_no = str(run.run_no) + if execution.task_id: + from app.models import ShippingTask + + task = ShippingTask.query.get(int(execution.task_id)) + if task is not None: + task_no = str(task.task_no) + return { + 'case_no': case_no, + 'review_case_no': case_no, + 'review_run_no': review_run_no, + 'task_no': task_no, + } + + +def _navigation_for_action(action_code: str | None, refs: dict[str, Any]) -> dict[str, Any] | None: + """按主动作码生成前端导航提示;缺关键编号时返回 None。""" + code = str(action_code or '').strip() + if not code: + return None + if code in _PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS: + run_no = refs.get('review_run_no') + case_no = refs.get('case_no') + if not run_no and not case_no: + return None + return { + 'target': 'order_review', + 'focus': _ACTION_NAVIGATION_FOCUS.get(code, 'draft'), + 'run_no': run_no, + 'case_no': case_no, + } + if code in _PROCESS_GATE_TASK_NAVIGATION_ACTIONS: + task_no = refs.get('task_no') + if not task_no: + return None + return { + 'target': 'task_workspace', + 'focus': _ACTION_NAVIGATION_FOCUS.get(code), + 'task_no': task_no, + } + return None + + +def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]: + """ + 用户端安全投影:唯一当前阻断 + 主要恢复动作;不含管理员诊断 JSON。 + + Returns: + current_blocking_gate、reason、next_action、diagnostic_hint(可选非阻断提示)。 + """ + full = serialize_process_execution(execution, include_diagnostics=False) + current = full.get('current_gate') + blocking = None + if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | { + 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', + }: + blocking = current + diagnostic_hint = None + for gate in full.get('gates') or []: + for finding in gate.get('findings') or []: + if finding.get('severity') == 'diagnostic': + diagnostic_hint = '其他可选字段存在证据不足,不影响当前处理' + break + if diagnostic_hint: + break + reason_code = (blocking or {}).get('blocking_reason_code') + next_action = full.get('primary_next_action_code') or ( + primary_next_action_for_gate( + gate_code=str((blocking or {}).get('gate_code') or ''), + status=str((blocking or {}).get('status') or ''), + ) if blocking else None + ) + refs = _execution_navigation_refs(execution) + navigation = _navigation_for_action(next_action, refs) + return { + 'execution_no': full.get('execution_no'), + 'status': full.get('status'), + 'current_blocking_gate': blocking, + 'blocking_reason_code': reason_code, + 'blocking_message': _user_facing_blocking_message(reason_code), + 'next_action_code': next_action, + 'responsible_party': full.get('responsible_party'), + 'diagnostic_hint': diagnostic_hint, + 'case_no': refs.get('case_no'), + 'review_case_no': refs.get('review_case_no'), + 'review_run_no': refs.get('review_run_no'), + 'task_no': refs.get('task_no'), + 'navigation': navigation, + 'gates_track': [ + { + 'gate_code': item.get('gate_code'), + 'label': item.get('label'), + 'status': item.get('status'), + 'sequence_no': item.get('sequence_no'), + } + for item in (full.get('gates') or []) + ], + } + + +def _user_facing_blocking_message(reason_code: str | None) -> str | None: + """ + 将内部原因码映射为用户可读业务文案;未知码不回落展示原码。 + + Args: + reason_code: Gate.blocking_reason_code。 + + Returns: + 可读文案;无法映射时 None(前端展示门禁标签 + 通用提示)。 + """ + code = str(reason_code or '').strip() + if not code: + return None + messages = { + 'auto_freeze_not_enabled': '自动建单策略尚未放行,需人工确认', + 'profile_not_auto_freeze_approved': '自动建单策略尚未放行,需人工确认', + 'profile_manual_confirmation_required': '自动建单策略尚未放行,需人工确认', + 'freeze_not_ready': '订单尚未满足冻结建单条件,请先完成复核确认', + 'document_unavailable': '发货通知文档不可用,请重新上传或物化文档', + 'layout_parse_failed': 'PDF 版面解析失败,请重试解析', + 'profile_not_matched': '未能匹配文档模板,请人工确认 Profile', + 'profile_ambiguous': '文档模板存在歧义,请人工确认 Profile', + 'extraction_incomplete': '订单字段抽取未完成,请重试或进入复核', + 'required_field_missing': '存在必填字段缺失,请补充订单信息', + 'reservation_invalid': 'Reservation 校验未通过,请修正后重试', + 'customer_unresolved': '客户身份未识别,请确认客户', + 'customer_ambiguous': '客户身份存在歧义,请确认客户', + 'duplicate_unresolved': '疑似重复订单,请裁定后继续', + 'field_conflict': '订单字段存在冲突,请解决冲突后继续', + 'cross_source_conflict': '跨来源字段冲突,请解决冲突后继续', + 'no_inventory_source_candidates': '暂无可用库存源候选,请重算或人工指定', + 'require_manual_review': '库存源需人工确认', + 'inventory_source_unavailable': '库存源不可用,请更换或重试', + 'task_creation_failed': '履约任务创建失败,请重试或联系管理员', + 'inventory_preparation_failed': '库存准备失败,请重试或上传库存文件', + 'inventory_preparation_waiting': '库存准备进行中,请稍后刷新', + 'inventory_mapping_required': '库存字段映射待确认', + 'inventory_match_failed': '库存匹配失败,请复核匹配结果', + 'inventory_insufficient': '库存不足,请处理缺料后继续', + 'excel_not_ready': '暂不满足 Excel 生成条件', + 'artifact_generation_failed': 'Excel 生成失败,请重试', + 'manual_upload_pending': '请下载 Excel 并在货代平台上传后登记凭据', + 'gate_invalidated': '上游结果已变化,当前门禁需重新评估', + 'review_required': '需要人工复核后才能继续', + } + return messages.get(code) + + +def project_admin_gate_diagnostics(execution: ShippingProcessExecution) -> dict[str, Any]: + """管理员诊断投影:全部 Gate、Finding、Attempt 摘要与有效结果。""" + return serialize_process_execution(execution, include_diagnostics=True) + + +def project_workbench_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]: + """ + 业务工作台投影:用户阻断摘要 + 当前 Gate 下的业务可见 findings。 + + 核心逻辑:不暴露 Attempt 快照哈希与完整 effective_result 内部结构。 + """ + user = project_user_gate_summary(execution) + current = user.get('current_blocking_gate') or {} + return { + **user, + 'current_findings': list(current.get('findings') or []), + } + + +def find_execution_projection_for_case(case_id: int) -> dict[str, Any] | None: + """按 Review Case 查找 Execution 投影;无则 None。""" + execution = ( + ShippingProcessExecution.query + .filter_by(review_case_id=int(case_id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + return None + return serialize_process_execution(execution) + + +def find_execution_projection_for_task(task_id: int) -> dict[str, Any] | None: + """按 ShippingTask 查找 Execution 投影;无则 None。""" + execution = ( + ShippingProcessExecution.query + .filter_by(task_id=int(task_id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + return None + return serialize_process_execution(execution) diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py new file mode 100644 index 00000000..e7afe356 --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -0,0 +1,178 @@ +""" +services/shipping_notice/process_gate_recovery_service.py + +用途:处理客户端门禁恢复动作请求(幂等、版本校验、权限边界由 API 层配合)。 +依赖:process_gate_service、process_gate_executor、process_gate_contract、 + ShippingProcessExecution。 +逻辑:只接受契约内 action_code;排队 Attempt 后同步动作立即执行,异步动作入队 Job; + 库存源路由的 retry_with_latest_rules / adopt / keep 委托 Draft 服务。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import NotFoundError, ValidationError +from app.models import ShippingProcessExecution, ShippingProcessGate +from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_ACTION_CODES, + get_process_gate_definition, + primary_next_action_for_gate, +) +from app.services.shipping_notice.process_gate_executor import ( + action_requires_async_worker, + execute_queued_attempt, +) +from app.services.shipping_notice.process_gate_service import queue_gate_attempt + + +def get_execution_by_no(execution_no: str) -> ShippingProcessExecution: + """按编号读取 Execution;不存在抛 NotFound。""" + row = ShippingProcessExecution.query.filter_by( + execution_no=str(execution_no or '').strip().upper(), + ).first() + if row is None: + raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND') + return row + + +def request_gate_action( + *, + execution_no: str, + gate_code: str, + action_code: str, + expected_gate_version: int, + idempotency_key: str, + actor_type: str, + actor_id: int | str | None, + payload: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + 请求执行服务端下发的门禁恢复动作。 + + 核心逻辑:校验 action 属于契约且与当前门禁主要动作一致(或为同门禁允许的附属动作); + 创建 queued Attempt 后,同步动作立即 execute_queued_attempt,异步动作入队 Gate Job。 + 客户端禁止提交起始阶段/目标状态/Worker 名。 + + Args: + execution_no / gate_code: 定位目标。 + action_code: 契约内动作。 + expected_gate_version: 乐观锁。 + idempotency_key: 幂等键。 + actor_type / actor_id: 操作主体。 + payload: 可选附加参数(如 reason),不得含目标状态。 + + Returns: + 含 attempt / gate 摘要的字典。 + """ + action = str(action_code or '').strip() + if action not in PROCESS_GATE_ACTION_CODES: + raise ValidationError('Unknown process gate action', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') + forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql'} + body = dict(payload) if isinstance(payload, dict) else {} + if forbidden.intersection(set(body.keys())): + raise ValidationError('Client must not submit execution controls', code='SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN') + + # 同步适配器需要操作人;从 actor 注入,禁止客户端伪造目标状态。 + if actor_id is not None and 'actor_user_id' not in body: + try: + body['actor_user_id'] = int(actor_id) + except (TypeError, ValueError): + pass + body.setdefault('idempotency_key', str(idempotency_key or '')) + + execution = get_execution_by_no(execution_no) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code=str(gate_code or '').strip(), + ).first() + if gate is None: + raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + + primary = gate.next_action_code or primary_next_action_for_gate( + gate_code=gate.gate_code, status=gate.status, + ) + # [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。 + allowed_side: set[str] = set() + if gate.gate_code == 'inventory_source_routing': + allowed_side = { + 'adopt_rule_suggestion', + 'keep_manual_inventory_decision', + } + if primary and action != primary and action not in allowed_side: + raise ValidationError( + 'Action is not the primary recovery action for this gate', + code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', + details={'expected': primary, 'got': action, 'gate_code': gate.gate_code}, + ) + + definition = get_process_gate_definition(gate.gate_code) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code=gate.gate_code, + trigger_type='user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=idempotency_key, + expected_gate_version=expected_gate_version, + input_snapshot={'action_code': action, 'payload': body}, + ) + + # 幂等回放且已终态:直接返回,不二次执行。 + if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}: + db_gate = ShippingProcessGate.query.get(int(attempt.gate_id)) + return { + 'execution_no': execution.execution_no, + 'gate_code': gate.gate_code, + 'action_code': action, + 'responsible_party': definition.get('responsible_party'), + 'dispatch': 'idempotent_replay', + 'attempt': { + 'id': int(attempt.id), + 'attempt_no': int(attempt.attempt_no), + 'status': attempt.status, + 'idempotency_key': attempt.idempotency_key, + }, + 'gate_status': db_gate.status if db_gate else gate.status, + 'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version), + } + + if action_requires_async_worker(action): + from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job + + job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=( + int(actor_id) if actor_type == 'user' and actor_id is not None else None + )) + return { + 'execution_no': execution.execution_no, + 'gate_code': gate.gate_code, + 'action_code': action, + 'responsible_party': definition.get('responsible_party'), + 'dispatch': 'async_job', + 'job_id': job_id, + 'attempt': { + 'id': int(attempt.id), + 'attempt_no': int(attempt.attempt_no), + 'status': attempt.status, + 'idempotency_key': attempt.idempotency_key, + }, + 'gate_evaluation_version': int(gate.evaluation_version), + } + + updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery') + return { + 'execution_no': execution.execution_no, + 'gate_code': updated_gate.gate_code, + 'action_code': action, + 'responsible_party': definition.get('responsible_party'), + 'dispatch': 'sync', + 'attempt': { + 'id': int(attempt.id), + 'attempt_no': int(attempt.attempt_no), + 'status': attempt.status, + 'idempotency_key': attempt.idempotency_key, + }, + 'gate_status': updated_gate.status, + 'gate_evaluation_version': int(updated_gate.evaluation_version), + 'next_action_code': updated_gate.next_action_code, + } diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py new file mode 100644 index 00000000..8863b3d9 --- /dev/null +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -0,0 +1,765 @@ +""" +services/shipping_notice/process_gate_service.py + +用途:门禁推进、结果提交与下游失效的唯一写入入口。 +依赖:ShippingProcessExecution/Gate/Attempt、process_gate_contract、process_gate_dependency、 + fulfillment_audit、workflow_ledger_service。 +逻辑:创建 Execution 与全部门禁行;queue_gate_attempt 按幂等键复用前校验 + Execution/Gate/action/输入指纹;状态变更与 Attempt 结果、Execution 指针、 + 下游失效、审计在同一事务提交;禁止业务路径绕过本服务改 Gate 状态。 +""" + +from __future__ import annotations + +import hashlib +import json +import uuid +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, +) +from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit +from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_DEFINITIONS, + PROCESS_GATE_RECOVERABLE_STATUSES, + get_process_gate_definition, + primary_next_action_for_gate, +) +from app.services.shipping_notice.process_gate_dependency import compute_invalidated_gates +from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text + + +def _utc_now() -> datetime: + """naive UTC,与模型默认一致。""" + return datetime.utcnow() + + +def _stable_hash(value: Any) -> str: + """对受控快照生成 SHA-256。""" + encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(encoded.encode('ascii')).hexdigest() + + +def _new_execution_no() -> str: + """生成业务可读 Execution 编号。""" + return f"SPE-{_utc_now().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def _locked_execution(execution_no: str) -> ShippingProcessExecution: + """按 execution_no 行锁加载 Execution。""" + row = ( + ShippingProcessExecution.query + .filter_by(execution_no=str(execution_no or '').strip().upper()) + .with_for_update() + .first() + ) + if row is None: + raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND') + return row + + +def _locked_gate(*, execution: ShippingProcessExecution, gate_code: str) -> ShippingProcessGate: + """按 gate_code 行锁加载门禁。""" + code = str(gate_code or '').strip() + gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code=code) + .with_for_update() + .first() + ) + if gate is None: + raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + return gate + + +def _assert_idempotent_replay_matches( + *, + replay: ShippingProcessGateAttempt, + execution_no: str, + gate_code: str, + action_code: str | None, + input_snapshot: dict[str, Any] | None, +) -> None: + """ + 校验幂等键命中的 Attempt 与当前请求属于同一 Execution/Gate/Action。 + + 核心逻辑:同键仅允许「相同请求」复用;跨 Execution、跨 Gate、跨 action_code + 或输入指纹不一致时抛 ConflictError,禁止误复用其他上下文的 Attempt。 + + Args: + replay: 已存在的 Attempt。 + execution_no: 本次请求的 Execution 编号。 + gate_code: 本次请求的门禁编码。 + action_code: 本次请求的动作码(可空,表示未声明)。 + input_snapshot: 本次请求输入快照;双方均有 hash 时额外比对。 + + Raises: + ConflictError: 上下文不一致。 + NotFoundError: Attempt 关联的 Gate/Execution 丢失。 + """ + gate = db.session.get(ShippingProcessGate, int(replay.gate_id)) + if gate is None: + raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) + if execution is None: + raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND') + + expected_execution = str(execution_no or '').strip().upper() + actual_execution = str(execution.execution_no or '').strip().upper() + expected_gate = str(gate_code or '').strip() + actual_gate = str(gate.gate_code or '').strip() + stored_snapshot = replay.input_snapshot_json if isinstance(replay.input_snapshot_json, dict) else {} + stored_action = str(stored_snapshot.get('action_code') or '').strip() or None + requested_action = str(action_code or '').strip() or None + + mismatches: list[str] = [] + if expected_execution and actual_execution != expected_execution: + mismatches.append('execution_no') + if expected_gate and actual_gate != expected_gate: + mismatches.append('gate_code') + if requested_action != stored_action: + # 任一方声明了 action 且不一致即冲突;双方皆空则视为未声明动作,允许复用。 + if requested_action is not None or stored_action is not None: + mismatches.append('action_code') + if input_snapshot is not None and replay.input_snapshot_hash: + if _stable_hash(input_snapshot) != str(replay.input_snapshot_hash): + mismatches.append('input_fingerprint') + + if mismatches: + raise ConflictError( + 'Idempotency key conflicts with a different gate request', + code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT', + details={'mismatched_fields': mismatches, 'idempotency_key': replay.idempotency_key}, + ) + + +def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None: + """ + 根据 Gate 列表重算 Execution 当前门禁与主恢复动作。 + + 核心逻辑:取第一个非 passed/skipped 门禁为 current;全部通过则 completed。 + """ + gates = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id)) + .order_by(ShippingProcessGate.sequence_no.asc()) + .all() + ) + last_passed = None + current = None + for gate in gates: + if gate.status == 'passed': + last_passed = gate.gate_code + continue + if gate.status == 'skipped': + continue + current = gate + break + execution.last_passed_gate_code = last_passed + if current is None: + execution.current_gate_code = None + execution.primary_next_action_code = None + execution.responsible_party = None + if execution.status not in {'cancelled', 'failed'}: + execution.status = 'completed' + return + execution.current_gate_code = current.gate_code + execution.primary_next_action_code = current.next_action_code + definition = get_process_gate_definition(current.gate_code) + execution.responsible_party = str(definition.get('responsible_party') or '') or None + if current.status == 'waiting_external': + execution.status = 'waiting_external' + elif current.status in {'blocked_retryable', 'blocked_manual', 'invalidated', 'failed_terminal'}: + execution.status = 'blocked' + elif execution.status in {'completed', 'cancelled', 'failed'}: + execution.status = 'active' + else: + execution.status = 'active' + + +def ensure_execution_for_workflow_version( + *, + workflow_item_id: int, + workflow_item_version_id: int, + review_case_id: int | None = None, + task_id: int | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, + start_gate_code: str = 'document_materialization', +) -> ShippingProcessExecution: + """ + 为 WorkflowItemVersion 幂等创建 Execution 与全部门禁行。 + + 核心逻辑:同一 version 仅一个 Execution;已存在则绑定 review_case/task 指针后返回。 + + Args: + workflow_item_id / workflow_item_version_id: 台账外键。 + review_case_id / task_id: 建单前/后可选绑定。 + actor_type / actor_id: 创建审计主体。 + start_gate_code: 首个待执行门禁;之前门禁标记 skipped。 + + Returns: + ShippingProcessExecution。 + """ + existing = ( + ShippingProcessExecution.query + .filter_by(workflow_item_version_id=int(workflow_item_version_id)) + .with_for_update() + .first() + ) + if existing is not None: + if review_case_id and existing.review_case_id is None: + existing.review_case_id = int(review_case_id) + if task_id and existing.task_id is None: + existing.task_id = int(task_id) + existing.updated_at = _utc_now() + db.session.flush() + return existing + + now = _utc_now() + execution = ShippingProcessExecution( + execution_no=_new_execution_no(), + workflow_item_id=int(workflow_item_id), + workflow_item_version_id=int(workflow_item_version_id), + review_case_id=int(review_case_id) if review_case_id else None, + task_id=int(task_id) if task_id else None, + status='active', + lock_version=1, + created_at=now, + updated_at=now, + ) + db.session.add(execution) + db.session.flush() + + start_seq = get_process_gate_definition(start_gate_code)['sequence_no'] + for item in PROCESS_GATE_DEFINITIONS: + seq = int(item['sequence_no']) + code = str(item['gate_code']) + if seq < start_seq: + status = 'skipped' + next_action = None + elif seq == start_seq: + status = 'pending' + next_action = None + else: + status = 'pending' + next_action = None + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code=code, + sequence_no=seq, + status=status, + evaluation_version=1, + next_action_code=next_action, + lock_version=1, + created_at=now, + updated_at=now, + )) + db.session.flush() + _refresh_execution_pointers(execution) + record_fulfillment_audit( + event_type='process_execution_created', + aggregate_type='process_execution', + aggregate_id=str(execution.execution_no), + action='create_execution', + actor_type=actor_type if actor_type in {'user', 'system', 'rpa', 'chatflow', 'admin'} else 'system', + actor_id=actor_id, + workflow_item_id=None, + before=None, + after={ + 'execution_no': execution.execution_no, + 'status': execution.status, + 'gate_code': execution.current_gate_code, + 'lifecycle_status': execution.status, + }, + metadata={'workflow_item_id': int(workflow_item_id), 'workflow_item_version_id': int(workflow_item_version_id)}, + source='process_gate', + ) + db.session.flush() + return execution + + +def bind_execution_task( + *, + execution_no: str, + task_id: int, + actor_type: str = 'system', + actor_id: str | int | None = None, +) -> ShippingProcessExecution: + """建单后绑定 ShippingTask;幂等覆盖空 task_id。""" + execution = _locked_execution(execution_no) + if execution.task_id and int(execution.task_id) != int(task_id): + raise ConflictError('Execution already bound to another task', code='SHIPPING.PROCESS_EXECUTION_TASK_BOUND') + execution.task_id = int(task_id) + execution.updated_at = _utc_now() + execution.lock_version = int(execution.lock_version) + 1 + db.session.flush() + return execution + + +def queue_gate_attempt( + *, + execution_no: str, + gate_code: str, + trigger_type: str, + actor_type: str, + actor_id: str | int | None, + idempotency_key: str, + expected_gate_version: int | None = None, + input_snapshot: dict[str, Any] | None = None, + rule_snapshot: dict[str, Any] | None = None, +) -> ShippingProcessGateAttempt: + """ + 为指定门禁创建 queued Attempt;同幂等键重放首次结果。 + + Raises: + ConflictError: 版本冲突或已有活动 Attempt。 + ValidationError: 门禁不可恢复。 + """ + key = str(idempotency_key or '').strip() + if not key: + raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED') + requested_action = None + if isinstance(input_snapshot, dict): + requested_action = str(input_snapshot.get('action_code') or '').strip() or None + + replay = ShippingProcessGateAttempt.query.filter_by(idempotency_key=key).first() + if replay is not None: + # [STEP] 幂等复用前校验 Execution / Gate / action 一致,防止跨上下文误复用。 + _assert_idempotent_replay_matches( + replay=replay, + execution_no=str(execution_no or '').strip(), + gate_code=str(gate_code or '').strip(), + action_code=requested_action, + input_snapshot=input_snapshot, + ) + record_fulfillment_audit( + event_type='process_gate_idempotent_replay', + aggregate_type='process_gate_attempt', + aggregate_id=str(replay.id), + action='idempotent_replay', + actor_type=actor_type if actor_type in {'user', 'system', 'admin', 'worker'} else 'system', + actor_id=actor_id, + result='ignored', + before={'status': replay.status, 'gate_code': gate_code, 'idempotency_key': key}, + after={'status': replay.status, 'gate_code': gate_code, 'idempotency_key': key, 'attempt_no': replay.attempt_no}, + metadata={'execution_no': execution_no}, + source='process_gate', + ) + return replay + + execution = _locked_execution(execution_no) + gate = _locked_gate(execution=execution, gate_code=gate_code) + if expected_gate_version is not None and int(gate.evaluation_version) != int(expected_gate_version): + raise ConflictError('Process gate version mismatch', code='SHIPPING.PROCESS_GATE_VERSION_MISMATCH') + if gate.status not in PROCESS_GATE_RECOVERABLE_STATUSES | {'pending', 'queued'}: + if gate.status in {'running'}: + raise ConflictError('Process gate already running', code='SHIPPING.PROCESS_GATE_BUSY') + if gate.status == 'passed': + raise ValidationError('Process gate already passed', code='SHIPPING.PROCESS_GATE_ALREADY_PASSED') + + active = ( + ShippingProcessGateAttempt.query + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ) + .first() + ) + if active is not None: + raise ConflictError('Process gate already has an active attempt', code='SHIPPING.PROCESS_GATE_BUSY') + + last = ( + ShippingProcessGateAttempt.query + .filter_by(gate_id=int(gate.id)) + .order_by(ShippingProcessGateAttempt.attempt_no.desc()) + .first() + ) + attempt_no = int(last.attempt_no) + 1 if last else 1 + now = _utc_now() + attempt = ShippingProcessGateAttempt( + gate_id=int(gate.id), + attempt_no=attempt_no, + status='queued', + trigger_type=str(trigger_type or 'auto'), + actor_type=str(actor_type or 'system'), + actor_id=str(actor_id) if actor_id is not None else None, + idempotency_key=key, + input_snapshot_json=dict(input_snapshot or {}) or None, + input_snapshot_hash=_stable_hash(input_snapshot or {}) if input_snapshot is not None else None, + rule_snapshot_json=dict(rule_snapshot or {}) or None, + rule_snapshot_hash=_stable_hash(rule_snapshot or {}) if rule_snapshot is not None else None, + created_at=now, + ) + db.session.add(attempt) + db.session.flush() + + before_status = gate.status + gate.status = 'queued' + gate.next_action_code = primary_next_action_for_gate(gate_code=gate.gate_code, status='queued') + gate.latest_attempt_id = int(attempt.id) + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.lock_version = int(gate.lock_version) + 1 + gate.updated_at = now + execution.lock_version = int(execution.lock_version) + 1 + execution.updated_at = now + _refresh_execution_pointers(execution) + + record_fulfillment_audit( + event_type='process_gate_recovery_requested', + aggregate_type='process_gate', + aggregate_id=f'{execution.execution_no}:{gate.gate_code}', + action=str(trigger_type or 'recovery'), + actor_type=actor_type if actor_type in {'user', 'system', 'admin', 'worker'} else 'system', + actor_id=actor_id, + before={'status': before_status, 'gate_code': gate.gate_code, 'draft_version': None}, + after={ + 'status': gate.status, + 'gate_code': gate.gate_code, + 'attempt_no': attempt_no, + 'idempotency_key': key, + 'execution_no': execution.execution_no, + 'next_action_code': gate.next_action_code, + }, + metadata={'trigger_type': trigger_type}, + source='process_gate', + ) + db.session.flush() + return attempt + + +def mark_attempt_running( + *, + attempt_id: int, + worker_id: str | None = None, + 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') + if attempt.status not in {'queued', 'running'}: + raise ConflictError('Attempt is not runnable', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE') + now = _utc_now() + attempt.status = 'running' + attempt.worker_id = str(worker_id)[:64] if worker_id else attempt.worker_id + attempt.lease_token = str(lease_token)[:64] if lease_token else attempt.lease_token + 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( + event_type='process_gate_attempt_started', + aggregate_type='process_gate_attempt', + aggregate_id=str(attempt.id), + action='start_attempt', + actor_type='worker' if worker_id else 'system', + actor_id=worker_id, + before={'status': 'queued', 'gate_code': gate.gate_code}, + after={'status': 'running', 'gate_code': gate.gate_code, 'attempt_no': attempt.attempt_no}, + source='process_gate', + ) + db.session.flush() + return attempt + + +def complete_gate_attempt( + *, + attempt_id: int, + outcome: str, + output_snapshot: dict[str, Any] | None = None, + blocking_reason_code: str | None = None, + blocking_reason_json: dict[str, Any] | None = None, + recommendation_json: dict[str, Any] | None = None, + effective_result_json: dict[str, Any] | None = None, + error_code: str | None = None, + error_summary: str | None = None, + invalidate_change_type: str | None = None, +) -> ShippingProcessGate: + """ + 提交 Attempt 终态并更新 Gate / Execution;可选触发下游失效。 + + Args: + outcome: passed / blocked_retryable / blocked_manual / waiting_external / failed_terminal。 + invalidate_change_type: 若通过且需失效下游,传入依赖图变化类型。 + """ + allowed = { + 'passed', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', + } + 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') + 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') + + now = _utc_now() + before = { + 'status': gate.status, + 'gate_code': gate.gate_code, + 'blocking_reason_code': gate.blocking_reason_code, + } + attempt.output_snapshot_json = dict(output_snapshot or {}) or None + attempt.output_snapshot_hash = _stable_hash(output_snapshot or {}) if output_snapshot is not None else None + attempt.finished_at = now + attempt.error_code = str(error_code)[:64] if error_code else None + # [STEP] 持久化前脱敏,避免 URL/路径/连接信息进入 Attempt 与后续投影。 + attempt.error_summary = sanitize_gate_error_text(error_summary, max_len=2000) + # waiting_external 表示 Attempt 本身成功完成并进入外部等待,不应记为 failed。 + attempt.status = 'succeeded' if outcome in {'passed', 'waiting_external'} else 'failed' + attempt.lease_token = None + attempt.lease_expires_at = None + + gate.status = outcome + gate.blocking_reason_code = str(blocking_reason_code)[:64] if blocking_reason_code else None + reason_payload = dict(blocking_reason_json or {}) or None + if isinstance(reason_payload, dict) and reason_payload.get('message') is not None: + reason_payload['message'] = sanitize_gate_error_text(reason_payload.get('message'), max_len=500) + gate.blocking_reason_json = reason_payload + gate.recommendation_json = dict(recommendation_json or {}) or None + result_payload = dict(effective_result_json or {}) + # [STEP] 首次进入外部等待时写入 waiting_since,供超时轮询判定。 + if outcome == 'waiting_external' and not result_payload.get('waiting_since'): + prev = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {} + result_payload['waiting_since'] = prev.get('waiting_since') or now.isoformat() + gate.effective_result_json = result_payload or None + gate.next_action_code = primary_next_action_for_gate(gate_code=gate.gate_code, status=outcome) + gate.latest_attempt_id = int(attempt.id) + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.lock_version = int(gate.lock_version) + 1 + gate.updated_at = now + if outcome == 'passed': + gate.passed_at = now + gate.invalidated_at = None + gate.blocking_reason_code = None + + invalidated: list[str] = [] + if outcome == 'passed' and invalidate_change_type: + invalidated = list(invalidate_downstream_gates( + execution=execution, + change_type=str(invalidate_change_type), + actor_type='system', + actor_id=None, + )) + + execution.lock_version = int(execution.lock_version) + 1 + execution.updated_at = now + _refresh_execution_pointers(execution) + + event_type = 'process_gate_passed' if outcome == 'passed' else 'process_gate_blocked' + record_fulfillment_audit( + event_type=event_type, + aggregate_type='process_gate', + aggregate_id=f'{execution.execution_no}:{gate.gate_code}', + action=outcome, + actor_type='system', + result='success' if outcome == 'passed' else 'failure', + error_code=attempt.error_code, + before=before, + after={ + 'status': gate.status, + 'gate_code': gate.gate_code, + 'attempt_no': attempt.attempt_no, + 'blocking_reason_code': gate.blocking_reason_code, + 'next_action_code': gate.next_action_code, + 'execution_no': execution.execution_no, + 'invalidated_downstream_gates': invalidated, + }, + metadata={'outcome': outcome}, + source='process_gate', + ) + db.session.flush() + return gate + + +def invalidate_downstream_gates( + *, + execution: ShippingProcessExecution, + change_type: str, + actor_type: str = 'system', + actor_id: str | int | None = None, +) -> list[str]: + """ + 将依赖图指定的下游已通过门禁标记为 invalidated。 + + Returns: + 实际失效的 gate_code 列表。 + """ + targets = set(compute_invalidated_gates(change_type)) + if not targets: + return [] + now = _utc_now() + invalidated: list[str] = [] + gates = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id)) + .order_by(ShippingProcessGate.sequence_no.asc()) + .all() + ) + for gate in gates: + if gate.gate_code not in targets: + continue + if gate.status not in {'passed', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external'}: + continue + before = gate.status + gate.status = 'invalidated' + gate.invalidated_at = now + gate.next_action_code = primary_next_action_for_gate( + gate_code=gate.gate_code, status='invalidated', + ) or 'retry_with_latest_rules' + # invalidated 默认动作:多数门禁走 blocked_retryable 语义;若契约无显式项则置 pending 重跑入口。 + if gate.next_action_code is None: + gate.next_action_code = primary_next_action_for_gate( + gate_code=gate.gate_code, status='blocked_retryable', + ) + gate.blocking_reason_code = 'gate_invalidated' + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.lock_version = int(gate.lock_version) + 1 + gate.updated_at = now + invalidated.append(gate.gate_code) + record_fulfillment_audit( + event_type='process_gate_downstream_invalidated', + aggregate_type='process_gate', + aggregate_id=f'{execution.execution_no}:{gate.gate_code}', + action='invalidate', + actor_type=actor_type if actor_type in {'user', 'system', 'admin'} else 'system', + actor_id=actor_id, + before={'status': before, 'gate_code': gate.gate_code}, + after={ + 'status': 'invalidated', + 'gate_code': gate.gate_code, + 'blocking_reason_code': 'gate_invalidated', + 'execution_no': execution.execution_no, + }, + metadata={'change_type': change_type}, + source='process_gate', + ) + db.session.flush() + return invalidated + + +def sync_gate_from_business_result( + *, + execution_no: str, + gate_code: str, + passed: bool, + effective_result_json: dict[str, Any] | None = None, + recommendation_json: dict[str, Any] | None = None, + blocking_reason_code: str | None = None, + blocking_reason_json: dict[str, Any] | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, + idempotency_key: str | None = None, + invalidate_change_type: str | None = None, + allow_repass: bool = True, + outcome: str | None = None, +) -> ShippingProcessGate: + """ + 业务路径(如复核库存重路由)将结果同步进 Gate:创建 Attempt 并 complete。 + + 核心逻辑:无活动 Attempt 时自动 queue+complete;用于业务接线接入统一服务。 + 已通过门禁在 allow_repass 时先置 invalidated 再重评(输入变化重跑)。 + + Args: + invalidate_change_type: 通过后失效类型;None 时库存源路由默认 inventory_source_changed。 + allow_repass: 允许对已通过门禁重新评估。 + outcome: 可选显式 Attempt 结果(如 waiting_external);缺省由 passed/reason 推导。 + """ + key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}' + execution = _locked_execution(execution_no) + gate = _locked_gate(execution=execution, gate_code=gate_code) + if allow_repass and gate.status == 'passed': + gate.status = 'invalidated' + gate.invalidated_at = _utc_now() + gate.blocking_reason_code = 'gate_invalidated' + gate.evaluation_version = int(gate.evaluation_version) + 1 + gate.lock_version = int(gate.lock_version) + 1 + gate.updated_at = _utc_now() + db.session.flush() + + attempt = queue_gate_attempt( + execution_no=execution_no, + gate_code=gate_code, + trigger_type='user_manual' if actor_type == 'user' else 'auto', + actor_type=actor_type, + actor_id=actor_id, + idempotency_key=key, + input_snapshot=effective_result_json, + rule_snapshot=recommendation_json, + ) + if attempt.status in {'succeeded', 'failed'}: + 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') + return gate + mark_attempt_running(attempt_id=int(attempt.id), worker_id='inline-sync') + allowed_outcomes = { + 'passed', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', + } + if outcome and str(outcome) in allowed_outcomes: + outcome = str(outcome) + else: + outcome = 'passed' if passed else ( + 'blocked_manual' if blocking_reason_code else 'blocked_retryable' + ) + resolved_invalidate = invalidate_change_type + if resolved_invalidate is None and passed and gate_code == 'inventory_source_routing': + resolved_invalidate = 'inventory_source_changed' + return complete_gate_attempt( + attempt_id=int(attempt.id), + outcome=outcome, + output_snapshot=effective_result_json, + blocking_reason_code=blocking_reason_code, + blocking_reason_json=blocking_reason_json, + recommendation_json=recommendation_json, + effective_result_json=effective_result_json, + invalidate_change_type=resolved_invalidate, + ) diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index 61af09e9..d1bd2c60 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -4,7 +4,8 @@ services/shipping_notice/progress_audit_contract.py 用途:冻结货代发货通知进度审计与 Workflow(批次/PDF 项)领域契约词典。 依赖:无外部 IO;被 progress / audit / workflow / projection / OpenAPI 与测试引用。 逻辑:状态、用户可见阶段、健康提示、取消语义、Workflow Item 生命周期、模板评分/ - 通用解析/LLM 建议/人工裁决事件码、审计事件字典与敏感键黑名单的唯一代码源; + 通用解析/LLM 建议/人工裁决事件码、全门禁(Process Gate)恢复审计事件码、 + 审计事件字典与敏感键黑名单的唯一代码源; UI 与 Worker 行为变更在后续阶段接线,本模块只冻结名称与规则。 SESSION_* 别名保留供过渡期测试引用。 """ @@ -102,6 +103,27 @@ WORKFLOW_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ # 过渡期别名。 SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = WORKFLOW_ITEM_AUDIT_EVENT_TYPES +# 全门禁中断恢复(ShippingProcessExecution / Gate / Attempt)审计事件字典。 +# 阶段 1 仅冻结事件码;写路径与投影在后续阶段接线,禁止前端或 Worker 私自发明事件名。 +PROCESS_GATE_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ + 'process_execution_created', + 'process_gate_created', + 'process_gate_attempt_started', + 'process_gate_passed', + 'process_gate_blocked', + 'process_gate_recovery_requested', + 'process_gate_idempotent_replay', + 'process_gate_manual_override', + 'process_gate_rule_suggestion_generated', + 'process_gate_suggestion_adopted', + 'process_gate_suggestion_rejected', + 'process_gate_downstream_invalidated', + 'process_gate_technical_retry', + 'process_gate_lease_taken_over', + 'process_gate_artifact_superseded', + 'process_gate_permission_denied', +}) + # 字段派生 / 人工覆盖 / 规则模拟 / Excel 导出等项次相关审计事件词典(语义分组)。 # 自 2026-07-30 起:货代统一审计账本全部事件永久保留;本集合仅作事件分类引用。 LINE_DERIVATION_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ @@ -343,6 +365,25 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'export_artifact_no', 'template_version', 'field_code', + 'candidate_inventory_source_codes', + 'raw_rule_source_codes', + 'rule_suggestion_source_codes', + 'unavailable_source_codes', + 'rule_versions', + 'selection_mode', + 'suggestion_pending', + 'idempotency_key', + 'action_semantics', + 'line_keys', + 'routing_status', + # Process Gate 恢复摘要(禁止正文、规则 SQL、对象存储 URL)。 + 'gate_code', + 'attempt_no', + 'execution_no', + 'next_action_code', + 'blocking_reason_code', + 'input_fingerprint', + 'responsible_party', }) # 四语言 i18n key 清单(阶段 2 补齐文案;此处仅冻结路径,禁止前端硬编码)。 diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index 3c9b667d..be0a0a54 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -3,9 +3,10 @@ services/shipping_notice/progress_workflow.py 用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。 依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 - state_machine(CheckpointKind)、tool_response。 + state_machine(CheckpointKind)、tool_response、process_gate_bridge。 逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续; STP:must_human / wait_manual_upload 无副作用早停;货代 RPA 上传不在自动链内; + 退出前将 Task 履约状态同步到统一 Process Gate(13–19); 系统触发时事件 actor_id=None 且 detail.source=system。 """ @@ -110,6 +111,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: db.session.commit() except Exception: db.session.rollback() + _sync_process_gates_after_progress(task, payload) return tool_response( status="ok", task=task, @@ -203,14 +205,20 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: inv = ensure_inventory(inv_payload) if inv.get("status") == "running": steps.append("等待库存准备") + _sync_process_gates_after_progress(task, payload) return inv if inv.get("status") != "ok": + _sync_process_gates_after_progress(task, payload) return inv else: steps.append("载入库存") # [STEP 3] 库存就绪后进入履约侧自动推进(止于 Excel 就绪)。 fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps) + + # [STEP 4] 将履约真相同步到 Process Gate(inventory_preparation→manual_upload_handoff)。 + _sync_process_gates_after_progress(task, payload) + if fulfillment_result is not None: return fulfillment_result @@ -221,3 +229,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: message=f"自动推进已完成{suffix}", data=serialize_task_for_tool(task), ) + + +def _sync_process_gates_after_progress(task: Any, payload: dict[str, Any]) -> None: + """ + auto_progress 结束后把 Task 状态桥接到统一门禁。 + + 核心逻辑:存在 Execution 时必须同步成功;失败向上抛出,避免 Workflow/Task 与 Gate 双真相。 + 尚无 Execution(历史任务)时跳过,不阻断推进。 + + Args: + task: ShippingTask 实例。 + payload: 原自动推进载荷(取 operator)。 + """ + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + execution = ( + ShippingProcessExecution.query + .filter_by(task_id=int(task.id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + return + actor_id = payload.get('operator_id') or payload.get('user_id') + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=actor_id, + ) + db.session.flush() diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index a77fcf9d..beb22970 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -2,9 +2,12 @@ services/shipping_notice/ui_state.py 用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 -依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract。 +依赖:models.ShippingTask/ShippingBatch、state_machine、query_service、constants、stp_progress_contract、 + process_gate_projection(统一 Gate 用户摘要)。 逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons, 再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、stp_facts); + 若存在 ProcessExecution 且当前有 blocking Gate,则清空 action_buttons, + 恢复动作仅由 process_gate 驱动(Gate 为唯一业务真相); 批次 UI 仅作会话上传集合摘要,不作为履约写操作面。 """ @@ -546,13 +549,35 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]: 构建单票任务 UI State。 核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/checkpoint_kind/action_buttons/summary, - 禁止 Chat、通知卡与任务中心分别推导状态。 + 禁止 Chat、通知卡与任务中心分别推导状态;有 Execution 时附带统一 Gate 用户摘要; + 存在 current_blocking_gate 时清空 STP action_buttons,恢复仅走 process_gate。 """ ui = resolve_task_ui_state(task) action_buttons = _action_buttons_for_task(task) + process_gate = _process_gate_user_summary_for_task(task) + # [STEP] Gate 阻断时旧 action_buttons 不再作为业务恢复真相,避免双卡片/双动作。 + if isinstance(process_gate, dict) and process_gate.get('current_blocking_gate'): + action_buttons = [] steps = build_shipping_workflow_steps(task, ui.checkpoint) current_index = _derive_current_step_index(task) current_step = steps[current_index] if 0 <= current_index < len(steps) else None + summary = _build_task_summary( + task, + ui.checkpoint, + checkpoint_kind=ui.checkpoint_kind, + action_buttons=action_buttons, + ) + if process_gate is not None: + summary['process_gate'] = process_gate + # 仅输出当前 Gate;删除旧门禁重复摘要键(若历史调用方写入)。 + summary.pop('auto_build_gates', None) + summary.pop('failed_gates', None) + if process_gate.get('blocking_message'): + summary['current_blocking_message'] = process_gate['blocking_message'] + if process_gate.get('diagnostic_hint'): + summary['diagnostic_hint'] = process_gate['diagnostic_hint'] + if process_gate.get('current_blocking_gate'): + summary['allowed_actions'] = [] return { "task_no": task.task_no, "batch_no": task.batch.batch_no if task.batch is not None else None, @@ -564,17 +589,34 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]: "match_status": task.match_status, "current_step": current_step, "steps": steps, - "summary": _build_task_summary( - task, - ui.checkpoint, - checkpoint_kind=ui.checkpoint_kind, - action_buttons=action_buttons, - ), + "summary": summary, "action_buttons": action_buttons, + "process_gate": process_gate, "updated_at": task.updated_at.isoformat() if task.updated_at else None, } +def _process_gate_user_summary_for_task(task: ShippingTask) -> dict[str, Any] | None: + """ + 按 Task 查找活动 Execution 的用户 Gate 摘要。 + + Returns: + project_user_gate_summary;无 Execution 时 None。 + """ + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_projection import project_user_gate_summary + + execution = ( + ShippingProcessExecution.query + .filter_by(task_id=int(task.id)) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) + if execution is None: + return None + return project_user_gate_summary(execution) + + def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]: """ 构建批次级会话上传集合摘要(非履约写操作面)。 diff --git a/backend/app/services/shipping_notice/workflow_progress_projection.py b/backend/app/services/shipping_notice/workflow_progress_projection.py index 251fbc64..cde96a4f 100644 --- a/backend/app/services/shipping_notice/workflow_progress_projection.py +++ b/backend/app/services/shipping_notice/workflow_progress_projection.py @@ -3,11 +3,12 @@ services/shipping_notice/workflow_progress_projection.py 用途:将 Workflow / WorkflowItem / WorkflowEvent 投影为工作台只读 DTO(计数、阶段、摘要)。 依赖:ShippingNoticeWorkflow* 模型、ShippingNoticeDocument、ShippingOrderExtractionRun、 - workflow_ledger_service、progress_audit_contract。 + workflow_ledger_service、progress_audit_contract、process_gate_projection。 逻辑:由 workspace/shipping_notice 工作流读接口调用;解决「Run 已建但 Item=0」—— Item 在版面阶段即存在;会话投影返回全部 open Workflow(非仅第一条); counts.waiting_manual_upload 单独统计,不得并入 completed; - available_actions / reparse_kind 与 ledger 重识别资格同源,禁止前端自行推导。 + available_actions / reparse_kind 与 ledger 重识别资格同源,禁止前端自行推导; + 用户提示优先消费统一 Gate 摘要(唯一当前阻断),不再平行拼旧五门禁文案。 """ from __future__ import annotations @@ -224,7 +225,8 @@ def serialize_workflow_item( 序列化 WorkflowItem 用户态投影。 核心逻辑:附带当前/根 Document 文件名,供工作台列表直接展示 PDF 名; - 附带 available_actions / reparse_kind,供前端按权威契约展示按钮。 + 附带 available_actions / reparse_kind,供前端按权威契约展示按钮; + 若存在活动 ProcessExecution,附带统一 Gate 用户摘要(唯一阻断)。 Args: item: WorkflowItem ORM。 @@ -261,6 +263,14 @@ def serialize_workflow_item( 'available_actions': available_actions, 'reparse_kind': reparse_kind, } + gate_summary = _process_gate_user_summary_for_item(item) + if gate_summary is not None: + payload['process_gate'] = gate_summary + # 工作台提示只展示当前唯一阻断,避免旧检查点平行文案。 + if gate_summary.get('blocking_message'): + payload['gate_user_hint'] = gate_summary.get('blocking_message') + elif gate_summary.get('diagnostic_hint'): + payload['gate_user_hint'] = gate_summary.get('diagnostic_hint') if include_events: events = ( ShippingNoticeWorkflowEvent.query @@ -272,6 +282,26 @@ def serialize_workflow_item( return payload +def _process_gate_user_summary_for_item(item: ShippingNoticeWorkflowItem) -> dict[str, Any] | None: + """ + 按 WorkflowItem 当前版本查找活动 Execution 的用户 Gate 摘要。 + + Returns: + project_user_gate_summary 结果;无 Execution 时 None。 + """ + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_projection import project_user_gate_summary + + version_id = getattr(item, 'current_version_id', None) + query = ShippingProcessExecution.query.filter_by(workflow_item_id=int(item.id)) + if version_id is not None: + query = query.filter_by(workflow_item_version_id=int(version_id)) + execution = query.order_by(ShippingProcessExecution.id.desc()).first() + if execution is None: + return None + return project_user_gate_summary(execution) + + def serialize_workflow( workflow: ShippingNoticeWorkflow, *, diff --git a/backend/migrations/versions/b8c9d0e1f2a4_add_external_reservation_id_alias.py b/backend/migrations/versions/b8c9d0e1f2a4_add_external_reservation_id_alias.py new file mode 100644 index 00000000..a2a39dc4 --- /dev/null +++ b/backend/migrations/versions/b8c9d0e1f2a4_add_external_reservation_id_alias.py @@ -0,0 +1,72 @@ +""" +migrations/versions/b8c9d0e1f2a4_add_external_reservation_id_alias.py + +用途:为发货订单 Schema 的行级预约号补充真实邮件表头 External reservation ID。 +依赖:shipping_order_schemas、shipping_order_schema_versions,以及当前统一 Alembic head。 +逻辑:遍历 STANDARD_SHIPPING_NOTICE 的历史与当前版本,幂等追加显式别名并重算 +definition checksum;不修改历史 Run 已冻结快照,重识别时由新 Run 使用更新后的 Schema。 +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any + +from alembic import op +import sqlalchemy as sa + + +revision = 'b8c9d0e1f2a4' +down_revision = 'a7b8c9d0e1f3' +branch_labels = None +depends_on = None + + +_ALIAS = 'External reservation ID' + + +def _definition_checksum(definition: dict[str, Any]) -> str: + """使用 Schema 发布服务相同的规范 JSON 算法重算配置校验和。""" + encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8') + return hashlib.sha256(encoded).hexdigest() + + +def upgrade() -> None: + """为所有标准 Schema 版本的行级 reservation_id 幂等追加邮件表头别名。""" + bind = op.get_bind() + rows = bind.execute(sa.text(""" + SELECT version.id, version.definition_json + FROM shipping_order_schema_versions AS version + JOIN shipping_order_schemas AS schema ON schema.id = version.schema_id + WHERE schema.schema_code = 'STANDARD_SHIPPING_NOTICE' + """)).mappings().all() + for row in rows: + raw_definition = row['definition_json'] + definition = json.loads(raw_definition) if isinstance(raw_definition, str) else dict(raw_definition or {}) + fields = definition.get('fields') if isinstance(definition.get('fields'), list) else [] + changed = False + for field in fields: + if not isinstance(field, dict): + continue + if str(field.get('field_code') or '') != 'reservation_id' or str(field.get('scope') or '') != 'line': + continue + aliases = [str(value).strip() for value in field.get('aliases') or [] if str(value).strip()] + if _ALIAS not in aliases: + field['aliases'] = [*aliases, _ALIAS] + changed = True + if changed: + bind.execute(sa.text(""" + UPDATE shipping_order_schema_versions + SET definition_json = CAST(:definition_json AS jsonb), checksum = :checksum + WHERE id = :version_id + """), { + 'version_id': int(row['id']), + 'definition_json': json.dumps(definition, ensure_ascii=False), + 'checksum': _definition_checksum(definition), + }) + + +def downgrade() -> None: + """配置别名迁移不可逆,避免回滚后已冻结识别规则失去解释能力。""" + pass diff --git a/backend/migrations/versions/d0e1f2a3b4c6_add_shipping_process_gate_recovery.py b/backend/migrations/versions/d0e1f2a3b4c6_add_shipping_process_gate_recovery.py new file mode 100644 index 00000000..b0329486 --- /dev/null +++ b/backend/migrations/versions/d0e1f2a3b4c6_add_shipping_process_gate_recovery.py @@ -0,0 +1,253 @@ +""" +migrations/versions/d0e1f2a3b4c6_add_shipping_process_gate_recovery.py + +用途:新增门禁恢复三表 ShippingProcessExecution / Gate / Attempt 及唯一约束与索引; + 并扩展 shipping_audit_events.actor_type 允许 worker。 +依赖:shipping_notice_workflow_items/versions、shipping_order_review_cases、shipping_tasks、jobs、 + shipping_audit_events;Alembic revision b8c9d0e1f2a4。 +逻辑:建表与约束,不迁移历史运行实例;同步放宽审计 actor CHECK;downgrade 删除三表并回退 CHECK。 +说明:原误用 revision c9d0e1f2a3b5(与 seed_file_asset_cleanup_schedule 冲突),已改为 d0e1f2a3b4c6。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'd0e1f2a3b4c6' +down_revision = 'b8c9d0e1f2a4' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建 Execution / Gate / Attempt 三表、外键、唯一约束与查询索引。""" + op.create_table( + 'shipping_process_executions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('execution_no', sa.String(length=64), nullable=False), + sa.Column('workflow_item_id', sa.Integer(), nullable=False), + sa.Column('workflow_item_version_id', sa.Integer(), nullable=False), + sa.Column('review_case_id', sa.Integer(), nullable=True), + sa.Column('task_id', sa.Integer(), nullable=True), + sa.Column('status', sa.String(length=32), nullable=False, server_default='active'), + sa.Column('current_gate_code', sa.String(length=64), nullable=True), + sa.Column('last_passed_gate_code', sa.String(length=64), nullable=True), + sa.Column('primary_next_action_code', sa.String(length=64), nullable=True), + sa.Column('responsible_party', sa.String(length=32), nullable=True), + sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')", + name='ck_shipping_process_executions_status', + ), + sa.CheckConstraint('lock_version >= 1', name='ck_shipping_process_executions_lock_version'), + sa.ForeignKeyConstraint(['workflow_item_id'], ['shipping_notice_workflow_items.id']), + sa.ForeignKeyConstraint(['workflow_item_version_id'], ['shipping_notice_workflow_item_versions.id']), + sa.ForeignKeyConstraint(['review_case_id'], ['shipping_order_review_cases.id']), + sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']), + sa.UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'), + sa.UniqueConstraint( + 'workflow_item_version_id', + name='uq_shipping_process_executions_workflow_item_version', + ), + ) + op.create_index( + 'ix_shipping_process_executions_status_updated', + 'shipping_process_executions', + ['status', 'updated_at'], + ) + op.create_index( + 'ix_shipping_process_executions_workflow_item', + 'shipping_process_executions', + ['workflow_item_id', 'updated_at'], + ) + op.create_index( + 'ix_shipping_process_executions_current_gate', + 'shipping_process_executions', + ['current_gate_code', 'status', 'updated_at'], + ) + op.create_index( + 'ix_shipping_process_executions_review_case', + 'shipping_process_executions', + ['review_case_id'], + ) + op.create_index( + 'ix_shipping_process_executions_task', + 'shipping_process_executions', + ['task_id'], + ) + + op.create_table( + 'shipping_process_gates', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('execution_id', sa.Integer(), nullable=False), + sa.Column('gate_code', sa.String(length=64), nullable=False), + sa.Column('sequence_no', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'), + sa.Column('evaluation_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('input_fingerprint', sa.String(length=64), nullable=True), + sa.Column('blocking_reason_code', sa.String(length=64), nullable=True), + sa.Column('blocking_reason_json', sa.JSON(), nullable=True), + sa.Column('recommendation_json', sa.JSON(), nullable=True), + sa.Column('effective_result_json', sa.JSON(), nullable=True), + sa.Column('next_action_code', sa.String(length=64), nullable=True), + sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'), + sa.Column('latest_attempt_id', sa.Integer(), nullable=True), + sa.Column('passed_at', sa.DateTime(), nullable=True), + sa.Column('invalidated_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "status IN (" + "'pending', 'queued', 'running', 'passed', 'blocked_retryable', " + "'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped'" + ")", + name='ck_shipping_process_gates_status', + ), + sa.CheckConstraint('sequence_no >= 1', name='ck_shipping_process_gates_sequence'), + sa.CheckConstraint('evaluation_version >= 1', name='ck_shipping_process_gates_eval_version'), + sa.CheckConstraint('lock_version >= 1', name='ck_shipping_process_gates_lock_version'), + sa.ForeignKeyConstraint( + ['execution_id'], + ['shipping_process_executions.id'], + ondelete='CASCADE', + ), + sa.UniqueConstraint( + 'execution_id', + 'gate_code', + name='uq_shipping_process_gates_execution_code', + ), + sa.UniqueConstraint( + 'execution_id', + 'sequence_no', + name='uq_shipping_process_gates_execution_sequence', + ), + ) + op.create_index( + 'ix_shipping_process_gates_execution_status', + 'shipping_process_gates', + ['execution_id', 'status', 'updated_at'], + ) + op.create_index( + 'ix_shipping_process_gates_code_status', + 'shipping_process_gates', + ['gate_code', 'status', 'updated_at'], + ) + + op.create_table( + 'shipping_process_gate_attempts', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('gate_id', sa.Integer(), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('trigger_type', sa.String(length=32), nullable=False, server_default='auto'), + sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'), + sa.Column('actor_id', sa.String(length=64), nullable=True), + sa.Column('idempotency_key', sa.String(length=128), nullable=False), + sa.Column('input_snapshot_json', sa.JSON(), nullable=True), + sa.Column('input_snapshot_hash', sa.String(length=64), nullable=True), + sa.Column('rule_snapshot_json', sa.JSON(), nullable=True), + sa.Column('rule_snapshot_hash', sa.String(length=64), nullable=True), + sa.Column('output_snapshot_json', sa.JSON(), nullable=True), + sa.Column('output_snapshot_hash', sa.String(length=64), nullable=True), + sa.Column('job_id', sa.Integer(), nullable=True), + sa.Column('worker_id', sa.String(length=64), nullable=True), + sa.Column('lease_token', sa.String(length=64), nullable=True), + sa.Column('lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('heartbeat_at', sa.DateTime(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('error_code', sa.String(length=64), nullable=True), + sa.Column('error_summary', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled', 'superseded')", + name='ck_shipping_process_gate_attempts_status', + ), + sa.CheckConstraint('attempt_no >= 1', name='ck_shipping_process_gate_attempts_no'), + sa.CheckConstraint( + "trigger_type IN (" + "'auto', 'user_retry', 'user_manual', 'worker_takeover', " + "'upstream_invalidation', 'system_requeue'" + ")", + name='ck_shipping_process_gate_attempts_trigger', + ), + sa.CheckConstraint( + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')", + name='ck_shipping_process_gate_attempts_actor_type', + ), + sa.ForeignKeyConstraint( + ['gate_id'], + ['shipping_process_gates.id'], + ondelete='CASCADE', + ), + sa.ForeignKeyConstraint(['job_id'], ['jobs.id']), + sa.UniqueConstraint( + 'gate_id', + 'attempt_no', + name='uq_shipping_process_gate_attempts_gate_no', + ), + sa.UniqueConstraint( + 'idempotency_key', + name='uq_shipping_process_gate_attempts_idempotency', + ), + ) + op.create_index( + 'uq_shipping_process_gate_attempts_one_active', + 'shipping_process_gate_attempts', + ['gate_id'], + unique=True, + postgresql_where=sa.text("status IN ('queued', 'running')"), + sqlite_where=sa.text("status IN ('queued', 'running')"), + ) + op.create_index( + 'ix_shipping_process_gate_attempts_lease', + 'shipping_process_gate_attempts', + ['lease_token', 'lease_expires_at'], + ) + op.create_index( + 'ix_shipping_process_gate_attempts_job', + 'shipping_process_gate_attempts', + ['job_id'], + ) + op.create_index( + 'ix_shipping_process_gate_attempts_gate_status', + 'shipping_process_gate_attempts', + ['gate_id', 'status', 'created_at'], + ) + # [STEP] 门禁 Worker 审计需要 actor_type=worker。 + with op.batch_alter_table('shipping_audit_events') as batch_op: + batch_op.drop_constraint('ck_shipping_audit_events_actor_type', type_='check') + batch_op.create_check_constraint( + 'ck_shipping_audit_events_actor_type', + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')", + ) + + +def downgrade() -> None: + """删除门禁恢复三表(先 Attempt → Gate → Execution)并回退审计 actor CHECK。""" + with op.batch_alter_table('shipping_audit_events') as batch_op: + batch_op.drop_constraint('ck_shipping_audit_events_actor_type', type_='check') + batch_op.create_check_constraint( + 'ck_shipping_audit_events_actor_type', + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')", + ) + op.drop_index('ix_shipping_process_gate_attempts_gate_status', table_name='shipping_process_gate_attempts') + op.drop_index('ix_shipping_process_gate_attempts_job', table_name='shipping_process_gate_attempts') + op.drop_index('ix_shipping_process_gate_attempts_lease', table_name='shipping_process_gate_attempts') + op.drop_index('uq_shipping_process_gate_attempts_one_active', table_name='shipping_process_gate_attempts') + op.drop_table('shipping_process_gate_attempts') + + op.drop_index('ix_shipping_process_gates_code_status', table_name='shipping_process_gates') + op.drop_index('ix_shipping_process_gates_execution_status', table_name='shipping_process_gates') + op.drop_table('shipping_process_gates') + + op.drop_index('ix_shipping_process_executions_task', table_name='shipping_process_executions') + op.drop_index('ix_shipping_process_executions_review_case', table_name='shipping_process_executions') + op.drop_index('ix_shipping_process_executions_current_gate', table_name='shipping_process_executions') + op.drop_index('ix_shipping_process_executions_workflow_item', table_name='shipping_process_executions') + op.drop_index('ix_shipping_process_executions_status_updated', table_name='shipping_process_executions') + op.drop_table('shipping_process_executions') diff --git a/backend/tests/test_shipping_process_gate_api.py b/backend/tests/test_shipping_process_gate_api.py new file mode 100644 index 00000000..b7a05ef7 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_api.py @@ -0,0 +1,208 @@ +""" +tests/test_shipping_process_gate_api.py + +用途:Phase 5 Workspace/Admin 门禁 API 的 Envelope、403/404、禁止控制字段与幂等行为。 +依赖:Flask test client、JWT、process_gate_service / bridge 夹具、Agent 授权关系。 +逻辑:属主可读可写;同 Agent 授权人员只读;未授权他人 403;forbidden payload 400; + 同幂等键 POST 不产生第二 Attempt。 +""" + +from __future__ import annotations + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.models import Agent, ShippingProcessGate, ShippingProcessGateAttempt, User +from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome +from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version +from tests.test_shipping_process_gate_service import _seed_workflow_version + + +def _auth_headers(user: User) -> dict[str, str]: + """构造 Bearer 头。""" + return {'Authorization': f'Bearer {issue_local_access_token(user)}', 'Content-Type': 'application/json'} + + +def _seed_blocked_execution(owner: User | None = None): + """ + 创建属主 WorkflowItem + Execution,并将 order_freeze_readiness 置为 blocked_manual。 + + Returns: + (owner, execution, gate) + """ + suffix = f'api{owner.id if owner else "x"}'[:24] + user, item, version = _seed_workflow_version(suffix=suffix) + if owner is not None: + item.owner_user_id = int(owner.id) + db.session.flush() + user = owner + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + actor_type='system', + actor_id=int(user.id), + ) + apply_gate_outcome( + execution=execution, + gate_code='order_freeze_readiness', + passed=False, + blocking_reason_code='auto_freeze_not_enabled', + effective_result={'findings': []}, + force=True, + idempotency_key=f'api-freeze-{execution.execution_no}', + ) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), + gate_code='order_freeze_readiness', + ).first() + db.session.commit() + return user, execution, gate + + +def test_workspace_get_execution_owner_ok_other_forbidden(app, client): + """属主可 GET Execution;未授权他人返回 403。""" + with app.app_context(): + owner, execution, _gate = _seed_blocked_execution() + other = User(username='gate-api-other', email='gate-api-other@example.com', password_hash='x') + db.session.add(other) + db.session.commit() + execution_no = execution.execution_no + + ok = client.get( + f'/api/workspace/shipping-notice/process-executions/{execution_no}', + headers=_auth_headers(owner), + ) + assert ok.status_code == 200 + body = ok.get_json() + assert body.get('success') is True + assert body['data']['execution_no'] == execution_no + + denied = client.get( + f'/api/workspace/shipping-notice/process-executions/{execution_no}', + headers=_auth_headers(other), + ) + assert denied.status_code == 403 + err = denied.get_json() + assert err.get('success') is False + assert err.get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_PERMISSION_DENIED' + + +def test_workspace_agent_authorized_readonly_cannot_write(app, client): + """同 Agent 授权人员可 GET,但 POST 恢复仍 403。""" + with app.app_context(): + owner, execution, gate = _seed_blocked_execution() + agent = Agent( + name='Gate Readonly Agent', + agent_code='gate_readonly_agent', + dify_app_id='gate-readonly-app', + dify_api_key='test-key', + ) + viewer = User(username='gate-api-viewer', email='gate-api-viewer@example.com', password_hash='x') + db.session.add_all([agent, viewer]) + db.session.flush() + from app.models import ShippingNoticeWorkflow, ShippingNoticeWorkflowItem + + item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id)) + assert item is not None + workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id)) + assert workflow is not None + workflow.owner_agent_id = int(agent.id) + viewer.agents = [agent] + db.session.commit() + execution_no = execution.execution_no + + read_ok = client.get( + f'/api/workspace/shipping-notice/process-executions/{execution_no}', + headers=_auth_headers(viewer), + ) + assert read_ok.status_code == 200 + assert read_ok.get_json()['data']['execution_no'] == execution_no + + write_denied = client.post( + f'/api/workspace/shipping-notice/process-executions/{execution_no}' + f'/gates/order_freeze_readiness/actions', + headers=_auth_headers(viewer), + json={ + 'action_code': 'open_order_review', + 'expected_gate_version': int(gate.evaluation_version), + 'idempotency_key': 'api-readonly-write-1', + }, + ) + assert write_denied.status_code == 403 + assert write_denied.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_PERMISSION_DENIED' + + +def test_workspace_post_action_rejects_forbidden_controls(app, client): + """POST 含 target_status 必须 400 且无 Attempt 副作用。""" + with app.app_context(): + owner, execution, gate = _seed_blocked_execution() + execution_no = execution.execution_no + before = ShippingProcessGateAttempt.query.count() + resp = client.post( + f'/api/workspace/shipping-notice/process-executions/{execution_no}' + f'/gates/order_freeze_readiness/actions', + headers=_auth_headers(owner), + json={ + 'action_code': 'open_order_review', + 'expected_gate_version': int(gate.evaluation_version), + 'idempotency_key': 'api-forbidden-1', + 'target_status': 'passed', + }, + ) + assert resp.status_code == 400 + assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN' + assert ShippingProcessGateAttempt.query.count() == before + + +def test_workspace_post_action_idempotent(app, client): + """相同幂等键连续 POST 只产生一个 Attempt,并返回成功 Envelope。""" + with app.app_context(): + owner, execution, gate = _seed_blocked_execution() + execution_no = execution.execution_no + payload = { + 'action_code': 'open_order_review', + 'expected_gate_version': int(gate.evaluation_version), + 'idempotency_key': 'api-idempotent-1', + 'payload': {'note': 'first'}, + } + url = ( + f'/api/workspace/shipping-notice/process-executions/{execution_no}' + f'/gates/order_freeze_readiness/actions' + ) + first = client.post(url, headers=_auth_headers(owner), json=payload) + assert first.status_code == 200 + first_body = first.get_json() + assert first_body.get('success') is True + attempt_id = first_body['data']['attempt']['id'] + + # 版本已前进时,回放同幂等键仍应返回首次 Attempt,不新建。 + second = client.post(url, headers=_auth_headers(owner), json=payload) + assert second.status_code == 200 + second_body = second.get_json() + assert second_body['data']['attempt']['id'] == attempt_id + assert second_body['data'].get('dispatch') == 'idempotent_replay' + assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='api-idempotent-1').count() == 1 + + +def test_workspace_get_missing_execution_404(app, client): + """不存在的 execution_no 返回 404。""" + with app.app_context(): + user = User(username='gate-api-404', email='gate-api-404@example.com', password_hash='x') + db.session.add(user) + db.session.commit() + resp = client.get( + '/api/workspace/shipping-notice/process-executions/SPE-NOT-EXIST', + headers=_auth_headers(user), + ) + assert resp.status_code == 404 + assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_EXECUTION_NOT_FOUND' + + +def test_admin_list_executions_requires_admin(app, client): + """Admin 列表接口拒绝普通用户。""" + with app.app_context(): + owner, _execution, _gate = _seed_blocked_execution() + resp = client.get( + '/api/admin/shipping-notice/process-executions', + headers=_auth_headers(owner), + ) + assert resp.status_code in {401, 403} diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py new file mode 100644 index 00000000..a390fea1 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -0,0 +1,97 @@ +""" +tests/test_shipping_process_gate_contract.py + +用途:锁定全门禁中断恢复 Phase 1/1.5 契约与依赖图完整性(编码、动作、失效范围、原因归属)。 +依赖:process_gate_contract、process_gate_dependency。 +逻辑:调用 assert_*_integrity;断言 19 个唯一门禁、原因码唯一 owning_gate、 + 字段阻断资格与 Excel 仅重生失效范围。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.process_gate_contract import ( + AUTO_BUILD_LEGACY_GATE_OWNING_MAP, + PROCESS_GATE_CODES, + PROCESS_GATE_CODE_SET, + PROCESS_GATE_DEFINITIONS, + PROCESS_GATE_REASON_OWNING_GATE, + assert_process_gate_contract_integrity, + field_quality_may_block, + owning_gate_for_reason, + primary_next_action_for_gate, +) +from app.services.shipping_notice.process_gate_dependency import ( + PROCESS_GATE_INVALIDATION_RULES, + assert_process_gate_dependency_integrity, + compute_invalidated_gates, +) + + +def test_process_gate_contract_integrity(): + """ + 校验门禁契约无重复编码、序号连续且动作/状态闭环。 + + 核心逻辑:直接调用契约自检;再断言恰好 19 个唯一 gate_code。 + """ + # [STEP 1] 契约自检(重复码 / 序号 / 动作归属) + assert_process_gate_contract_integrity() + + # [STEP 2] 冻结规模:19 门禁且集合与有序列表一致 + assert len(PROCESS_GATE_DEFINITIONS) == 19 + assert len(PROCESS_GATE_CODES) == 19 + assert len(PROCESS_GATE_CODE_SET) == 19 + assert set(PROCESS_GATE_CODES) == PROCESS_GATE_CODE_SET + + +def test_inventory_source_routing_primary_retry_action(): + """ + 库存源路由在 blocked_retryable 时主恢复动作必须为按最新规则重试。 + + 核心逻辑:primary_next_action_for_gate 禁止前端本地推导。 + """ + action = primary_next_action_for_gate( + gate_code='inventory_source_routing', + status='blocked_retryable', + ) + assert action == 'retry_with_latest_rules' + + +def test_process_gate_reason_ownership_is_unique(): + """ + 每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。 + + 核心逻辑:契约自检 + 显式抽查自动冻结与字段完整性归属。 + """ + assert_process_gate_contract_integrity() + assert owning_gate_for_reason('profile_manual_confirmation_required') == 'order_freeze_readiness' + assert owning_gate_for_reason('required_field_missing') == 'field_completeness' + assert owning_gate_for_reason('customer_unresolved') == 'customer_resolution' + assert owning_gate_for_reason('evidence_missing') == 'order_field_extraction' + # 旧五门禁键不得再各自成为用户阻断真相。 + assert AUTO_BUILD_LEGACY_GATE_OWNING_MAP['quality_gate_passed'] == 'order_freeze_readiness' + assert AUTO_BUILD_LEGACY_GATE_OWNING_MAP['approved_template'] == 'order_freeze_readiness' + assert len(PROCESS_GATE_REASON_OWNING_GATE) == len(set(PROCESS_GATE_REASON_OWNING_GATE.keys())) + + +def test_field_quality_block_eligibility(): + """仅 required 或 auto_create_key_field 可因字段质量阻断。""" + assert field_quality_may_block(required=True, auto_create_key_field=False) is True + assert field_quality_may_block(required=False, auto_create_key_field=True) is True + assert field_quality_may_block(required=False, auto_create_key_field=False) is False + + +def test_process_gate_dependency_integrity_and_excel_only_scope(): + """ + 校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。 + + 核心逻辑:依赖自检 + excel_regeneration_only 显式排除 inventory_matching。 + """ + # [STEP 1] 前置依赖与失效规则仅引用已知门禁 + assert_process_gate_dependency_integrity() + + # [STEP 2] 仅重生 Excel:失效 artifact + 人工上传,不碰库存匹配 + excel_only = compute_invalidated_gates('excel_regeneration_only') + assert 'inventory_matching' not in excel_only + assert 'artifact_generation' in excel_only + assert 'manual_upload_handoff' in excel_only + assert set(excel_only) == set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only']) diff --git a/backend/tests/test_shipping_process_gate_error_sanitizer.py b/backend/tests/test_shipping_process_gate_error_sanitizer.py new file mode 100644 index 00000000..91321fa2 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_error_sanitizer.py @@ -0,0 +1,29 @@ +""" +tests/test_shipping_process_gate_error_sanitizer.py + +用途:验证门禁异常摘要脱敏会剥离 URL、路径与凭据片段。 +依赖:process_gate_error_sanitizer.sanitize_gate_error_text。 +逻辑:对含敏感片段的样本文本断言输出不含原值且保留可读业务提示。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text + + +def test_sanitize_gate_error_text_redacts_url_path_and_secret(): + """URL、Windows 路径与 password= 片段必须被遮蔽。""" + raw = ( + 'failed call https://erp.example.com/api?token=abc ' + r'at C:\service\worker.py password=super-secret ' + 'detail=timeout' + ) + cleaned = sanitize_gate_error_text(raw, max_len=500) + assert cleaned is not None + assert 'https://' not in cleaned + assert 'erp.example.com' not in cleaned + assert r'C:\service' not in cleaned + assert 'super-secret' not in cleaned + assert '[url]' in cleaned + assert '[path]' in cleaned + assert 'timeout' in cleaned diff --git a/backend/tests/test_shipping_process_gate_fault_injection.py b/backend/tests/test_shipping_process_gate_fault_injection.py new file mode 100644 index 00000000..137e647e --- /dev/null +++ b/backend/tests/test_shipping_process_gate_fault_injection.py @@ -0,0 +1,200 @@ +""" +tests/test_shipping_process_gate_fault_injection.py + +用途:Phase 7 故障注入——幂等连点、审计失败回滚语义、租约冲突、双路径不双写。 +依赖:process_gate_service、process_gate_recovery_service、Flask testing app。 +逻辑:在最小 Execution 夹具上模拟重复恢复请求与审计异常,断言无副作用双写。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.core.errors import ConflictError, ServiceUnavailableError +from app.models import ShippingProcessGateAttempt +from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome +from app.services.shipping_notice.process_gate_recovery_service import request_gate_action +from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + queue_gate_attempt, +) +from tests.test_shipping_process_gate_service import _seed_workflow_version + + +def test_ten_identical_recovery_clicks_create_one_attempt(app): + """同一幂等键连点十次只产生一个 Attempt。""" + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix='fault1') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + apply_gate_outcome( + execution=execution, + gate_code='layout_parsing', + passed=False, + blocking_reason_code='layout_parse_failed', + effective_result={'findings': []}, + force=True, + idempotency_key='layout-fail-seed', + ) + gate = ( + db.session.query(__import__('app.models', fromlist=['ShippingProcessGate']).ShippingProcessGate) + .filter_by(execution_id=int(execution.id), gate_code='layout_parsing') + .first() + ) + key = 'fault-ten-clicks' + first = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key=key, + expected_gate_version=int(gate.evaluation_version), + ) + for _ in range(9): + again = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key=key, + expected_gate_version=int(gate.evaluation_version), + ) + assert int(again.id) == int(first.id) + assert ShippingProcessGateAttempt.query.filter_by(idempotency_key=key).count() == 1 + + +def test_active_attempt_blocks_second_queue(app): + """已有活动 Attempt 时第二次不同幂等键必须 Conflict。""" + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix='fault2') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + apply_gate_outcome( + execution=execution, + gate_code='layout_parsing', + passed=False, + blocking_reason_code='layout_parse_failed', + effective_result={}, + force=True, + idempotency_key='layout-fail-2', + ) + from app.models import ShippingProcessGate + + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='layout_parsing', + ).first() + queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='active-a', + expected_gate_version=int(gate.evaluation_version), + ) + db.session.refresh(gate) + with pytest.raises(ConflictError) as exc: + queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='active-b', + expected_gate_version=int(gate.evaluation_version), + ) + assert exc.value.code == 'SHIPPING.PROCESS_GATE_BUSY' + + +def test_audit_failure_rolls_back_gate_queue(app, monkeypatch): + """ + 审计失败时业务事务应整体失败,不留下半成品 Attempt。 + + 核心逻辑:monkeypatch record_fulfillment_audit 抛错,断言 queue 抛出且无 Attempt 行。 + """ + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix='fault3') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + apply_gate_outcome( + execution=execution, + gate_code='layout_parsing', + passed=False, + blocking_reason_code='layout_parse_failed', + effective_result={}, + force=True, + idempotency_key='layout-fail-3', + ) + from app.models import ShippingProcessGate + + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='layout_parsing', + ).first() + version_before = int(gate.evaluation_version) + + def _boom(**kwargs): + raise ServiceUnavailableError('audit down', code='SHIPPING.AUDIT_UNAVAILABLE') + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.record_fulfillment_audit', + _boom, + ) + with pytest.raises(ServiceUnavailableError): + queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='audit-fail-key', + expected_gate_version=version_before, + ) + db.session.rollback() + assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='audit-fail-key').count() == 0 + + +def test_request_gate_action_rejects_forbidden_controls(app): + """客户端提交 target_status / worker_name 必须被拒绝。""" + from app.core.errors import ValidationError + + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix='fault4') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + apply_gate_outcome( + execution=execution, + gate_code='order_freeze_readiness', + passed=False, + blocking_reason_code='auto_freeze_not_enabled', + effective_result={}, + force=True, + idempotency_key='freeze-block-fault', + ) + from app.models import ShippingProcessGate + + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='order_freeze_readiness', + ).first() + with pytest.raises(ValidationError) as exc: + request_gate_action( + execution_no=execution.execution_no, + gate_code='order_freeze_readiness', + action_code='open_order_review', + expected_gate_version=int(gate.evaluation_version), + idempotency_key='forbidden-payload', + actor_type='user', + actor_id=1, + payload={'target_status': 'passed', 'worker_name': 'evil'}, + ) + assert exc.value.code == 'SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN' diff --git a/backend/tests/test_shipping_process_gate_lease.py b/backend/tests/test_shipping_process_gate_lease.py new file mode 100644 index 00000000..8a76ebd5 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_lease.py @@ -0,0 +1,147 @@ +""" +tests/test_shipping_process_gate_lease.py + +用途:验证门禁 Attempt 租约竞争、心跳续租与超时接管。 +依赖:process_gate_job_service、process_gate_service、Flask testing app。 +逻辑:创建 queued Attempt 后双 Worker claim,仅一方持有租约;心跳超时后 recover 接管。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from app import db +from app.models import ShippingProcessGateAttempt +from app.services.shipping_notice.process_gate_job_service import ( + claim_and_run_gate_attempt, + heartbeat_gate_attempt, + recover_stale_gate_attempts, +) +from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + mark_attempt_running, + queue_gate_attempt, +) +from tests.test_shipping_process_gate_service import _seed_workflow_version + + +def test_lease_takeover_after_stale_heartbeat(app, monkeypatch): + """心跳超过接管阈值后,recover_stale_gate_attempts 必须接管。""" + with app.app_context(): + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service._takeover_seconds', + lambda: 30, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', + lambda **kwargs: 0, + ) + _user, item, version = _seed_workflow_version(suffix='lease1') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='system', + actor_id='w1', + idempotency_key='lease-takeover-1', + ) + mark_attempt_running( + attempt_id=int(attempt.id), + worker_id='worker-a', + lease_token='token-a', + lease_expires_at=datetime.utcnow() - timedelta(seconds=120), + ) + # 心跳早于接管阈值(默认/补丁 30s)即可被 recover 选中。 + attempt.heartbeat_at = datetime.utcnow() - timedelta(seconds=120) + db.session.flush() + + taken = recover_stale_gate_attempts(worker_id='worker-b') + assert int(attempt.id) in taken + db.session.refresh(attempt) + assert attempt.status == 'queued' + assert attempt.worker_id is None + assert attempt.lease_token is None + + +def test_heartbeat_rejects_foreign_lease(app): + """租约 Token 不匹配时心跳必须 Conflict。""" + from app.core.errors import ConflictError + + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix='lease2') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='layout_parsing', + trigger_type='auto', + actor_type='system', + actor_id='w1', + idempotency_key='lease-hb-1', + ) + mark_attempt_running( + attempt_id=int(attempt.id), + worker_id='worker-a', + lease_token='token-a', + lease_expires_at=datetime.utcnow() + timedelta(seconds=60), + ) + try: + heartbeat_gate_attempt( + attempt_id=int(attempt.id), + worker_id='worker-b', + lease_token='wrong', + ) + assert False, 'expected ConflictError' + except ConflictError as err: + assert err.code == 'SHIPPING.PROCESS_GATE_LEASE_CONFLICT' + + +def test_sync_manual_open_via_claim_and_run(app, monkeypatch): + """claim_and_run 对同步人工入口动作可完成 Attempt。""" + with app.app_context(): + # enqueue 在 recover 空跑时无副作用;claim 路径执行 open_order_review。 + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', + lambda **kwargs: 0, + ) + _user, item, version = _seed_workflow_version(suffix='lease3') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + # 先阻断冻结门禁,再排队人工打开动作。 + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + apply_gate_outcome( + execution=execution, + gate_code='order_freeze_readiness', + passed=False, + blocking_reason_code='auto_freeze_not_enabled', + effective_result={'findings': []}, + force=True, + idempotency_key='freeze-block-1', + ) + gate = db.session.query(__import__('app.models', fromlist=['ShippingProcessGate']).ShippingProcessGate).filter_by( + execution_id=int(execution.id), + gate_code='order_freeze_readiness', + ).first() + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='order_freeze_readiness', + trigger_type='user_manual', + actor_type='user', + actor_id=1, + idempotency_key='open-review-1', + expected_gate_version=int(gate.evaluation_version), + input_snapshot={'action_code': 'open_order_review', 'payload': {'actor_user_id': 1}}, + ) + result = claim_and_run_gate_attempt(attempt_id=int(attempt.id), worker_id='worker-sync') + assert result.get('skipped') is False + db.session.refresh(attempt) + assert attempt.status in {'succeeded', 'failed'} diff --git a/backend/tests/test_shipping_process_gate_migration.py b/backend/tests/test_shipping_process_gate_migration.py new file mode 100644 index 00000000..72a9766e --- /dev/null +++ b/backend/tests/test_shipping_process_gate_migration.py @@ -0,0 +1,87 @@ +""" +tests/test_shipping_process_gate_migration.py + +用途:验证门禁恢复迁移 upgrade/downgrade 往返及关键索引存在。 +依赖:Alembic Operations、SQLite 内存库、d0e1f2a3b4c6 迁移。 +逻辑:构造最小父表 → upgrade 断言三表与活动 Attempt 唯一索引 → downgrade 断言表消失。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_shipping_process_gate_migration_round_trip(monkeypatch): + """upgrade 创建三表与索引;downgrade 完整删除。""" + migration = importlib.import_module( + 'migrations.versions.d0e1f2a3b4c6_add_shipping_process_gate_recovery', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_order_review_cases', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_notice_workflow_items', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_notice_workflow_item_versions', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + # 迁移会放宽 shipping_audit_events.actor_type CHECK,测试库需有最小表桩。 + sa.Table( + 'shipping_audit_events', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('actor_type', sa.String(length=32), nullable=False), + sa.CheckConstraint( + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')", + name='ck_shipping_audit_events_actor_type', + ), + ) + metadata.create_all(engine) + + with engine.begin() as connection: + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + inspector = sa.inspect(connection) + tables = set(inspector.get_table_names()) + assert 'shipping_process_executions' in tables + assert 'shipping_process_gates' in tables + assert 'shipping_process_gate_attempts' in tables + + attempt_indexes = { + item['name'] for item in inspector.get_indexes('shipping_process_gate_attempts') + } + assert 'uq_shipping_process_gate_attempts_one_active' in attempt_indexes + assert 'uq_shipping_process_gate_attempts_idempotency' in { + *(item['name'] for item in inspector.get_indexes('shipping_process_gate_attempts')), + *( + item['name'] + for item in inspector.get_unique_constraints('shipping_process_gate_attempts') + ), + } + + execution_indexes = { + item['name'] for item in inspector.get_indexes('shipping_process_executions') + } + assert 'ix_shipping_process_executions_status_updated' in execution_indexes + assert 'ix_shipping_process_executions_current_gate' in execution_indexes + + gate_indexes = { + item['name'] for item in inspector.get_indexes('shipping_process_gates') + } + assert 'ix_shipping_process_gates_execution_status' in gate_indexes + + migration.downgrade() + inspector = sa.inspect(connection) + tables_after = set(inspector.get_table_names()) + assert 'shipping_process_executions' not in tables_after + assert 'shipping_process_gates' not in tables_after + assert 'shipping_process_gate_attempts' not in tables_after diff --git a/backend/tests/test_shipping_process_gate_models.py b/backend/tests/test_shipping_process_gate_models.py new file mode 100644 index 00000000..c9366ee7 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_models.py @@ -0,0 +1,191 @@ +""" +tests/test_shipping_process_gate_models.py + +用途:验证门禁恢复三模型的唯一约束、活动 Attempt 部分唯一索引与编号不可覆盖。 +依赖:Alembic Operations、SQLite 内存库、d0e1f2a3b4c6 迁移建表结果。 +逻辑:在最小父表桩上 upgrade 后插入 Execution/Gate/Attempt,断言重复 Execution、 + 重复幂等键与双活动 Attempt 被数据库拒绝;终态后可创建下一 Attempt。 +""" + +from __future__ import annotations + +import importlib +from datetime import datetime + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _prepare_gate_tables(monkeypatch): + """ + 创建迁移所需最小父表并执行 upgrade,返回 connection 与表对象。 + """ + migration = importlib.import_module( + 'migrations.versions.d0e1f2a3b4c6_add_shipping_process_gate_recovery', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_tasks', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_order_review_cases', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_notice_workflows', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_notice_documents', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_notice_workflow_items', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_notice_workflow_item_versions', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_audit_events', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('actor_type', sa.String(length=32), nullable=False), + sa.CheckConstraint( + "actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')", + name='ck_shipping_audit_events_actor_type', + ), + ) + metadata.create_all(engine) + connection = engine.connect() + connection.execute(sa.text('INSERT INTO shipping_notice_workflow_items (id) VALUES (1)')) + connection.execute(sa.text('INSERT INTO shipping_notice_workflow_item_versions (id) VALUES (1)')) + connection.execute(sa.text('INSERT INTO shipping_notice_workflow_item_versions (id) VALUES (2)')) + connection.commit() + + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + migration.upgrade() + + executions = sa.Table('shipping_process_executions', sa.MetaData(), autoload_with=connection) + gates = sa.Table('shipping_process_gates', sa.MetaData(), autoload_with=connection) + attempts = sa.Table('shipping_process_gate_attempts', sa.MetaData(), autoload_with=connection) + return connection, migration, executions, gates, attempts + + +def test_duplicate_execution_constraints_rejected(monkeypatch): + """重复 execution_no 与同一 version 的第二 Execution 必须被拒绝。""" + connection, _migration, executions, gates, _attempts = _prepare_gate_tables(monkeypatch) + now = datetime.utcnow() + connection.execute(executions.insert().values( + id=1, execution_no='SPE-1', workflow_item_id=1, workflow_item_version_id=1, + status='active', lock_version=1, created_at=now, updated_at=now, + )) + connection.commit() + + with pytest.raises(sa.exc.IntegrityError): + connection.execute(executions.insert().values( + id=2, execution_no='SPE-1', workflow_item_id=1, workflow_item_version_id=2, + status='active', lock_version=1, created_at=now, updated_at=now, + )) + connection.commit() + connection.rollback() + + with pytest.raises(sa.exc.IntegrityError): + connection.execute(executions.insert().values( + id=3, execution_no='SPE-2', workflow_item_id=1, workflow_item_version_id=1, + status='active', lock_version=1, created_at=now, updated_at=now, + )) + connection.commit() + connection.rollback() + + connection.execute(gates.insert().values( + id=1, execution_id=1, gate_code='inventory_source_routing', sequence_no=10, + status='blocked_retryable', evaluation_version=1, lock_version=1, + created_at=now, updated_at=now, + )) + connection.commit() + connection.close() + + +def test_active_attempt_partial_unique_and_idempotency(monkeypatch): + """同一 Gate 不能有两个 queued/running Attempt;幂等键全局唯一。""" + connection, _migration, executions, gates, attempts = _prepare_gate_tables(monkeypatch) + now = datetime.utcnow() + connection.execute(executions.insert().values( + id=1, execution_no='SPE-ACTIVE', workflow_item_id=1, workflow_item_version_id=1, + status='active', lock_version=1, created_at=now, updated_at=now, + )) + connection.execute(gates.insert().values( + id=1, execution_id=1, gate_code='inventory_source_routing', sequence_no=10, + status='blocked_retryable', evaluation_version=1, lock_version=1, + created_at=now, updated_at=now, + )) + connection.execute(attempts.insert().values( + id=1, gate_id=1, attempt_no=1, status='running', trigger_type='user_retry', + actor_type='user', actor_id='1', idempotency_key='idem-1', created_at=now, + )) + connection.commit() + + with pytest.raises(sa.exc.IntegrityError): + connection.execute(attempts.insert().values( + id=2, gate_id=1, attempt_no=2, status='queued', trigger_type='user_retry', + actor_type='user', actor_id='1', idempotency_key='idem-2', created_at=now, + )) + connection.commit() + connection.rollback() + + with pytest.raises(sa.exc.IntegrityError): + connection.execute(attempts.insert().values( + id=3, gate_id=1, attempt_no=2, status='failed', trigger_type='user_retry', + actor_type='user', actor_id='1', idempotency_key='idem-1', created_at=now, + )) + connection.commit() + connection.rollback() + connection.close() + + +def test_succeeded_attempt_allows_next_number_not_reuse(monkeypatch): + """成功 Attempt 后可创建下一编号;不得复用同一 attempt_no。""" + connection, _migration, executions, gates, attempts = _prepare_gate_tables(monkeypatch) + now = datetime.utcnow() + connection.execute(executions.insert().values( + id=1, execution_no='SPE-OK', workflow_item_id=1, workflow_item_version_id=1, + status='active', lock_version=1, created_at=now, updated_at=now, + )) + connection.execute(gates.insert().values( + id=1, execution_id=1, gate_code='task_creation', sequence_no=12, + status='passed', evaluation_version=1, lock_version=1, + created_at=now, updated_at=now, + )) + connection.execute(attempts.insert().values( + id=1, gate_id=1, attempt_no=1, status='succeeded', trigger_type='auto', + actor_type='system', idempotency_key='idem-ok-1', finished_at=now, created_at=now, + )) + connection.commit() + + connection.execute(attempts.insert().values( + id=2, gate_id=1, attempt_no=2, status='queued', trigger_type='user_retry', + actor_type='user', actor_id='9', idempotency_key='idem-ok-2', created_at=now, + )) + connection.commit() + count = connection.execute(sa.text( + 'SELECT COUNT(*) FROM shipping_process_gate_attempts WHERE gate_id = 1' + )).scalar_one() + assert count == 2 + + with pytest.raises(sa.exc.IntegrityError): + connection.execute(attempts.insert().values( + id=3, gate_id=1, attempt_no=1, status='failed', trigger_type='auto', + actor_type='system', idempotency_key='idem-ok-3', created_at=now, + )) + connection.commit() + connection.rollback() + connection.close() diff --git a/backend/tests/test_shipping_process_gate_requeue.py b/backend/tests/test_shipping_process_gate_requeue.py new file mode 100644 index 00000000..800f18bc --- /dev/null +++ b/backend/tests/test_shipping_process_gate_requeue.py @@ -0,0 +1,77 @@ +""" +tests/test_shipping_process_gate_requeue.py + +用途:验证门禁 Job 技术重试 / 外部等待轮询不会复用仍 running 的旧 Job。 +依赖:process_gate_job_service.enqueue_gate_attempt_job、jobs.queue、Flask testing app。 +逻辑:先创建 running Job 绑定 Attempt,再 force_new 入队,必须得到不同 job_id 且新 Job 为 queued。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.jobs.types import JobType +from app.models import Job +from app.services.shipping_notice.process_gate_job_service import ( + SHIPPING_PROCESS_GATE_JOB_DOMAIN, + enqueue_gate_attempt_job, +) +from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + queue_gate_attempt, +) +from tests.test_shipping_process_gate_service import _seed_workflow_version + + +def test_force_new_enqueue_does_not_reuse_running_job(app): + """ + force_new=True 时即使存在同 attempt 的 running Job,也必须新建可领取 queued Job。 + """ + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix='requeue1') + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + trigger_type='user_retry', + actor_type='system', + actor_id='requeue-worker', + idempotency_key='requeue-force-new-1', + input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}}, + ) + # [STEP] 模拟旧 Job 仍为 running(重试前未结束)。 + running = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='running', + business_ref=f'attempt:{int(attempt.id)}', + payload_json={'attempt_id': int(attempt.id)}, + progress=10, + message='running', + attempts=1, + max_attempts=3, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow(), + ) + db.session.add(running) + db.session.flush() + attempt.job_id = int(running.id) + db.session.flush() + + # 若无 force_new,默认去重可能复用 running;此处必须新建。 + new_job_id = enqueue_gate_attempt_job( + attempt_id=int(attempt.id), + delay_seconds=5, + force_new=True, + ) + assert int(new_job_id) != int(running.id) + new_job = db.session.get(Job, int(new_job_id)) + assert new_job is not None + assert new_job.status == 'queued' + assert str(new_job.business_ref or '').startswith(f'attempt:{int(attempt.id)}:r') + db.session.refresh(attempt) + assert int(attempt.job_id) == int(new_job_id) diff --git a/backend/tests/test_shipping_process_gate_service.py b/backend/tests/test_shipping_process_gate_service.py new file mode 100644 index 00000000..5742e78c --- /dev/null +++ b/backend/tests/test_shipping_process_gate_service.py @@ -0,0 +1,371 @@ +""" +tests/test_shipping_process_gate_service.py + +用途:验证统一门禁领域服务的创建、状态机、指纹跳过、下游失效与 19 Gate 接线矩阵。 +依赖:Flask testing app、process_gate_service、process_gate_bridge、process_gate_contract。 +逻辑:最小 Workflow/Item/Version 夹具上创建 Execution;对每个 Gate 覆盖 + passed / blocked_manual / failed_terminal;断言指纹未变不重跑。 +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from app import db +from app.models import ( + FileAsset, + ShippingNoticeDocument, + ShippingNoticeIntake, + ShippingNoticeWorkflow, + ShippingNoticeWorkflowItem, + ShippingNoticeWorkflowItemVersion, + ShippingProcessGate, + ShippingProcessGateAttempt, + User, +) +from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome +from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES, PROCESS_GATE_DEFINITIONS +from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + invalidate_downstream_gates, + queue_gate_attempt, + sync_gate_from_business_result, +) + + +def _seed_workflow_version(suffix: str = '001') -> tuple[Any, Any, Any]: + """ + 创建最小 User → Workflow → Item → Version 链。 + + Args: + suffix: 用于编号去重的后缀。 + + Returns: + (user, item, version) + """ + tag = str(suffix or '001')[:40] + user = User(username=f'gate-svc-{tag}', email=f'gate-svc-{tag}@example.com', password_hash='x') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no=f'FA-GATE-{tag}', + owner_user_id=int(user.id), + original_filename='gate.pdf', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{user.id}/gate-{tag}.pdf', + content_hash=(tag.ljust(64, '0'))[:64], + file_size=10, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no=f'SNI-GATE-{tag}', + asset_id=int(asset.id), + user_id=int(user.id), + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=int(intake.id), + document_type='attachment', + attachment_key='gate.pdf', + filename='gate.pdf', + classification='order_notice', + parse_status='parsed', + content_hash=(f'h{tag}'.ljust(64, '1'))[:64], + ) + db.session.add(document) + db.session.flush() + workflow = ShippingNoticeWorkflow( + workflow_no=f'WF-GATE-{tag}', + conversation_id=f'conv-gate-{tag}', + owner_user_id=int(user.id), + status='open', + current_stage='extracting', + ) + db.session.add(workflow) + db.session.flush() + item = ShippingNoticeWorkflowItem( + item_no=f'WFI-GATE-{tag}', + workflow_id=int(workflow.id), + workflow_no=workflow.workflow_no, + conversation_id=f'conv-gate-{tag}', + owner_user_id=int(user.id), + root_document_id=int(document.id), + current_document_id=int(document.id), + lifecycle_status='extracting', + current_stage='extracting', + current_version_no=1, + ) + db.session.add(item) + db.session.flush() + version = ShippingNoticeWorkflowItemVersion( + workflow_item_id=int(item.id), + item_no=item.item_no, + workflow_id=int(workflow.id), + workflow_no=workflow.workflow_no, + document_id=int(document.id), + version_no=1, + status='active', + is_current=True, + ) + db.session.add(version) + db.session.flush() + item.current_version_id = int(version.id) + db.session.flush() + return user, item, version + + +@pytest.fixture +def gate_execution(app): + """提供已初始化 19 Gate 的 Execution。""" + with app.app_context(): + _user, item, version = _seed_workflow_version() + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + actor_type='system', + actor_id='test', + ) + db.session.commit() + yield execution + + +def test_ensure_execution_creates_nineteen_gates(gate_execution): + """创建 Execution 时必须初始化全部 19 个 Gate 行。""" + gates = ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all() + assert len(gates) == 19 + assert {g.gate_code for g in gates} == set(PROCESS_GATE_CODES) + assert gate_execution.current_gate_code == 'document_materialization' + + +def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution): + """已通过且输入指纹未变的 Gate 不重跑。""" + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + + first = apply_gate_outcome( + execution=gate_execution, + gate_code='document_materialization', + passed=True, + effective_result={'stage': 'ok'}, + input_fingerprint='fp-doc-1', + idempotency_key='fp-skip-1', + ) + attempts_before = ShippingProcessGateAttempt.query.filter_by(gate_id=int(first.id)).count() + second = apply_gate_outcome( + execution=gate_execution, + gate_code='document_materialization', + passed=True, + effective_result={'stage': 'ok'}, + input_fingerprint='fp-doc-1', + idempotency_key='fp-skip-2', + ) + attempts_after = ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count() + assert second.status == 'passed' + assert attempts_after == attempts_before + + +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', + ) + apply_gate_outcome( + execution=gate_execution, + gate_code='document_materialization', + passed=True, + effective_result={'ok': True}, + force=True, + idempotency_key='doc-pass', + ) + invalidated = invalidate_downstream_gates( + execution=gate_execution, + change_type='inventory_source_changed', + ) + assert 'inventory_matching' in invalidated + assert 'document_materialization' not in invalidated + doc = ShippingProcessGate.query.filter_by( + execution_id=int(gate_execution.id), + gate_code='document_materialization', + ).first() + assert doc.status == 'passed' + + +@pytest.mark.parametrize('gate_code', [str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS]) +def test_each_gate_supports_passed_manual_blocked_and_technical_failed(app, gate_code): + """ + 19 Gate 每个至少覆盖 passed、blocked_manual、failed_terminal 三类结果。 + + 核心逻辑:同一 Execution 上对目标 Gate 依次同步三类 outcome。 + """ + with app.app_context(): + _user, item, version = _seed_workflow_version(suffix=gate_code.replace('_', '')[:32]) + execution = ensure_execution_for_workflow_version( + workflow_item_id=int(item.id), + workflow_item_version_id=int(version.id), + ) + # [STEP 1] passed + passed = sync_gate_from_business_result( + execution_no=execution.execution_no, + gate_code=gate_code, + passed=True, + effective_result_json={'findings': [], 'case': 'passed'}, + idempotency_key=f'{gate_code}:passed', + invalidate_change_type=None, + ) + assert passed.status == 'passed' + # [STEP 2] blocked_manual(允许 repass) + blocked = sync_gate_from_business_result( + execution_no=execution.execution_no, + gate_code=gate_code, + passed=False, + blocking_reason_code='gate_invalidated', + effective_result_json={'findings': [], 'case': 'blocked_manual'}, + idempotency_key=f'{gate_code}:blocked', + invalidate_change_type=None, + ) + assert blocked.status == 'blocked_manual' + # [STEP 3] failed_terminal via complete path after queue + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code=gate_code, + trigger_type='system_requeue', + actor_type='system', + actor_id='test', + idempotency_key=f'{gate_code}:terminal', + ) + from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running + + mark_attempt_running(attempt_id=int(attempt.id), worker_id='test') + terminal = complete_gate_attempt( + attempt_id=int(attempt.id), + outcome='failed_terminal', + error_code='TECH', + error_summary='technical failed', + effective_result_json={'case': 'failed_terminal'}, + ) + assert terminal.status == 'failed_terminal' + + +def test_idempotent_queue_replays_same_attempt(gate_execution): + """相同幂等键只产生一个 Attempt。""" + first = queue_gate_attempt( + execution_no=gate_execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='same-key-ten-times', + input_snapshot={'action_code': 'retry_with_latest_rules'}, + ) + for _ in range(9): + again = queue_gate_attempt( + execution_no=gate_execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='same-key-ten-times', + input_snapshot={'action_code': 'retry_with_latest_rules'}, + ) + assert int(again.id) == int(first.id) + count = ShippingProcessGateAttempt.query.filter_by(idempotency_key='same-key-ten-times').count() + assert count == 1 + + +def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app): + """同幂等键跨 Gate / 跨 action 必须 409,禁止复用其他上下文 Attempt。""" + from app.core.errors import ConflictError + + first = queue_gate_attempt( + execution_no=gate_execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='cross-context-key', + input_snapshot={'action_code': 'retry_with_latest_rules'}, + ) + with pytest.raises(ConflictError) as gate_exc: + queue_gate_attempt( + execution_no=gate_execution.execution_no, + gate_code='order_extraction', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='cross-context-key', + input_snapshot={'action_code': 'retry_with_latest_rules'}, + ) + assert gate_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT' + + with pytest.raises(ConflictError) as action_exc: + queue_gate_attempt( + execution_no=gate_execution.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='cross-context-key', + input_snapshot={'action_code': 'open_order_review'}, + ) + assert action_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT' + assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').count() == 1 + assert int(first.id) == int( + ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').first().id + ) + + +def test_idempotent_key_conflicts_across_execution(app): + """同幂等键跨 Execution 必须冲突。""" + from app.core.errors import ConflictError + + with app.app_context(): + _u1, item1, ver1 = _seed_workflow_version(suffix='idem-a') + _u2, item2, ver2 = _seed_workflow_version(suffix='idem-b') + exe1 = ensure_execution_for_workflow_version( + workflow_item_id=int(item1.id), + workflow_item_version_id=int(ver1.id), + actor_type='system', + actor_id='test', + ) + exe2 = ensure_execution_for_workflow_version( + workflow_item_id=int(item2.id), + workflow_item_version_id=int(ver2.id), + actor_type='system', + actor_id='test', + ) + db.session.commit() + queue_gate_attempt( + execution_no=exe1.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='cross-execution-key', + input_snapshot={'action_code': 'retry_with_latest_rules'}, + ) + with pytest.raises(ConflictError) as exc: + queue_gate_attempt( + execution_no=exe2.execution_no, + gate_code='layout_parsing', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='cross-execution-key', + input_snapshot={'action_code': 'retry_with_latest_rules'}, + ) + assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT' diff --git a/docker-compose.yml b/docker-compose.yml index f301402a..7d227c53 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -147,6 +147,11 @@ services: - SHIPPING_NOTICE_WORKER_POLL_SECONDS=${SHIPPING_NOTICE_WORKER_POLL_SECONDS:-2} - SHIPPING_NOTICE_WORKER_CONCURRENCY=${SHIPPING_NOTICE_WORKER_CONCURRENCY:-2} - SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=${SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS:-420} + - SHIPPING_PROCESS_GATE_LEASE_SECONDS=${SHIPPING_PROCESS_GATE_LEASE_SECONDS:-60} + - SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS=${SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS:-15} + - SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=${SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS:-120} + - SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=${SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES:-3} + - SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=${SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS:-30} extra_hosts: - "host.docker.internal:host-gateway" volumes: diff --git a/docs/features/shipping-notice/README.md b/docs/features/shipping-notice/README.md index 9d0255fa..dbe0f8c7 100644 --- a/docs/features/shipping-notice/README.md +++ b/docs/features/shipping-notice/README.md @@ -6,6 +6,7 @@ | **业务说明** | 货代、跟单 | [business.md](business.md) | | **字段资产治理方案(本轮)** | 产品、研发、测试 | [field-governance-plan.md](field-governance-plan.md) | | **库存源路由方案** | 研发 | [inventory_source_plan.md](inventory_source_plan.md) | +| **全门禁中断恢复契约(Phase 1)** | 研发、测试 | [process-gate-recovery-contract.md](process-gate-recovery-contract.md) | | **客户识别规则改造方案** | 研发、产品、测试 | [customer_identity_rules_plan.md](customer_identity_rules_plan.md) | | **产品原型** | 产品、测试 | [../../prototype/shipping_notice_agent_prototype.md](../../prototype/shipping_notice_agent_prototype.md) | | **OpenAPI** | Dify 导入 | [../../openapi/shipping_notice_tools.dify.json](../../openapi/shipping_notice_tools.dify.json) | diff --git a/docs/features/shipping-notice/process-gate-recovery-acceptance.md b/docs/features/shipping-notice/process-gate-recovery-acceptance.md new file mode 100644 index 00000000..39a4ea83 --- /dev/null +++ b/docs/features/shipping-notice/process-gate-recovery-acceptance.md @@ -0,0 +1,101 @@ +# 货代发货通知 — 全门禁中断恢复阶段验收报告 + +> **基线日期**:2026-08-01(第三次评审修复后) +> **契约**:[`process-gate-recovery-contract.md`](./process-gate-recovery-contract.md) +> **技术手册**:[`technical.md`](./technical.md) + +--- + +## 1. 阶段合规结论(以当前工作树实测为准) + +| 阶段 | 目标 | 结论 | +| --- | --- | --- | +| Phase 1.5 | Finding / 字段阻断 / 原因唯一归属 / 旧五门禁收敛 | **通过** | +| Phase 2 | Execution/Gate/Attempt 模型与迁移 | **通过**(定向测) | +| Phase 3 | 统一领域服务 + 业务接线(含履约 13–19) | **通过**(定向测) | +| Phase 4 | Job、租约、运行中心跳、Worker 接管、真实异步执行器 | **通过**(定向测) | +| Phase 5 | Workspace/Admin API、权限、幂等冲突、异常脱敏 | **通过**(定向测) | +| Phase 6 | Chat / 复核台 / 任务中心统一恢复卡片;Gate 阻断时旧 `action_buttons` 清零 | **代码通过**;实机阻断卡需 Execution 数据 | +| Phase 7 | 故障注入、环境变量、healthcheck、验收证据 | **部分通过**(缺生产双 Worker 演练签字) | + +**发布边界**:核心代码须已纳入 Git(见提交);**人工实机 / 生产演练未签前,仍不得宣称生产可发布闭环。** Phase 7 与「上线前 28 条」人工项未全部签署,正式发布仍阻断。 + +仍待人工签署: + +- 生产双 Worker 强杀现场演练 +- Dify 平台配置确认 +- 管理端 768px 实机截图 +- 真实「唯一当前阻断 + 主恢复动作 + 409 刷新」视觉验收 + +--- + +## 2. 针对最新评审缺陷的修复摘要 + +| 优先级 | 问题 | 修复 | +| --- | --- | --- | +| P0 | 核心交付文件未跟踪 | 纳入 Git(模型/迁移/服务/API/Worker/前端/测试/文档) | +| P0 | Phase 7 未闭环 | 本报告保持「部分通过」;不虚构签署 | +| P1 | 旧 `action_buttons` 与 Gate 双真相 | `build_task_ui_state` 在 blocking Gate 时清空 `action_buttons`;TaskTodoPanel 兜底隐藏 | +| P1 | 异常摘要未脱敏 | `process_gate_error_sanitizer` + executor/service/projection | +| P1 | Admin 诊断筛选不足 | 支持 Gate/原因/责任方/时间/搜索;Attempt Diff + 审计中心入口 | +| P2 | 诊断页原始 JSON | Findings/阻断原因结构化卡片 | +| P2 | funclist 与验收矛盾 | funclist 改为 Phase 7 部分完成表述 | + +--- + +## 3. 关键交付物与实测 + +### 领域与接线 + +- `process_gate_*` 服务族(含幂等校验、脱敏、授权只读) +- 迁移 head:`d0e1f2a3b4c6_add_shipping_process_gate_recovery` +- Gate 阻断时 `ui_state.action_buttons = []` + +### API / 前端 + +- Workspace / Admin process-execution 路由(Admin 多维筛选) +- `features/shipping-process-gates/*` + Admin 诊断页 +- 四语言错误码与诊断文案 + +### 测试(2026-08-01 本机工作树实测) + +| 套件 | 结果 | +| --- | --- | +| `pytest` `test_shipping_process_gate_*.py` + `test_shipping_process_gate_error_sanitizer.py` | **49 passed** | +| `vitest` `shipping-process-gates` + `shippingConfigNavigation.spec.ts` | **6 passed** | +| `vue-tsc --noEmit` | **通过** | + +--- + +## 4. 部署影响面(Phase 7) + +已变更: + +- `.env.shared` / `docker-compose.yml`:`SHIPPING_PROCESS_GATE_*` +- `scripts/healthcheck.sh`:shipping-worker 运行 + 门禁表 + handler 注册 + +**上线前必须**: + +1. 各环境 Alembic upgrade(门禁三表 + audit `actor_type` CHECK) +2. `deploy_compose` 健康检查通过 +3. 数据库备份后发布 +4. 人工完成 §1 待签署项 + +--- + +## 5. Dify 配置说明(人工) + +本方案**不**要求 Agent 修改 Dify。请人工确认: + +1. 输出仍符合当前动态 Schema / Observation 契约 +2. 不新增绕过 HXOPS Gate 的并行「下一节点」字段 +3. 可选字段证据不足不得在 Dify 侧被标成流程硬失败 + +--- + +## 6. 签署 + +| 角色 | 结果 | 日期 | +| --- | --- | --- | +| 实现(Agent) | 代码阻断项已修复;定向 pytest **49 passed**;vue-tsc 通过;Phase 7 人工项未签 | 2026-08-01 | +| 人工 QA / 生产演练 | 待签署 | — | diff --git a/docs/features/shipping-notice/process-gate-recovery-contract.md b/docs/features/shipping-notice/process-gate-recovery-contract.md new file mode 100644 index 00000000..9e740bed --- /dev/null +++ b/docs/features/shipping-notice/process-gate-recovery-contract.md @@ -0,0 +1,266 @@ +# 货代发货通知 — 全门禁中断恢复契约(Phase 1) + +> **权威契约文档**:冻结 19 个业务门禁编码、状态、恢复动作、失效规则、权限与客户端 API 边界。 +> **代码真相源**:`backend/app/services/shipping_notice/process_gate_contract.py`、`process_gate_dependency.py`、`progress_audit_contract.py`(`PROCESS_GATE_AUDIT_EVENT_TYPES`)。 +> **运行时 / 部署 / Dify**:仍以 [technical.md](./technical.md) 为准;本文件不替代技术手册。 +> **阶段说明**:Phase 0(库存源路由独立重算)已闭环,见 technical.md「门禁恢复阶段 0」。**Phase 1 仅冻结契约**,不接线持久化模型、统一 API 或 Worker 租约。 + +契约版本:`shipping-process-gate-v1` + +--- + +## 1. 范围与阶段边界 + +| 阶段 | 内容 | 状态 | +| --- | --- | --- | +| Phase 0 | 库存源路由门禁纵向闭环(不重识别 PDF;人工决定优先;幂等与审计) | **已关闭** | +| Phase 1 | 全部门禁 / 状态 / 动作 / 失效图 / 权限 / TS 类型与文档对齐 | **契约冻结(本文)** | +| Phase 1.5 | Finding 严重级别、原因唯一归属、字段阻断资格、旧五门禁收敛 | **已完成(本文 §8)** | +| Phase 2 | Execution/Gate/Attempt 模型与迁移 | **已完成(接线前复核)** | +| Phase 3 | 统一领域服务接线(含履约 13–19 Gate 同步) | **已完成** | +| Phase 4 | Job、租约、运行中心跳、Worker 接管、真实异步执行器 | **已完成** | +| Phase 5 | 统一 Workspace/Admin API、权限与错误码 | **已完成** | +| Phase 6 | Chat / 复核台 / 任务中心统一恢复卡片与导航动作 | **已完成** | +| Phase 7 | 故障注入、环境变量、healthcheck、验收报告 | **部分完成(缺生产演练签字)** | +| 后续 | 生产双 Worker 演练、Dify 人工配置确认 | **待签署** | + +最终目标:某一门禁失败时只恢复该门禁,复用输入未变化的上游结果,精确失效受影响下游,并从最近合法检查点继续推进。 + +--- + +## 2. 十九个业务门禁 + +| 顺序 | `gate_code` | 业务标签 | 主要恢复动作(按阻断状态) | +| ---: | --- | --- | --- | +| 1 | `document_materialization` | 文档和附件可用性 | `rematerialize_document` | +| 2 | `layout_parsing` | PDF 版面解析 | `retry_layout_parsing` | +| 3 | `document_profile_routing` | Profile/模板路由 | `reroute_document_profile` / `open_profile_review` | +| 4 | `order_field_extraction` | 订单字段抽取 | `retry_order_extraction` / `open_order_review` | +| 5 | `field_completeness` | 必填字段完整性 | `edit_order_fields` | +| 6 | `reservation_validation` | Reservation 格式和证据 | `revalidate_reservation` / `edit_reservation` | +| 7 | `customer_resolution` | 客户身份识别 | `retry_customer_resolution` / `confirm_customer` | +| 8 | `duplicate_detection` | 重复订单/修订判断 | `retry_duplicate_detection` / `adjudicate_duplicate` | +| 9 | `field_conflict_resolution` | 字段冲突 | `resolve_field_conflicts` | +| 10 | `inventory_source_routing` | 库存源路由 | `retry_with_latest_rules` / `open_inventory_source_review` | +| 11 | `order_freeze_readiness` | 订单冻结资格 | `recheck_freeze_readiness` / `open_order_review` | +| 12 | `task_creation` | ShippingTask 创建 | `retry_task_creation` | +| 13 | `inventory_preparation` | 库存文件或快照准备 | `retry_inventory_preparation` / `poll_inventory_preparation` / `upload_inventory_file` | +| 14 | `inventory_field_mapping` | 库存字段映射 | `retry_inventory_field_mapping` / `confirm_inventory_field_mapping` | +| 15 | `inventory_matching` | Reservation + 料号匹配 | `retry_inventory_matching` / `open_inventory_match_review` | +| 16 | `inventory_sufficiency` | 库存满足性 | `recheck_inventory_sufficiency` / `open_shortage_review` | +| 17 | `excel_readiness` | Excel 生成资格 | `recheck_excel_readiness` | +| 18 | `artifact_generation` | Excel Artifact | `regenerate_excel_artifact` | +| 19 | `manual_upload_handoff` | 人工上传交接 | `regenerate_manual_upload_todo` | + +规则: + +- 每个 `gate_code` 全局唯一,`sequence_no` 连续 1..19。 +- 每种 Gate 状态最多一个主要 `next_action`;前端禁止本地推导动作码。 +- 库存源路由额外动作:`adopt_rule_suggestion`、`keep_manual_inventory_decision`(人工决定语义,Phase 0 已落地)。 + +--- + +## 3. 状态枚举 + +### 3.1 Gate 状态(`ShippingProcessGateStatus`) + +```text +pending +queued +running +passed +blocked_retryable +blocked_manual +waiting_external +failed_terminal +invalidated +skipped +``` + +| 子集 | 成员 | +| --- | --- | +| 终态 | `passed`、`failed_terminal`、`skipped` | +| 可恢复 | `blocked_retryable`、`blocked_manual`、`waiting_external`、`invalidated`、`failed_terminal` | + +### 3.2 Execution 状态 + +```text +active | blocked | waiting_external | completed | cancelled | failed +``` + +### 3.3 Attempt 状态 + +```text +queued | running | succeeded | failed | cancelled | superseded +``` + +### 3.4 责任方(`ShippingProcessGateResponsibleParty`) + +```text +system | worker | owner | admin | external +``` + +### 3.5 触发类型 + +```text +auto | user_retry | user_manual | worker_takeover | upstream_invalidation | system_requeue +``` + +--- + +## 4. 动作码(`ShippingProcessGateActionCode`) + +完整集合与 Python `PROCESS_GATE_ACTION_CODES` 对齐,包括但不限于: + +`rematerialize_document`、`retry_layout_parsing`、`reroute_document_profile`、`open_profile_review`、`retry_order_extraction`、`open_order_review`、`edit_order_fields`、`revalidate_reservation`、`edit_reservation`、`retry_customer_resolution`、`confirm_customer`、`retry_duplicate_detection`、`adjudicate_duplicate`、`resolve_field_conflicts`、`retry_with_latest_rules`、`open_inventory_source_review`、`adopt_rule_suggestion`、`keep_manual_inventory_decision`、`recheck_freeze_readiness`、`retry_task_creation`、`retry_inventory_preparation`、`poll_inventory_preparation`、`upload_inventory_file`、`retry_inventory_field_mapping`、`confirm_inventory_field_mapping`、`retry_inventory_matching`、`open_inventory_match_review`、`recheck_inventory_sufficiency`、`open_shortage_review`、`recheck_excel_readiness`、`regenerate_excel_artifact`、`regenerate_manual_upload_todo`。 + +客户端恢复请求只允许提交服务端下发的 `action_code`(外加 `expected_gate_version` 与 `idempotency_key`)。 + +--- + +## 5. 状态边界 + +```text +ShippingProcessExecution / Gate / Attempt + = 业务状态真相(门禁是否通过、阻断原因、下一动作、输入指纹) + +Job + = 调度状态真相(排队、领取、重试、超时回收) + +WorkflowItem + = 用户业务台账与聚合进度(列表/时间线/待办投影) + +ShippingTask + = 冻结订单及履约实体(建单后事实) +``` + +禁止事项: + +- 不得用 `Job.status`、`step_payload_json` 或前端本地推导作为门禁恢复真相。 +- 不得引入 Temporal、Celery、Kafka 或新的工作流平台;继续复用现有 PostgreSQL Job + Shipping Worker。 + +--- + +## 6. 下游失效规则 + +上游输入变化时,必须精确失效依赖下游(不含变化源自身)。代码源:`PROCESS_GATE_INVALIDATION_RULES`。 + +| 变化类型(`change_type`) | 必须失效的下游门禁 | +| --- | --- | +| `pdf_or_extraction_changed` | `field_completeness` → … → `manual_upload_handoff`(字段完整性及之后全部履约门禁) | +| `reservation_changed` | `duplicate_detection`、`order_freeze_readiness`、`inventory_matching`、`inventory_sufficiency`、`excel_readiness`、`artifact_generation`、`manual_upload_handoff` | +| `part_number_changed` | `order_freeze_readiness`、`inventory_matching`、`inventory_sufficiency`、`excel_readiness`、`artifact_generation`、`manual_upload_handoff` | +| `quantity_changed` | 同 `part_number_changed` | +| `customer_changed` | `duplicate_detection`、`order_freeze_readiness`、`task_creation` 及全部库存/Excel/上传门禁 | +| `inventory_source_changed` | `inventory_preparation` → `manual_upload_handoff` | +| `inventory_file_changed` | `inventory_field_mapping` → `manual_upload_handoff` | +| `inventory_field_mapping_changed` | `inventory_matching` → `manual_upload_handoff` | +| `excel_regeneration_only` | 仅 `artifact_generation`、`manual_upload_handoff`(**不得**失效 `inventory_matching`) | + +旧 Artifact 不删除,标记为 `superseded`。前端禁止自行决定失效范围。 + +--- + +## 7. 客户端 API 约束(Phase 5 已接线) + +目标接口形态(实际前缀为 `/api/workspace/shipping-notice/...`): + +```http +GET /api/workspace/shipping-notice/process-executions/{execution_no} +GET /api/workspace/shipping-notice/process-executions/{execution_no}/gates +POST /api/workspace/shipping-notice/process-executions/{execution_no}/gates/{gate_code}/actions +GET /api/workspace/shipping-notice/process-executions/{execution_no}/audit-events +``` + +管理员诊断(`/api/admin/shipping-notice/process-executions...`)见 `backend/app/api/admin/shipping_process_gate.py`。 + +允许提交:`action_code`、`expected_gate_version`、`idempotency_key`(及动作所需的受控业务字段,如人工选择库存源)。 + +**客户端禁止提交:** + +- 起始阶段 / 起始门禁(`start_stage` / `start_gate`) +- 目标状态(`target_status`) +- Worker 名称或 Worker 实例标识 +- Python 工具名 / 内部 service 名 +- 任意下一节点或 DAG 跳转 +- 规则 SQL、表达式或未发布规则正文 + +403 / 409 均不得产生业务副作用;相同幂等键返回首次结果。 + +--- + +## 8. Finding 契约与原因唯一归属(Phase 1.5) + +### 8.1 Finding 标准结构 + +```json +{ + "finding_code": "optional_field_evidence_missing", + "owning_gate_code": "order_field_extraction", + "severity": "diagnostic", + "field_code": "ship_to_address", + "decision_id": 123, + "reason_code": "evidence_missing", + "user_visible": false, + "blocks_current_action": false +} +``` + +| 字段 | 规则 | +| --- | --- | +| `severity` | `blocking` 才可改变 Gate 状态;`diagnostic` 仅管理员诊断 | +| `owning_gate_code` | 必须属于 19 门禁之一;同一根因禁止多门禁平行用户阻断 | +| `user_visible` / `blocks_current_action` | 缺省由 severity 推导 | + +### 8.2 字段阻断资格 + +仅当 `required=true` **或** `auto_create_key_field=true` 时,字段质量问题可进入 `blocked_fields`。 +可选非关键字段(如 `ship_to_address`)证据不足 → diagnostic Finding,`blocked_fields=[]`。 + +### 8.3 原因唯一归属矩阵(摘录) + +完整矩阵见 `PROCESS_GATE_REASON_OWNING_GATE`。关键归属: + +| 原因 | owning_gate | +| --- | --- | +| Profile 未匹配 / 歧义 / 漂移 | `document_profile_routing` | +| 字段抽取技术失败 / 证据不足 | `order_field_extraction` | +| 必填字段缺失 | `field_completeness` | +| 客户未识别或不唯一 | `customer_resolution` | +| 自动冻结资格 / 客户范围 / 场景 / 紧急停止 | `order_freeze_readiness` | +| 无有效库存源 | `inventory_source_routing` | + +旧自动建单五门禁键经 `AUTO_BUILD_LEGACY_GATE_OWNING_MAP` 映射;用户端同一时间对自动冻结最多显示一次「自动建单策略尚未放行」。 + +--- + +## 9. 权限矩阵 + +| 主体 | 查看 | 恢复(retry / regenerate) | 人工决定(采用/保留/覆盖) | 审计详情 | +| --- | ---: | ---: | ---: | ---: | +| 任务所有者(owner) | 是 | 是 | 是 | 是 | +| 管理员(admin) | 是 | 是 | 是 | 是 | +| 其他授权人员 | 是 | 否(除非另行授权) | 否(除非另行授权) | 按权限 | +| Worker | 是(系统读) | 自动执行(非用户动作) | 否 | 写系统事件 | +| 未授权用户 | 否 | 否 | 否 | 否 | + +默认:非所有者只读;权限拒绝也写 `process_gate_permission_denied` 审计。 + +--- + +## 10. 审计事件与快照键 + +事件集合:`PROCESS_GATE_AUDIT_EVENT_TYPES`(含 `process_execution_created`、`process_gate_*` 等 16 项)。 + +快照白名单新增键:`gate_code`、`attempt_no`、`execution_no`、`next_action_code`、`blocking_reason_code`、`input_fingerprint`、`responsible_party`。禁止写入正文、规则 SQL、对象存储 URL、凭据。 + +--- + +## 11. 相关文档 + +- 技术手册(运行时 / Phase 0 库存路由恢复):[technical.md](./technical.md) +- 业务说明:[business.md](./business.md) +- 需求总览:`docs/demand.md` +- 技术架构:`docs/tec.md` +- 功能清单:`docs/funclist.md` +- 测试矩阵:`docs/test_plan_matrix.md` diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 782d419e..819b3a6c 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -215,6 +215,12 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格 **目标**:不新增第二套模板库或复核工作台,在现有对话、任务中心、复核工作台、模板模块和审计中心中承载新能力。 +**复核重识别闭环(2026-07-31)**:重新识别不建立独立进度模型,前端按既有 WorkflowItem 的 `layout_parsing / extracting / pending_review / reparse_failed` 权威状态轮询;仅展示不确定阶段,不根据耗时伪造百分比。新版 `current_run_no + current_case_no` 形成后自动加载,手工“跳转当前版本”也必须先刷新 Item。坐标模板路由中,`line_layouts` 是物理子布局描述而非必需消费行数;只有模板明确 `allow_cross_page=true` 的固定子行模式才能暂存跨页 carry,完整自适应订单行不得因此被丢弃。成功模板匹配必须把 Profile 身份传给 Route Decision,保证“实际使用”审计可追溯。 + +**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。 + +**`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。 + 验收标准:四语言文案完整;前端 `npm run build` 通过;业务按钮只消费后端允许动作;对象版本冲突可见;普通用户无法进入模板治理或全局审计;页面不展示虚假百分比或内部 Workflow/Job/Provider 细节。 ### 6. 核心页面位置与框线原型 @@ -1650,12 +1656,9 @@ SHIPPING_NOTICE_CHAT_DIFY_API_KEY= SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 ``` -### 1.3 注册 Agent 记录 +### 1.3 配置 Agent 记录 -```bash -cd backend -python seed_shipping_notice_agents.py -``` +货代发货通知 Agent 由管理端手工创建和维护。配置完成后填写本节的 Dify Chatflow 环境变量;不使用种子脚本写入或覆盖 Agent 记录。 ### 1.4 Mock RPA(开发) @@ -2427,6 +2430,43 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - `order_build_eligibility_service` 在 Draft 校验与确认前投影行级候选;人工选择须填写原因且库存源已启用。 - API:`PUT .../order-review-cases/{case_no}/draft/lines/{line_key}/inventory-candidates`;Draft 投影含 `build_eligibility`。 +### 门禁恢复阶段 0:库存源路由独立重算(2026-07-31) + +- **目标**:在不重新识别 PDF 的前提下,按最新已发布路由规则与最新库存源启停/解析 Profile 状态重算建单前库存源候选(典型:`DBS SIN` 线索命中已停用源后的恢复)。 +- **投影分层**: + - `raw_rule_source_codes`:规则原始候选; + - `unavailable_source_codes`:停用、不存在或无已发布解析 Profile 的源; + - `candidate_inventory_source_codes`:当前有效结果; + - `rule_suggestion*`:最新规则建议(含 `rule_versions` / `matched_rules`)。 +- **人工决定优先级**: + - 人工指定结果优先于自动规则结果; + - `POST .../draft/inventory-routing/reroute` 只生成/刷新建议,不静默覆盖人工决定; + - 用户显式 `adopt-suggestion` 后才替换有效结果; + - `keep-manual` 明确保留人工值并清除 `suggestion_pending`; + - 无人工决定且规则唯一可用命中时,建议直接成为有效结果。 +- **API**: + - `POST .../draft/inventory-routing/reroute`(可选 `line_key`、`idempotency_key`) + - `POST .../draft/lines/{line_key}/inventory-routing/adopt-suggestion` + - `POST .../draft/lines/{line_key}/inventory-routing/keep-manual` +- **审计**:`inventory_routing_*` 事件写入操作人、规则版本、前后候选与幂等键;同一幂等键只产生一次有效副作用;409 版本冲突不执行副作用。 +- **前端**:复核台 `ReviewInventoryCandidatesPanel` 提供「重新匹配路由 / 采用规则结果 / 保留人工结果」。 + +### 门禁恢复阶段 1:契约冻结(2026-07-31) + +- **范围**:冻结 19 个业务门禁编码、状态、恢复动作、责任方、依赖失效图、审计事件与快照键;前后端类型对齐。 +- **代码源**:`process_gate_contract.py`、`process_gate_dependency.py`、`progress_audit_contract.PROCESS_GATE_AUDIT_EVENT_TYPES`、前端 `ShippingProcessGate*` 联合类型。 +- **权威契约**:[process-gate-recovery-contract.md](./process-gate-recovery-contract.md)。 +- **非范围**:本阶段不接线 Execution/Gate/Attempt 持久化、统一恢复 API、Worker 租约或页面改造(后续阶段)。 + +### 门禁恢复阶段 1.5:语义统一与错误阻断修复(2026-08-01) + +- **目标**:在 Phase 3 接线前修正阻断真相,防止错误状态写入 Execution/Gate/Attempt。 +- **字段阻断资格**:仅 `required=true` 或 `auto_create_key_field=true` 可因字段质量进入 `blocked_fields`;可选非关键字段证据不足只生成 `severity=diagnostic` Finding。 +- **Candidate 冲突**:只投影最终 `blocked_fields` 对应 Decision;派生成功后的 `line_no` 不得再带出派生前 `evidence_missing`。 +- **原因唯一归属**:`PROCESS_GATE_REASON_OWNING_GATE`;自动冻结资格/客户范围/场景/紧急停止统一归属 `order_freeze_readiness`。 +- **旧五门禁**:内部仍评估 `can_auto_create`,但禁止 `auto_build_gate_*` 平行用户阻断;用户可见最多一条「自动建单策略尚未放行」。 +- **投影**:`process_gate_projection` 分离用户安全投影与管理员诊断投影;`ui_state` / Workflow 提示优先消费统一 Gate 摘要。 + ### STP 阶段 3:自动建单与复核工作台(2026-07-30) - 抽取收尾 `maybe_stp_auto_create_for_run`:无人工改脏且资格 ready 时幂等自动建单并 `auto_progress`。 @@ -2616,7 +2656,6 @@ API 层 - `frontend/src/features/chat/shipping/*` — 聊天上传、会话摘要与订单抽取通知 - `frontend/src/features/workspace/shipping-task-center/*` — 我的待办与任务处理工作台 -- `backend/seed_shipping_notice_agents.py` — Agent 注册 - `backend/scripts/export_shipping_notice_openapi.py` — OpenAPI 导出 - `docs/features/shipping-notice/technical.md` — 手动配置主文档 @@ -2635,7 +2674,6 @@ API 层 | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | | `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | -| `seed_shipping_notice_agents.py` | Agent 注册脚本 | --- diff --git a/docs/funclist.md b/docs/funclist.md index 81e8fc77..96f86e63 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -74,12 +74,13 @@ | Workflow 阶段 0–2 底座与投影 | 已实现 | 删除 session work items;Workflow/Item/Version/Event;进度投影与会话轮询;见 `workflow-stage0-acceptance.md` 与 technical.md | | Workflow 阶段 3 确认后自动进度 | 已实现 | 五门禁(批准模板/字段完整/证据/冲突重复/质量)失败仅 Review Case;确认返回 `workflow_id`/`workflow_item_id` 并推进 `building_order→…→manual_upload_pending`;复核页 `ReviewWorkflowProgressPanel` 轮询;建单后取消 Task `pending_void`+Excel 只读;移除工作台 upload-inventory/mark-manual-uploaded/retry-upload 写入口 | | Workflow 阶段 4 任务中心与审计闭环 | 已实现 | 任务中心进行中 2s/8s 自动刷新;时间线合并 Workflow Event;审计关联链/敏感读权限/哈希日检;删除复核监管台 | -| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,PDF 数量保持权威,歧义统一进入人工复核 | +| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,支持 `External reservation ID` 等冻结 Schema 显式别名;每个 Run 从原始 HTML 重建,避免旧的部分解析结果遮蔽新规则;PDF 数量保持权威,歧义统一进入人工复核 | | PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 | | 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理;只读画布完整展示必需锚点及各受控标签区域的冻结识别值,必需锚点可对照配置值、识别值和匹配状态;标注取字、运行匹配与版本诊断统一按视觉行恢复字符阅读顺序 | | 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;盲测工作台支持独立样本复核、执行与批准,同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,重复上传按内容和表身份收敛,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 | -| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。 | -| **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 Task 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。**阶段 0–5 已落地**:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。**项次派生 Phase 0–4**:`line_no`=内部项次、`export_sequence`=导出行号、Schema 派生模拟、运行时派生审计、复核覆盖锁定与 `field_meta` 投影、冻结血缘。首期不触发货代 RPA 上传、不改 Dify | +| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 | +| **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 Task 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。**阶段 0–5 已落地**:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。**项次派生 Phase 0–4**:`line_no`=内部项次、`export_sequence`=导出行号、Schema 派生模拟、运行时派生审计、复核覆盖锁定与 `field_meta` 投影、冻结血缘。**库存源路由独立恢复(门禁恢复阶段 0)**:复核台可按最新已发布规则与库存源启停重算路由(不重识别 PDF);人工决定优先且不被静默覆盖;支持采用规则建议 / 保留人工结果;幂等键与审计前后快照齐全。首期不触发货代 RPA 上传、不改 Dify | +| **全门禁级中断恢复(契约冻结)** | 已实现(Phase 1.5–6 自动化;Phase 7 部分) | **代码与定向自动化已落地**:库存源路由独立恢复;契约/模型/迁移;Finding 语义;领域服务与业务接线;Job 租约/心跳/Worker;Workspace/Admin API;Chat/复核台/任务中心恢复卡片;Admin 诊断筛选与 Attempt Diff;Gate 阻断时旧 `action_buttons` 清零;异常摘要脱敏。权威契约:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md);验收:[process-gate-recovery-acceptance.md](features/shipping-notice/process-gate-recovery-acceptance.md)。**Phase 7 未闭环**:生产双 Worker 强杀演练、真实 Execution E2E/阻断卡视觉、人工 QA 签署。不引入 Temporal/Celery。 | | **订单项次派生与血缘审计** | 已实现(Phase 0–4 + 评审纠偏) | 统一 `customer_po_line_no` / `line_no` / `export_sequence`;Schema 派生模拟支持历史 Extraction 样本;运行时派生含 `evidence_refs`;复核覆盖/恢复(`LINE_NO_OVERRIDDEN`/`LINE_NO_RESTORED`);货代统一审计新写入永久保留(`6a9c3e5f7b2d`) | | 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 | | Run 自动冻结门禁与执行 | 已实现 | Run 创建时冻结 `manual_confirmation` 初始策略;结果落库后按模板资格、已确认 Bill-to 客户、业务场景、技术失败、预算停止和待处理订单刷新 `auto_freeze_policy_json`。仅资格与全部门禁显式放行时,自动消费当前 Run 的 accepted Candidate 并冻结新建 Task;不触发库存、Excel 或上传履约副作用。 | diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index 9369c2fb..17ad2d19 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -59,6 +59,8 @@ const ShippingOrderExtractionRunsPage = () => import("@/features/admin/modules/shipping-order-extraction-runs/ShippingOrderExtractionRunsPage.vue"); const ShippingAuditCenterPage = () => import("@/features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue"); +const ShippingProcessGateDiagnosticsPage = () => + import("@/features/admin/modules/shipping-process-gates/ShippingProcessGateDiagnosticsPage.vue"); const ShippingOrderDocumentProfilesPage = () => import("@/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue"); const OrderProfileVersionDetailPage = () => @@ -207,6 +209,12 @@ export const adminRoutes: RouteRecordRaw[] = [ component: ShippingAuditCenterPage, meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'shipping_audit', title: "运行与审计" }, }, + { + path: "shipping-process-gates", + name: "AdminShippingProcessGates", + component: ShippingProcessGateDiagnosticsPage, + meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'process_gates', title: "门禁诊断" }, + }, { path: "shipping-order-document-profiles", name: "AdminShippingOrderDocumentProfiles", diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue index c960358c..9e0e797a 100644 --- a/frontend/src/features/admin/components/AdminNav.vue +++ b/frontend/src/features/admin/components/AdminNav.vue @@ -2,7 +2,8 @@ * features/admin/components/AdminNav.vue * 管理后台左侧导航,在模块原始顺序中渲染货代手风琴、企微和报表二级菜单。 * 依赖:admin-nav.store、modules 常量、vue-router。 - * 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开以便看到激活项。 + * 逻辑:报表/企微子菜单默认折叠;当前路由落在对应模块时自动展开; + * lg 起固定宽度侧栏,小屏横向滚动导航以免挤占主内容。 */ + + diff --git a/frontend/src/features/admin/shippingConfigNavigation.spec.ts b/frontend/src/features/admin/shippingConfigNavigation.spec.ts index 89924532..7f985e4e 100644 --- a/frontend/src/features/admin/shippingConfigNavigation.spec.ts +++ b/frontend/src/features/admin/shippingConfigNavigation.spec.ts @@ -17,6 +17,7 @@ const shippingRoutes = adminRoutes[0].children?.filter((route) => || route.name === 'AdminShippingIdentityRules' || route.name === 'AdminShippingOrderExtractionRuns' || route.name === 'AdminShippingAudit' + || route.name === 'AdminShippingProcessGates' || route.name === 'AdminShippingOrderDocumentProfiles', ) ?? []; @@ -46,10 +47,11 @@ describe('shipping configuration navigation contract', () => { { id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } }, { id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } }, { id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' }, + { id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' }, { id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } }, { id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } }, ]); - expect(shippingRoutes).toHaveLength(7); + expect(shippingRoutes).toHaveLength(8); expect(shippingRoutes.some((route) => route.name === 'AdminShippingReviewSupervision')).toBe(false); }); @@ -72,6 +74,7 @@ describe('shipping configuration navigation contract', () => { expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'identity_rules' }), expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_extraction_runs' }), expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'shipping_audit' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'process_gates' }), expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }), ]); }); diff --git a/frontend/src/features/admin/types/admin.types.ts b/frontend/src/features/admin/types/admin.types.ts index b6eda5e8..587f741d 100644 --- a/frontend/src/features/admin/types/admin.types.ts +++ b/frontend/src/features/admin/types/admin.types.ts @@ -28,6 +28,7 @@ export type ShippingConfigSubModuleId = | 'identity_rules' | 'order_extraction_runs' | 'shipping_audit' + | 'process_gates' | 'inventory_fields' | 'connections' | 'inventory_sites' diff --git a/frontend/src/features/admin/views/AdminLayout.vue b/frontend/src/features/admin/views/AdminLayout.vue index 758c4208..8d9e9b83 100644 --- a/frontend/src/features/admin/views/AdminLayout.vue +++ b/frontend/src/features/admin/views/AdminLayout.vue @@ -2,7 +2,8 @@ * features/admin/views/AdminLayout.vue * 管理后台壳层:顶栏 + 左侧导航 + 子路由出口。 * 依赖:AdminNav、vue-router、admin-nav.store。 - * 逻辑:AdminNav 统一承担模块和二级目录导航,内容区保持全宽展示当前页面。 + * 逻辑:AdminNav 统一承担模块和二级目录导航;lg 起侧栏与内容并排, + * 小于 lg(含 768px)上下堆叠,避免运维诊断页主区被侧栏挤窄。 */ diff --git a/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue b/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue index 3d35f441..704911bd 100644 --- a/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue +++ b/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.vue @@ -5,6 +5,7 @@ * orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。 * 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice; * 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页; + * 用户界面只展示业务原因,内部错误码仅保留在管理员审计中; * 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细。 */ + + diff --git a/frontend/src/features/shipping-process-gates/composables/processGateNavigation.ts b/frontend/src/features/shipping-process-gates/composables/processGateNavigation.ts new file mode 100644 index 00000000..2588deb6 --- /dev/null +++ b/frontend/src/features/shipping-process-gates/composables/processGateNavigation.ts @@ -0,0 +1,78 @@ +/** + * features/shipping-process-gates/composables/processGateNavigation.ts + * 用途:将服务端下发的门禁恢复动作映射为 Vue Router 深链(复核台 / 任务工作台)。 + * 依赖:process-gate.types、vue-router RouteLocationRaw。 + * 逻辑:与 process_gate_projection.navigation 对齐;禁止本地发明 action_code。 + */ +import type { RouteLocationRaw } from 'vue-router'; +import type { ShippingProcessGateUserSummary } from '../types/process-gate.types'; + +/** 点击后仅导航、不 POST 的人工入口动作(regenerate_manual_upload_todo 除外)。 */ +export const PROCESS_GATE_NAVIGATION_ACTIONS = new Set([ + 'open_order_review', + 'open_inventory_source_review', + 'open_profile_review', + 'edit_order_fields', + 'edit_reservation', + 'confirm_customer', + 'adjudicate_duplicate', + 'resolve_field_conflicts', + 'open_inventory_match_review', + 'open_shortage_review', + 'upload_inventory_file', + 'confirm_inventory_field_mapping', +]); + +export interface ProcessGateNavigationContext { + agentId?: string; + conversationId?: string; + preserveQuery?: Record; +} + +/** + * 判断动作码是否属于前端导航类恢复动作。 + */ +export function isProcessGateNavigationAction(actionCode: string): boolean { + return PROCESS_GATE_NAVIGATION_ACTIONS.has(String(actionCode || '').trim()); +} + +/** + * 根据 Gate 摘要与动作码构建 router 目标。 + * 核心逻辑:优先 summary.navigation;缺省时回退 review_run_no / case_no / task_no。 + * @returns 可 push 的路由;缺关键编号时 null + */ +export function buildProcessGateNavigationRoute( + summary: ShippingProcessGateUserSummary, + actionCode: string, + context: ProcessGateNavigationContext = {}, +): RouteLocationRaw | null { + const code = String(actionCode || '').trim(); + if (!isProcessGateNavigationAction(code)) return null; + + const nav = summary.navigation; + const runNo = String(nav?.run_no || summary.review_run_no || '').trim(); + const caseNo = String(nav?.case_no || summary.review_case_no || summary.case_no || '').trim(); + const taskNo = String(nav?.task_no || summary.task_no || '').trim(); + const focus = String(nav?.focus || 'draft').trim(); + + if (nav?.target === 'task_workspace' || code === 'upload_inventory_file') { + if (!taskNo) return null; + return { name: 'workspace-shipping-tasks', params: { taskNo } }; + } + + if (!runNo) return null; + const query: Record = { + ...(context.preserveQuery || {}), + mode: 'order-review', + run_no: runNo, + }; + if (caseNo) query.case = caseNo; + if (focus) query.focus = focus; + if (context.conversationId) query.conversation_id = context.conversationId; + if (!context.agentId) return null; + return { + name: 'Chat', + params: { agentId: context.agentId }, + query, + }; +} diff --git a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts new file mode 100644 index 00000000..167aa722 --- /dev/null +++ b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts @@ -0,0 +1,132 @@ +/** + * features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts + * 用途:任务工作台门禁恢复动作编排(导航、幂等键、版本锁、409 刷新)。 + * 依赖:process-gates.api、processGateNavigation、process-gate.types、useMessage。 + * 逻辑:ProcessGateRecoveryCard 调用 submitPrimaryAction;禁止本地发明 action_code。 + */ +import { ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { useRouter } from 'vue-router'; +import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client'; +import { useMessage } from '@/shared/composables/useMessage'; +import { postWorkspaceProcessGateAction } from '../api/process-gates.api'; +import type { + ShippingProcessGateActionCode, + ShippingProcessGateUserSummary, +} from '../types/process-gate.types'; +import { + buildProcessGateNavigationRoute, + isProcessGateNavigationAction, + type ProcessGateNavigationContext, +} from './processGateNavigation'; + +export type ProcessGateActionOutcome = + | 'submitted' + | 'navigated' + | 'refresh_needed' + | 'failed' + | 'noop'; + +export interface ProcessGateActionResult { + outcome: ProcessGateActionOutcome; +} + +function newIdempotencyKey(): string { + if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { + return crypto.randomUUID(); + } + return `pg-${Date.now()}-${Math.random().toString(16).slice(2)}`; +} + +/** + * 编排单次门禁恢复:导航类动作直接 router.push;其余 POST 到 Workspace API。 + * @returns busy 状态与 submitPrimaryAction 方法 + */ +export function useShippingProcessGateRecovery() { + const { t } = useI18n(); + const msg = useMessage(); + const router = useRouter(); + const busy = ref(false); + + /** + * 提交或导航当前阻断 Gate 的主要恢复动作。 + * 核心逻辑:evaluation_version 来自 current_blocking_gate;409 返回 refresh_needed。 + */ + async function submitPrimaryAction( + summary: ShippingProcessGateUserSummary, + options?: { + payload?: Record; + navigationContext?: ProcessGateNavigationContext; + }, + ): Promise { + const gate = summary.current_blocking_gate; + const actionCode = (summary.next_action_code || gate?.next_action_code || '') as ShippingProcessGateActionCode | ''; + if (!summary.execution_no || !gate?.gate_code || !actionCode) { + msg.warning(t('workspace.shippingNotice.processGate.noAction')); + return { outcome: 'noop' }; + } + + if (isProcessGateNavigationAction(actionCode)) { + const route = buildProcessGateNavigationRoute( + summary, + actionCode, + options?.navigationContext || {}, + ); + if (!route) { + msg.warning(t('workspace.shippingNotice.processGate.navigationMissing')); + return { outcome: 'failed' }; + } + busy.value = true; + try { + await router.push(route); + return { outcome: 'navigated' }; + } catch { + msg.warning(t('workspace.shippingNotice.actions.failed')); + return { outcome: 'failed' }; + } finally { + busy.value = false; + } + } + + const expectedVersion = Number(gate.evaluation_version); + if (!Number.isFinite(expectedVersion) || expectedVersion < 1) { + msg.warning(t('workspace.shippingNotice.processGate.versionMissing')); + return { outcome: 'failed' }; + } + busy.value = true; + try { + await postWorkspaceProcessGateAction(summary.execution_no, String(gate.gate_code), { + action_code: actionCode, + expected_gate_version: expectedVersion, + idempotency_key: newIdempotencyKey(), + payload: options?.payload, + }); + msg.success(t('workspace.shippingNotice.processGate.actionSubmitted')); + return { outcome: 'submitted' }; + } catch (error: unknown) { + const isVersionMismatch = error instanceof BusinessError && ( + error.code === 'SHIPPING.PROCESS_GATE_VERSION_MISMATCH' + || error.status === 409 + ); + if (isVersionMismatch) { + msg.warning(resolveLocalizedErrorMessage( + 'SHIPPING.PROCESS_GATE_VERSION_MISMATCH', + error instanceof BusinessError ? error.message : undefined, + )); + return { outcome: 'refresh_needed' }; + } + const message = error instanceof BusinessError + ? resolveLocalizedErrorMessage(error.code, error.message) + : (error instanceof Error ? error.message : t('workspace.shippingNotice.actions.failed')); + msg.warning(message); + return { outcome: 'failed' }; + } finally { + busy.value = false; + } + } + + return { + busy, + submitPrimaryAction, + }; +} diff --git a/frontend/src/features/shipping-process-gates/types/process-gate.types.ts b/frontend/src/features/shipping-process-gates/types/process-gate.types.ts new file mode 100644 index 00000000..7caa06e8 --- /dev/null +++ b/frontend/src/features/shipping-process-gates/types/process-gate.types.ts @@ -0,0 +1,52 @@ +/** + * features/shipping-process-gates/types/process-gate.types.ts + * 用途:全门禁恢复 API 与工作台卡片类型;与后端 process_gate_projection 对齐。 + * 依赖:features/chat/types/shipping.api.types 中的 Gate 联合类型与摘要接口。 + * 逻辑:避免重复定义 action/gate code 联合;Workspace API 专用响应在此扩展。 + */ +import type { + ShippingProcessGateActionCode, + ShippingProcessGateCode, + ShippingProcessGateProjection, + ShippingProcessGateStatus, + ShippingProcessGateUserSummary, +} from '@/features/chat/types/shipping.api.types'; + +export type { + ShippingProcessGateActionCode, + ShippingProcessGateCode, + ShippingProcessGateProjection, + ShippingProcessGateStatus, + ShippingProcessGateUserSummary, +}; + +export interface ShippingProcessGateActionRequest { + action_code: ShippingProcessGateActionCode | string; + expected_gate_version: number; + idempotency_key: string; + payload?: Record; +} + +export interface ShippingProcessGateActionResponse { + execution_no: string; + gate_code: ShippingProcessGateCode | string; + action_code: ShippingProcessGateActionCode | string; + dispatch: 'sync' | 'async_job' | 'idempotent_replay' | string; + attempt: { + id: number; + attempt_no: number; + status: string; + idempotency_key: string; + }; + gate_status?: string; + gate_evaluation_version?: number; + next_action_code?: ShippingProcessGateActionCode | string | null; + job_id?: number; +} + +export interface ShippingProcessGateAuditEventsPage { + items: Array>; + total: number; + page: number; + page_size: number; +} diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskWorkbench.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskWorkbench.vue index b06bf53b..a316d86a 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskWorkbench.vue +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskWorkbench.vue @@ -28,7 +28,7 @@ const emit = defineEmits<{ refreshed: []; }>(); -const { t } = useI18n(); +const { t, te } = useI18n(); const msg = useMessage(); const workflowSteps = computed(() => resolveShippingWorkflowSteps(props.detail)); @@ -42,11 +42,32 @@ const workflowItem = computed(() => props.detail.workflow_item || null); const workflowEvents = computed(() => workflowItem.value?.events || []); const stpFacts = computed(() => props.detail.ui_state?.summary?.stp_facts || null); const lastActivityAt = computed(() => workflowItem.value?.last_activity_at || props.detail.updated_at || null); -const terminateReason = computed(() => workflowItem.value?.closed_reason || null); +const terminateReason = computed(() => { + const code = String(workflowItem.value?.closed_reason || '').trim(); + if (!code) return null; + const key = `workspace.shippingNotice.workflowReasons.${code}`; + return te(key) ? t(key) : t('workspace.shippingNotice.timeline.updated'); +}); const hasExcelArtifact = computed(() => Array.isArray(props.detail.export_artifacts) && props.detail.export_artifacts.length > 0, ); +/** 将内部状态映射为业务文案,未知值不回显原始状态码。 */ +function workflowStatusLabel(value: unknown): string { + const code = String(value || '').trim(); + if (!code) return t('workspace.shippingNotice.status.unknown'); + const key = `workspace.shippingNotice.workflowStatus.${code}`; + return te(key) ? t(key) : t('workspace.shippingNotice.status.unknown'); +} + +const taskStatusLabel = computed(() => workflowStatusLabel(props.detail.process_status)); +const taskMatchStatusLabel = computed(() => { + const code = String(props.detail.match_status || '').trim(); + if (!code) return t('workspace.shippingNotice.matchStatus.unknown'); + const key = `workspace.shippingNotice.matchStatus.${code}`; + return te(key) ? t(key) : t('workspace.shippingNotice.matchStatus.unknown'); +}); + /** * 下载已生成的发货 Excel。 */ @@ -84,8 +105,8 @@ async function downloadExcel() {
{{ $t('workspace.shippingNotice.todo.workflowItem') }}
-
- {{ workflowItem.item_no }} · {{ workflowItem.lifecycle_status }} · {{ workflowItem.current_stage }} +
+ {{ workflowStatusLabel(workflowItem.lifecycle_status) }} · {{ workflowStatusLabel(workflowItem.current_stage) }}
@@ -109,11 +130,11 @@ async function downloadExcel() {
{{ $t('workspace.shippingNotice.fields.status') }}
-
{{ detail.process_status || '—' }}
+
{{ taskStatusLabel }}
{{ $t('workspace.shippingNotice.fields.match') }}
-
{{ detail.match_status || '—' }}
+
{{ taskMatchStatusLabel }}
{{ $t('workspace.shippingNotice.fields.shipTo') }}
diff --git a/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts b/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts index b45fef25..1d7a25c1 100644 --- a/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts +++ b/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts @@ -2,7 +2,7 @@ * features/workspace/shipping-task-center/TaskProgressTimeline.spec.ts * 用途:锁定任务中心时间线同时消费 Task Event 与 Workflow Event。 * 依赖:Vitest、@vue/test-utils、TaskProgressTimeline。 - * 逻辑:合并排序后两类事件均可见;Workflow 操作人展示 type/id。 + * 逻辑:合并排序后两类事件均可见;未知内部码、操作人 ID 与 JSON 详情不展示。 */ import { describe, expect, it } from 'vitest'; import { mount } from '@vue/test-utils'; @@ -21,8 +21,10 @@ const messages = { empty: '暂无事件记录', detail: '查看详情', sourceTask: '任务事件', - sourceWorkflow: 'Workflow 事件', - workflowEvent: 'Workflow 事件', + sourceWorkflow: '文件处理记录', + workflowEvent: '文件处理记录', + updated: '处理状态已更新', + actors: { user: '业务人员', system: '系统' }, }, }, }, @@ -51,10 +53,40 @@ describe('TaskProgressTimeline', () => { }); // 关键断言:时间线同时展示 Task 与 Workflow 事件来源标签,且 Workflow 显示操作人。 expect(wrapper.text()).toContain('任务事件'); - expect(wrapper.text()).toContain('Workflow 事件'); + expect(wrapper.text()).toContain('文件处理记录'); expect(wrapper.text()).toContain('任务已创建'); expect(wrapper.text()).toContain('人工上传已登记'); - expect(wrapper.text()).toContain('操作者 1'); - expect(wrapper.text()).toContain('操作者 user/42'); + expect(wrapper.text()).toContain('操作者 业务人员'); + expect(wrapper.text()).not.toContain('user/42'); + expect(wrapper.text()).not.toContain('操作者 1'); + }); + + it('does not expose unknown event codes or raw detail JSON', () => { + const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages }); + const wrapper = mount(TaskProgressTimeline, { + props: { + events: [{ + event_type: 'internal_task_event', + actor_id: 99, + detail_json: { node_id: 'node-1', error: 'HTTP 500' }, + }], + workflowEvents: [{ + seq_no: 2, + event_code: 'internal_workflow_event', + actor_type: 'worker', + actor_id: 'worker-7', + payload: { gate_code: 'quality_gate_internal' }, + }], + }, + global: { plugins: [i18n] }, + }); + const text = wrapper.text(); + expect(text).toContain('处理状态已更新'); + for (const technicalText of [ + 'internal_task_event', 'internal_workflow_event', 'node_id', 'HTTP 500', + 'gate_code', 'quality_gate_internal', 'worker-7', + ]) { + expect(text).not.toContain(technicalText); + } }); }); diff --git a/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.vue b/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.vue index 04259aed..5ce21ea1 100644 --- a/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.vue +++ b/frontend/src/features/workspace/shipping-task-center/TaskProgressTimeline.vue @@ -3,7 +3,7 @@ * 用途:展示任务事件 + Workflow Event 统一时间线(只读),不发明进度百分比。 * 依赖:ShippingTaskEvent、ShippingWorkflowEvent、dateTime、vue-i18n。 * 逻辑:由 ShippingTaskWorkbench 传入 task events 与 workflow events;按时间合并排序; - * Workflow 事件操作人展示为 actor_type/actor_id。 + * 未知事件与操作者内部标识统一使用通用业务文案。 */ diff --git a/frontend/src/locales/en/admin.json b/frontend/src/locales/en/admin.json index 113b1805..61e834bf 100644 --- a/frontend/src/locales/en/admin.json +++ b/frontend/src/locales/en/admin.json @@ -40,7 +40,8 @@ "shippingOrderDocumentProfiles": "Doc Templates", "shippingFieldAssets": "Field Assets", "shippingOrderSchema": "Order Schema", - "shippingAudit": "Audit center" + "shippingAudit": "Audit center", + "shippingProcessGates": "Process gate diagnostics" }, "shippingOrderExtractionRuns": { "eyebrow": "READ-ONLY RUN DIAGNOSTICS", @@ -3712,5 +3713,81 @@ "chainTruncated": " (truncated)", "eventHash": "Event hash", "previousEventHash": "Previous hash" + }, + "shippingProcessGates": { + "title": "Process Gate diagnostics", + "subtitle": "Read-only Execution gate track, blocking status, and Attempt history for recovery troubleshooting.", + "refresh": "Refresh", + "loading": "Loading…", + "empty": "No executions", + "loadFailed": "Failed to load executions", + "detailFailed": "Failed to load execution detail", + "attemptsFailed": "Failed to load attempts", + "detailTitle": "Execution diagnostics", + "executionNo": "Execution no.", + "status": "Status", + "allStatuses": "All statuses", + "currentGate": "Current gate", + "nextAction": "Primary action", + "updatedAt": "Updated at", + "actions": "Actions", + "viewDetail": "View detail", + "viewAttempts": "View attempts", + "viewSnapshots": "View input/output snapshots", + "total": "{count} total", + "previous": "Previous", + "next": "Next", + "gates": "Gate track", + "gateCode": "Gate code", + "gateStatus": "Gate status", + "blockingReason": "Blocking reason code", + "blockingReasonDetail": "Blocking reason detail", + "gateDiagnostics": "Selected gate diagnostics", + "findings": "Findings", + "effectiveResult": "Effective result", + "attempts": "Attempts", + "noAttempts": "No attempts", + "taskNo": "Task no.", + "caseNo": "Review case", + "scrollHint": "Scroll horizontally to see all columns", + "filterGate": "Filter by gate code", + "filterReason": "Filter by blocking reason", + "filterParty": "Filter by responsible party", + "filterSearch": "Keyword search", + "filterFrom": "Updated from", + "filterTo": "Updated to", + "applyFilters": "Apply filters", + "resetFilters": "Reset filters", + "findingsStructured": "Structured findings", + "severity": "Severity", + "field": "Field", + "party": "Party", + "reason": "Reason", + "message": "Message", + "noFindings": "No findings", + "attemptDiff": "{scope}: +{added} / -{removed} / ~{changed}", + "auditLink": "View process_gate_ audit events for this execution in the audit center", + "openAudit": "Open audit center", + "responsibleParty": "Responsible party", + "blockingReasonCode": "Blocking reason code", + "statusLabels": { + "active": "Active", + "blocked": "Blocked", + "waiting_external": "Waiting external", + "completed": "Completed", + "failed": "Failed", + "cancelled": "Cancelled", + "pending": "Pending", + "queued": "Queued", + "running": "Running", + "passed": "Passed", + "blocked_retryable": "Retryable block", + "blocked_manual": "Needs manual action", + "failed_terminal": "Terminal failure", + "invalidated": "Invalidated", + "skipped": "Skipped", + "succeeded": "Succeeded", + "superseded": "Superseded" + } } } diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index 0ab223d3..cc92923a 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -198,7 +198,7 @@ "nonOrderReasonPrompt": "Enter a reason for marking non-order", "reparseReasonPrompt": "Enter a reason for re-identification", "reasonRequired": "A reason is required to continue", - "caseRequired": "This work item has no review case; open manual review first", + "caseRequired": "A review form is not ready for this file yet. Try again shortly.", "versionHistoryTitle": "Version history", "currentVersion": "Current", "readonlyVersion": "Read-only", @@ -344,7 +344,8 @@ "candidate_ready": "Candidate ready", "review_required": "Manual review required", "failed": "Processing failed", - "cancelled": "Cancelled" + "cancelled": "Cancelled", + "unknown": "Status pending confirmation" }, "shippingOrderExtractionReason": { "profile_not_found": "No suitable published order template was found.", @@ -395,12 +396,14 @@ "generic_deterministic": "Generic rule-based parse", "llm_assisted_review": "AI-assisted review", "manual_review": "Manual review", - "rejected": "Rejected" + "rejected": "Rejected", + "unknown": "Processing method pending confirmation" }, "shippingOrderExtractionFreezeSource": { "profile_deterministic": "Auto-freeze source: template", "generic_deterministic": "Auto-freeze source: generic rules", - "manual_confirmation": "Freeze source: manual confirmation" + "manual_confirmation": "Confirmation method: manual confirmation", + "unknown": "Confirmation method pending" }, "shippingOrderExtractionPlanSummary": "This run planned {groups} order group(s) from {total} attachment(s). The first wave may process up to {attachments} attachment(s) with concurrency {concurrency}.", "shippingOrderExtractionPlanSelected": "{count} attachment(s) selected", @@ -439,7 +442,8 @@ }, "shippingOrderExtractionEmailSupplementRelation": { "po_mpn": "Relation: PO + part number", - "po_fallback": "Relation: PO fallback" + "po_fallback": "Relation: matched by PO", + "unknown": "Relation pending confirmation" }, "shippingOrderExtractionEmailSupplementField": { "reservation": "Reservation: ", @@ -1435,7 +1439,7 @@ "unknown": "Unknown status" }, "previewTitle": "PDF preview", - "buildGateRail": "Build eligibility and inventory candidates", + "buildGateRail": "Order checks and inventory sources", "previewLoading": "Loading PDF preview...", "previewUnavailable": "PDF preview is unavailable. Draft editing is unaffected.", "previewCollapsed": "This evidence has only a page and quote, with no reliable coordinates; the PDF preview is collapsed.", @@ -1446,15 +1450,36 @@ "viewEvidence": "View evidence", "locateSource": "Locate source: {field}", "orderFields": "Order fields", - "schemaVersion": "Frozen schema #{version}", + "schemaVersion": "Order field version V{version}", "issues": "Open issues", - "machineSource": "Source: machine extraction", + "issueCodes": { + "customer_unresolved": "Customer information has not been confirmed", + "machine_order_unavailable": "No reviewable order information was identified", + "machine_multiple_orders_legacy": "This file may contain multiple orders; please confirm them", + "required_field_missing": "Information required to create the order is missing", + "field_value_invalid": "Some order information has an invalid format", + "invalid_order_line": "Some order lines are incomplete or invalid", + "effective_reservation_missing": "A valid reservation number is missing", + "reservation_duplicated_in_order": "The order contains duplicate reservation numbers", + "require_manual_review": "The inventory source needs confirmation", + "no_inventory_source_candidates": "No available inventory source was found", + "manual_inventory_source_reason_required": "Select an inventory source and provide a reason", + "manual_inventory_source_invalid": "The selected inventory source is unavailable", + "inventory_source_unresolved": "The inventory source has not been determined", + "auto_build_gate_approved_template": "This file needs review before the order can be created", + "auto_build_gate_fields_complete": "Complete the order information to continue", + "auto_build_gate_evidence_passed": "Some recognized information needs confirmation", + "auto_build_gate_no_conflict_or_duplicate": "Check whether the order is duplicated or contains conflicting information", + "auto_build_gate_quality_gate_passed": "The automatic order creation policy has not approved this order; manual confirmation is required", + "unknown": "The system found an item that needs confirmation" + }, + "machineSource": "Source: system recognition", "manualSource": "Source: manual edit", "derivedSource": "Source: rule derivation", "overrideSource": "Source: manual override (locked)", "skippedSource": "Source: derivation skipped", "valueSources": { - "machine": "Machine", + "machine": "System recognized", "manual": "Manual edit", "manual_override": "Manual override", "derived": "Derived", @@ -1470,10 +1495,11 @@ "compare": "Compare suggestion", "scope": "Evidence scope: {level}", "evidenceLevel": { - "L1_field": "Field text", + "L1_field": "Current field content", "L2_table": "Containing table", "L3_page": "Containing page", - "L4_pdf": "Full PDF (authorized)" + "L4_pdf": "Full PDF (authorized)", + "unknown": "Relevant document content" }, "review": "Review", "empty": "No AI suggestions yet. Select a field, then request.", @@ -1493,7 +1519,8 @@ "accepted": "Accepted", "modified": "Modified", "rejected": "Rejected", - "failed": "Unavailable" + "failed": "Unavailable", + "unknown": "Status pending confirmation" }, "decisions": { "accept": "Accept", @@ -1524,7 +1551,7 @@ "other": "Other" } }, - "restoreMachine": "Restore machine value", + "restoreMachine": "Restore recognized value", "restorePriorProjection": "Restore extracted/derived value", "lineNoUnsavedHint": "Unsaved · enter override reason on blur", "lockedHint": "Locked", @@ -1557,7 +1584,7 @@ "addLine": "Add line", "copyLine": "Copy line", "deleteLine": "Delete line", - "noMachineOrder": "Machine results are awaiting review. Create a draft to make corrections.", + "noMachineOrder": "The recognized result needs confirmation. Create a draft to make corrections.", "lines": "Order lines", "line": "Line {index}", "noLines": "No order lines were identified.", @@ -1600,9 +1627,19 @@ "manual_upload_pending": "Awaiting upload registration" } }, + "reparseProgress": { + "title": "PDF recognition progress", + "subtitle": "Progress comes from the current work item. The new review draft opens automatically when ready.", + "polling": "Refreshing live progress…", + "refreshFailed": "Progress is temporarily unavailable. The last stage is retained while retrying automatically.", + "failed": "Recognition did not complete. The previous version was retained and you can recognize it again now.", + "retry": "Recognize again", + "stages": { "submitted": "Submitted", "layout_parsing": "Reading page content", "extracting": "Reading order information", "draft_ready": "Preparing review content" } + }, "backToSession": "Back to this session", "workItemHeader": "Work item {itemNo} · {version}", "jumpToCurrentVersion": "Go to current version", + "currentVersionUnavailable": "The current version is not ready or progress cannot be refreshed yet. Please try again shortly.", "showContext": "Conversation context", "hideContext": "Hide context", "contextTitle": "Conversation context", @@ -1614,7 +1651,8 @@ "work_item_closed": "This work item is closed and read-only. Disposition and editing are disabled.", "reparse_in_progress": "This PDF is being re-recognized. Please wait before continuing review.", "restored": "Re-recognition failed and the previous version was restored. You may continue editing.", - "draft_version_conflict": "Draft version conflict: your local edits are outdated. Reload the latest version before continuing." + "draft_version_conflict": "Draft version conflict: your local edits are outdated. Reload the latest version before continuing.", + "unknown": "The order status changed. Refresh before continuing." }, "versionHistory": { "title": "Version history", @@ -1626,31 +1664,33 @@ "open": "Open" }, "buildEligibility": { - "title": "Build eligibility", - "subtitle": "Reservation and inventory routing gates after draft validation.", + "title": "Order checks", + "subtitle": "Checks whether the order information and inventory sources are ready for order creation.", "canBuildYes": "Can build", "canBuildNo": "Cannot build yet", "statusLabel": "Eligibility status", - "blockingSummary": "Blocking summary", - "lineProjections": "Line projections", + "blockingSummary": "Needs attention", + "lineProjections": "Line check results", "lineCanBuild": "Eligible", - "lineBlocked": "Blocked", - "reservation": "Effective reservation", - "routingStatusLabel": "Routing status", + "lineBlocked": "Needs attention", + "reservation": "Reservation number", + "routingStatusLabel": "Inventory source status", "sourceHint": "Inventory hint", "candidates": "Candidate sources", - "blockReason": "Block reason", + "blockReason": "Reason to address", "manualReason": "Manual reason", "confirmBlocked": "Build eligibility is not satisfied. Resolve inventory or validation issues before confirming.", "status": { "ready": "Ready to build", - "needs_review": "Needs review" + "needs_review": "Needs review", + "unknown": "Needs confirmation" }, "routingStatus": { "resolved": "Resolved", "ambiguous": "Multiple candidates", "unresolved": "Unresolved", - "conflicted": "Manual review required" + "conflicted": "Confirmation required", + "unknown": "Needs confirmation" }, "blockReasons": { "require_manual_review": "Rules require manual inventory review", @@ -1658,20 +1698,33 @@ "manual_inventory_source_reason_required": "Manual selection reason required", "manual_inventory_source_invalid": "Selected inventory source invalid or disabled", "inventory_source_unresolved": "Inventory source unresolved", - "effective_reservation_missing": "Effective reservation missing" + "effective_reservation_missing": "A valid reservation number is missing", + "unknown": "The system found an item that needs confirmation" } }, "inventoryCandidates": { "title": "Manual inventory selection", - "subtitle": "Choose one or more enabled inventory sources for unresolved lines and provide a reason.", + "subtitle": "Choose one or more enabled inventory sources for unresolved lines and provide a reason. You can also rematch rules or resolve pending suggestions.", "selectSources": "Select candidates", "selectEnabledSources": "Select from enabled inventory sources", - "noCandidates": "No selectable sources. Check routing rules or contact an administrator.", + "noCandidates": "No inventory sources are available. Contact an administrator to check the configuration.", "noEnabledSources": "No enabled inventory sources are available. Ask an administrator to enable sources first.", "reasonLabel": "Reason (required)", "reasonPlaceholder": "Explain why these inventory sources were selected...", "submit": "Submit candidates" }, + "inventoryRouting": { + "reroute": "Rematch routing", + "adoptSuggestion": "Adopt rule result", + "keepManual": "Keep manual result", + "suggestionPending": "The rule suggestion was updated and differs from the current manual result. Adopt the rule result or keep the manual result.", + "rawCandidates": "Raw rule candidates", + "unavailableCandidates": "Unavailable candidates", + "ruleSuggestion": "Rule suggestion", + "ruleVersions": "Rule versions", + "hint": "Inventory source hint", + "rerouteHint": "You can rematch routing rules at any time. When a suggestion is pending, decide whether to adopt or keep the manual result first." + }, "confirmDialog": { "reasonLabel": "Reason (required)", "reasonPlaceholder": "Describe why you are taking this action...", @@ -1782,7 +1835,7 @@ }, "itemStatus": { "queued": "Queued", - "layout_parsing": "Parsing layout", + "layout_parsing": "Reading page content", "extracting": "Extracting", "building_order": "Building order", "inventory_matching": "Matching inventory", @@ -1792,7 +1845,8 @@ "failed": "Failed", "closed": "Completed", "cancelled": "Cancelled", - "manual_upload_pending": "Awaiting upload registration" + "manual_upload_pending": "Awaiting upload registration", + "unknown": "Status pending confirmation" }, "closedReason": { "confirmed": "Order confirmed", @@ -1802,11 +1856,21 @@ }, "actions": { "refresh": "Refresh", + "openReview": "Open review workspace", "viewProgress": "View progress", "cancelFile": "Cancel this file", "reparse": "Re-identify", "retryFailedRun": "Retry failed run" }, + "reparseError": { + "title": "Re-identification did not complete", + "schemaUnavailable": "The order field rules are unavailable, so no new recognition result was created.", + "fallback": "The previous recognition version is preserved. Open the review workspace to handle this file manually.", + "contactAdmin": "If this affects multiple files, ask an administrator to check the order field rule version.", + "pending": "This file is already being re-identified. Wait for the current run to finish.", + "generic": "Re-identification did not complete. View the file details or try again later.", + "requestId": "Request ID: {id}" + }, "reasonDialog": { "cancelTitle": "Cancel this file", "reparseTitle": "Retry / re-identify", @@ -1825,14 +1889,17 @@ "filename": "Filename", "status": "Status", "stage": "Stage", - "runNo": "Extraction run", - "caseNo": "Review case", + "runNo": "Recognition batch", + "caseNo": "Review number", "lastActivity": "Last activity", "closedReason": "Closed reason", "eventsTitle": "Event timeline", "eventsEmpty": "No events yet", "empty": "No file selected" }, - "versionHistoryNote": "Full version history API is not available yet; showing the current item version only." + "event": { + "unknown": "Processing status updated" + }, + "versionHistoryNote": "Showing the available versions for this file." } } diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index ea92638a..b5edf33e 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -248,7 +248,8 @@ "SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "Shipping notice parsing timed out. Retry or remove and upload again.", "SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "Saving preprocessed email or attachment documents failed. Retry parsing.", "SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "Shipping notice attachments are incomplete. Retry parse or remove and upload again.", - "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "Shipping notice intake has already been consumed.", + "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "This file is already being handled. View the existing result instead of submitting it again.", + "SHIPPING_NOTICE_ORDER_EXTRACTION_ALREADY_CONSUMED": "This file already has an order-processing result. View it or use recognition again.", "SHIPPING_NOTICE_INTAKE_EXPIRED": "Shipping notice intake has expired.", "SHIPPING_NOTICE_INTAKE_INVALID_STATUS": "Current intake status does not allow this operation.", "SHIPPING_NOTICE_DUPLICATE_RESOLUTION_REQUIRED": "A duplicate shipping notice was detected. Choose how to proceed.", @@ -370,6 +371,8 @@ "SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "The draft was updated in another window. Refresh and try again.", "SHIPPING_REVIEW_FIELD_INVALID": "The review field is not in this order's frozen schema.", "SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "Manual inventory source candidates are invalid. Select enabled sources and provide a reason.", + "SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "Cannot adopt the rule suggestion: this line has no valid pending rule result.", + "SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "Cannot keep the manual result: this line has no pending rule suggestion.", "SHIPPING_REVIEW_BUILD_ELIGIBILITY_BLOCKED": "Build eligibility failed. Resolve blocking issues or inventory candidates before confirming.", "SHIPPING_REVIEW_LINE_NOT_FOUND": "The order line was not found or was deleted.", "SHIPPING_REVIEW_DOCUMENT_NOT_FOUND": "The review PDF does not exist or is not accessible.", @@ -397,6 +400,18 @@ "SHIPPING_REVIEW_QUALITY_COMMENT_REQUIRED": "A comment is required when the quality issue reason is Other.", "SHIPPING_NOTICE_SESSION_WORK_ITEM_CLOSE_REASON_REQUIRED": "A reason is required to cancel this work item.", "SHIPPING_NOTICE_SESSION_WORK_ITEM_LOCK_VERSION_INVALID": "The work item version is invalid. Refresh and try again.", - "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "The work item was updated by another operation. Refresh and try again." + "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "The work item was updated by another operation. Refresh and try again.", + "SHIPPING.PROCESS_EXECUTION_NOT_FOUND": "The process execution was not found.", + "SHIPPING.PROCESS_GATE_NOT_FOUND": "The process gate was not found.", + "SHIPPING.PROCESS_GATE_ACTION_INVALID": "The process gate recovery action is invalid.", + "SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN": "The request includes forbidden execution control fields.", + "SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED": "This action is not the allowed primary recovery action for the current gate.", + "SHIPPING.PROCESS_GATE_VERSION_MISMATCH": "The gate version changed. Refresh and try again.", + "SHIPPING.PROCESS_GATE_BUSY": "The gate is already running. Try again shortly.", + "SHIPPING.PROCESS_GATE_ALREADY_PASSED": "This gate has already passed.", + "SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND": "The process gate attempt was not found.", + "SHIPPING.PROCESS_GATE_PERMISSION_DENIED": "You do not have permission to access or recover this gate.", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED": "The recovery request is missing an idempotency key.", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT": "The idempotency key conflicts with a different gate request. Retry with a new key." } } diff --git a/frontend/src/locales/en/workspace.json b/frontend/src/locales/en/workspace.json index 1118c190..f0ab0cd0 100644 --- a/frontend/src/locales/en/workspace.json +++ b/frontend/src/locales/en/workspace.json @@ -181,11 +181,57 @@ "adminViewOnlyShort": "View only", "lastActivity": "Last activity", "terminateReason": "Terminate reason", - "workflowItem": "Workflow Item", + "workflowItem": "File item", "downloadExcel": "Download shipping Excel", "manualUploadEndNote": "Excel generated. Download it, upload on the freight platform, then register credentials here.", "waitingManualUploadNote": "Excel generated. Download it, upload on the freight platform, then register credentials here." }, + "processGate": { + "title": "Action needed", + "currentGate": "Current step", + "blockingMessage": "What needs attention", + "reasonCode": "Reason", + "diagnosticHint": "Suggested action", + "noAction": "No action is currently available", + "versionMissing": "This information has changed. Refresh and try again.", + "navigationMissing": "Navigation context is missing. Refresh and try again.", + "genericBlocking": "This step needs manual attention", + "unknownStep": "Current step", + "continueAction": "Continue", + "actionSubmitted": "Action submitted", + "submitting": "Submitting…", + "actionCodes": { + "retry_with_latest_rules": "Retry with latest rules", + "open_inventory_source_review": "Open inventory source review", + "open_order_review": "Open order review", + "open_profile_review": "Open profile review", + "edit_order_fields": "Edit order fields", + "confirm_customer": "Confirm customer", + "adjudicate_duplicate": "Adjudicate duplicate", + "resolve_field_conflicts": "Resolve field conflicts", + "open_inventory_match_review": "Open inventory match review", + "open_shortage_review": "Open shortage review", + "upload_inventory_file": "Upload inventory file", + "adopt_rule_suggestion": "Adopt rule suggestion", + "keep_manual_inventory_decision": "Keep manual decision", + "retry_task_creation": "Retry task creation", + "retry_inventory_preparation": "Retry inventory preparation", + "regenerate_excel_artifact": "Regenerate Excel", + "regenerate_manual_upload_todo": "Regenerate manual upload todo" + }, + "reasons": { + "freeze_not_ready": "Order is not ready to build or freeze", + "profile_not_auto_freeze_approved": "Document profile is not approved for auto build", + "profile_manual_confirmation_required": "Document profile requires manual confirmation", + "customer_unresolved": "Customer is unresolved", + "customer_ambiguous": "Customer resolution is ambiguous", + "field_conflict": "Field conflicts need manual resolution", + "duplicate_unresolved": "Duplicate order is unresolved", + "require_manual_review": "Manual review is required", + "no_inventory_source_candidates": "No inventory source candidates found", + "inventory_source_unavailable": "Inventory source is unavailable" + } + }, "myTodos": { "title": "My Todos", "subtitle": "Cross-session aggregation of pending review, exceptions, and waiting manual upload registration.", @@ -237,8 +283,28 @@ "empty": "No events yet", "detail": "View details", "sourceTask": "Task event", - "sourceWorkflow": "Workflow event", - "workflowEvent": "Workflow event" + "sourceWorkflow": "File processing record", + "workflowEvent": "File processing record", + "updated": "Processing status updated", + "actors": { + "user": "Business user", + "system": "System", + "admin": "Administrator" + } + }, + "workflowStatus": { + "created": "Created", + "queued": "Waiting", + "extracting": "Recognizing", + "pending_review": "Pending review", + "waiting_manual_upload": "Waiting for manual upload", + "failed": "Processing failed", + "completed": "Completed", + "closed": "Closed" + }, + "workflowReasons": { + "user_cancelled": "Cancelled by user", + "completed": "Processing completed" }, "stpFacts": { "title": "STP fulfillment progress", diff --git a/frontend/src/locales/th/admin.json b/frontend/src/locales/th/admin.json index c2d50301..58d29233 100644 --- a/frontend/src/locales/th/admin.json +++ b/frontend/src/locales/th/admin.json @@ -39,7 +39,8 @@ "shippingOrderDocumentProfiles": "แม่แบบเอกสาร", "shippingFieldAssets": "คลังฟิลด์", "shippingOrderSchema": "Order Schema", - "shippingAudit": "ศูนย์ตรวจสอบ" + "shippingAudit": "ศูนย์ตรวจสอบ", + "shippingProcessGates": "การวินิจฉัย Process Gate" }, "shippingOrderExtractionRuns": { "eyebrow": "การวินิจฉัยการทำงานแบบอ่านอย่างเดียว", @@ -3580,5 +3581,81 @@ "chainTruncated": " (ตัดทอน)", "eventHash": "แฮชเหตุการณ์", "previousEventHash": "แฮชก่อนหน้า" + }, + "shippingProcessGates": { + "title": "การวินิจฉัย Process Gate", + "subtitle": "ดู Execution gate track สถานะการบล็อก และประวัติ Attempt แบบอ่านอย่างเดียว", + "refresh": "รีเฟรช", + "loading": "กำลังโหลด…", + "empty": "ไม่มี Execution", + "loadFailed": "โหลดรายการ Execution ล้มเหลว", + "detailFailed": "โหลดรายละเอียด Execution ล้มเหลว", + "attemptsFailed": "โหลด Attempt ล้มเหลว", + "detailTitle": "การวินิจฉัย Execution", + "executionNo": "หมายเลข Execution", + "status": "สถานะ", + "allStatuses": "สถานะทั้งหมด", + "currentGate": "Gate ปัจจุบัน", + "nextAction": "การกระทำหลัก", + "updatedAt": "อัปเดตเมื่อ", + "actions": "การดำเนินการ", + "viewDetail": "ดูรายละเอียด", + "viewAttempts": "ดู Attempt", + "viewSnapshots": "ดูสแนปช็อตอินพุต/เอาต์พุต", + "total": "ทั้งหมด {count} รายการ", + "previous": "ก่อนหน้า", + "next": "ถัดไป", + "gates": "Gate track", + "gateCode": "รหัส Gate", + "gateStatus": "สถานะ Gate", + "blockingReason": "รหัสเหตุผลที่บล็อก", + "blockingReasonDetail": "รายละเอียดเหตุผลที่บล็อก", + "gateDiagnostics": "การวินิจฉัย Gate ที่เลือก", + "findings": "Findings", + "effectiveResult": "ผลลัพธ์ที่มีผล", + "attempts": "Attempt", + "noAttempts": "ไม่มี Attempt", + "taskNo": "หมายเลขงาน", + "caseNo": "Review case", + "scrollHint": "เลื่อนแนวนอนเพื่อดูคอลัมน์ทั้งหมด", + "filterGate": "กรองตามรหัส Gate", + "filterReason": "กรองตามเหตุผลที่บล็อก", + "filterParty": "กรองตามผู้รับผิดชอบ", + "filterSearch": "ค้นหาด้วยคำสำคัญ", + "filterFrom": "อัปเดตตั้งแต่", + "filterTo": "อัปเดตถึง", + "applyFilters": "ใช้ตัวกรอง", + "resetFilters": "รีเซ็ตตัวกรอง", + "findingsStructured": "Findings แบบมีโครงสร้าง", + "severity": "ระดับความรุนแรง", + "field": "ฟิลด์", + "party": "ผู้รับผิดชอบ", + "reason": "เหตุผล", + "message": "ข้อความ", + "noFindings": "ไม่มี Finding", + "attemptDiff": "{scope}: เพิ่ม {added} / ลบ {removed} / เปลี่ยน {changed}", + "auditLink": "ดูเหตุการณ์ process_gate_ ของ Execution นี้ในศูนย์ audit", + "openAudit": "เปิดศูนย์ audit", + "responsibleParty": "ผู้รับผิดชอบ", + "blockingReasonCode": "รหัสเหตุผลที่บล็อก", + "statusLabels": { + "active": "กำลังดำเนินการ", + "blocked": "ถูกบล็อก", + "waiting_external": "รอภายนอก", + "completed": "เสร็จสิ้น", + "failed": "ล้มเหลว", + "cancelled": "ยกเลิกแล้ว", + "pending": "รอดำเนินการ", + "queued": "อยู่ในคิว", + "running": "กำลังรัน", + "passed": "ผ่านแล้ว", + "blocked_retryable": "บล็อกที่ลองใหม่ได้", + "blocked_manual": "ต้องดำเนินการด้วยมือ", + "failed_terminal": "ล้มเหลวขั้นสุดท้าย", + "invalidated": "หมดอายุผลแล้ว", + "skipped": "ข้ามแล้ว", + "succeeded": "สำเร็จ", + "superseded": "ถูกแทนที่" + } } } diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index 0349d9fb..2187723d 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -198,7 +198,7 @@ "nonOrderReasonPrompt": "กรอกเหตุผลที่ทำเครื่องหมายว่าไม่ใช่คำสั่งซื้อ", "reparseReasonPrompt": "กรอกเหตุผลการระบุใหม่", "reasonRequired": "ต้องระบุเหตุผลก่อนดำเนินการต่อ", - "caseRequired": "รายการงานนี้ยังไม่มีเคสตรวจสอบ กรุณาเปิดการตรวจสอบด้วยตนเองก่อน", + "caseRequired": "แบบฟอร์มตรวจสอบของไฟล์นี้ยังไม่พร้อม โปรดลองอีกครั้งในภายหลัง", "versionHistoryTitle": "ประวัติเวอร์ชัน", "currentVersion": "ปัจจุบัน", "readonlyVersion": "อ่านอย่างเดียว", @@ -344,7 +344,8 @@ "candidate_ready": "ตัวเลือกพร้อมแล้ว", "review_required": "ต้องตรวจสอบด้วยตนเอง", "failed": "ประมวลผลล้มเหลว", - "cancelled": "ยกเลิกแล้ว" + "cancelled": "ยกเลิกแล้ว", + "unknown": "รอยืนยันสถานะ" }, "shippingOrderExtractionReason": { "profile_not_found": "ไม่พบเทมเพลตคำสั่งซื้อที่เผยแพร่ซึ่งใช้งานได้", @@ -395,12 +396,14 @@ "generic_deterministic": "แยกวิเคราะห์ด้วยกฎทั่วไป", "llm_assisted_review": "ตรวจทานด้วย AI", "manual_review": "ตรวจทานด้วยตนเอง", - "rejected": "ปฏิเสธแล้ว" + "rejected": "ปฏิเสธแล้ว", + "unknown": "รอยืนยันวิธีประมวลผล" }, "shippingOrderExtractionFreezeSource": { "profile_deterministic": "แหล่งตรึงอัตโนมัติ: เทมเพลต", "generic_deterministic": "แหล่งตรึงอัตโนมัติ: กฎทั่วไป", - "manual_confirmation": "แหล่งตรึง: ยืนยันด้วยตนเอง" + "manual_confirmation": "วิธียืนยัน: ยืนยันด้วยตนเอง", + "unknown": "รอยืนยันวิธียืนยัน" }, "shippingOrderExtractionPlanSummary": "รอบนี้วางแผน {groups} กลุ่มคำสั่งซื้อจากไฟล์แนบ {total} ไฟล์ โดยรอบแรกจะประมวลผลได้สูงสุด {attachments} ไฟล์ พร้อมกัน {concurrency} ไฟล์", "shippingOrderExtractionPlanSelected": "เลือกแล้ว {count} ไฟล์", @@ -439,7 +442,8 @@ }, "shippingOrderExtractionEmailSupplementRelation": { "po_mpn": "วิธีเชื่อมโยง: PO + หมายเลขชิ้นส่วน", - "po_fallback": "วิธีเชื่อมโยง: ใช้ PO สำรอง" + "po_fallback": "วิธีเชื่อมโยง: จับคู่ด้วย PO", + "unknown": "รอยืนยันวิธีเชื่อมโยง" }, "shippingOrderExtractionEmailSupplementField": { "reservation": "Reservation: ", @@ -1435,7 +1439,7 @@ "unknown": "ไม่ทราบสถานะ" }, "previewTitle": "ตัวอย่าง PDF", - "buildGateRail": "คุณสมบัติสร้างงานและแหล่งสต็อก", + "buildGateRail": "ตรวจสอบคำสั่งซื้อและแหล่งสต็อก", "previewLoading": "กำลังโหลดตัวอย่าง PDF...", "previewUnavailable": "ตัวอย่าง PDF ใช้งานไม่ได้ แต่การแก้ไขร่างไม่ได้รับผลกระทบ", "previewCollapsed": "หลักฐานนี้มีเพียงหน้าและข้อความอ้างอิง โดยไม่มีพิกัดที่เชื่อถือได้ จึงย่อการแสดงตัวอย่าง PDF แล้ว", @@ -1446,8 +1450,29 @@ "viewEvidence": "ดูหลักฐาน", "locateSource": "ค้นหาต้นฉบับ: {field}", "orderFields": "ฟิลด์คำสั่งซื้อ", - "schemaVersion": "Schema ที่ตรึงไว้ #{version}", + "schemaVersion": "เวอร์ชันฟิลด์คำสั่งซื้อ V{version}", "issues": "ปัญหาที่ยังเปิดอยู่", + "issueCodes": { + "customer_unresolved": "ยังไม่ได้ยืนยันข้อมูลลูกค้า", + "machine_order_unavailable": "ไม่พบข้อมูลคำสั่งซื้อที่พร้อมตรวจสอบ", + "machine_multiple_orders_legacy": "ไฟล์นี้อาจมีหลายคำสั่งซื้อ โปรดยืนยันด้วยตนเอง", + "required_field_missing": "ข้อมูลที่จำเป็นสำหรับสร้างคำสั่งซื้อยังไม่ครบ", + "field_value_invalid": "ข้อมูลคำสั่งซื้อบางรายการมีรูปแบบไม่ถูกต้อง", + "invalid_order_line": "รายละเอียดคำสั่งซื้อบางรายการไม่ครบหรือไม่ถูกต้อง", + "effective_reservation_missing": "ไม่มีหมายเลขการจองที่ถูกต้อง", + "reservation_duplicated_in_order": "พบหมายเลขการจองซ้ำในคำสั่งซื้อนี้", + "require_manual_review": "ต้องยืนยันแหล่งสต็อกด้วยตนเอง", + "no_inventory_source_candidates": "ไม่พบแหล่งสต็อกที่ใช้งานได้", + "manual_inventory_source_reason_required": "เลือกแหล่งสต็อกและระบุเหตุผล", + "manual_inventory_source_invalid": "แหล่งสต็อกที่เลือกไม่พร้อมใช้งาน", + "inventory_source_unresolved": "ยังไม่สามารถระบุแหล่งสต็อกได้", + "auto_build_gate_approved_template": "ไฟล์นี้ต้องผ่านการตรวจสอบก่อนสร้างคำสั่งซื้อ", + "auto_build_gate_fields_complete": "กรอกข้อมูลคำสั่งซื้อให้ครบก่อนดำเนินการต่อ", + "auto_build_gate_evidence_passed": "ข้อมูลที่ระบบระบุบางส่วนต้องได้รับการยืนยัน", + "auto_build_gate_no_conflict_or_duplicate": "ตรวจสอบว่าคำสั่งซื้อซ้ำหรือมีข้อมูลขัดแย้งหรือไม่", + "auto_build_gate_quality_gate_passed": "นโยบายสร้างคำสั่งซื้ออัตโนมัติยังไม่อนุมัติรายการนี้ จึงต้องยืนยันด้วยตนเอง", + "unknown": "ระบบพบรายการที่ต้องยืนยันด้วยตนเอง" + }, "machineSource": "แหล่งที่มา: การระบุของระบบ", "manualSource": "แหล่งที่มา: แก้ไขโดยผู้ใช้", "derivedSource": "แหล่งที่มา: อนุมานจากกฎ", @@ -1470,10 +1495,11 @@ "compare": "เปรียบเทียบคำแนะนำ", "scope": "ขอบเขตหลักฐาน: {level}", "evidenceLevel": { - "L1_field": "ข้อความฟิลด์", + "L1_field": "ข้อมูลในฟิลด์ปัจจุบัน", "L2_table": "ตารางที่เกี่ยวข้อง", "L3_page": "หน้าที่เกี่ยวข้อง", - "L4_pdf": "PDF ทั้งฉบับ (ต้องได้รับอนุญาต)" + "L4_pdf": "PDF ทั้งฉบับ (ต้องได้รับอนุญาต)", + "unknown": "เนื้อหาเอกสารที่เกี่ยวข้อง" }, "review": "พิจารณา", "empty": "ยังไม่มีคำแนะนำ AI เลือกฟิลด์แล้วกดขอ", @@ -1493,7 +1519,8 @@ "accepted": "ยอมรับแล้ว", "modified": "แก้ไขแล้ว", "rejected": "ปฏิเสธแล้ว", - "failed": "ใช้ไม่ได้" + "failed": "ใช้ไม่ได้", + "unknown": "รอยืนยันสถานะ" }, "decisions": { "accept": "ยอมรับ", @@ -1524,7 +1551,7 @@ "other": "อื่นๆ" } }, - "restoreMachine": "คืนค่าเครื่อง", + "restoreMachine": "คืนค่าที่ระบบระบุ", "restorePriorProjection": "คืนค่าจากการระบุ/อนุมาน", "lineNoUnsavedHint": "ยังไม่บันทึก · กรอกเหตุผลเมื่อออกจากช่อง", "lockedHint": "ล็อกแล้ว", @@ -1600,9 +1627,19 @@ "manual_upload_pending": "รอลงทะเบียนอัปโหลด" } }, + "reparseProgress": { + "title": "ความคืบหน้าการรู้จำ PDF ใหม่", + "subtitle": "ความคืบหน้ามาจากรายการงานปัจจุบัน และจะเปิดแบบร่างตรวจทานเวอร์ชันใหม่โดยอัตโนมัติเมื่อพร้อม", + "polling": "กำลังรีเฟรชความคืบหน้าจริง…", + "refreshFailed": "ไม่สามารถรีเฟรชความคืบหน้าได้ชั่วคราว ระบบจะคงขั้นตอนล่าสุดและลองใหม่อัตโนมัติ", + "failed": "การรู้จำใหม่ยังไม่เสร็จสมบูรณ์ ระบบเก็บเวอร์ชันก่อนหน้าไว้และคุณสามารถลองรู้จำใหม่ได้ทันที", + "retry": "รู้จำใหม่อีกครั้ง", + "stages": { "submitted": "ส่งแล้ว", "layout_parsing": "กำลังอ่านเนื้อหาในหน้า", "extracting": "กำลังอ่านข้อมูลคำสั่งซื้อ", "draft_ready": "กำลังเตรียมข้อมูลตรวจสอบ" } + }, "backToSession": "กลับไปการประมวลผลครั้งนี้", "workItemHeader": "รายการงาน {itemNo} · {version}", "jumpToCurrentVersion": "ไปยังเวอร์ชันปัจจุบัน", + "currentVersionUnavailable": "เวอร์ชันปัจจุบันยังไม่พร้อมหรือยังรีเฟรชความคืบหน้าไม่ได้ โปรดลองอีกครั้งในภายหลัง", "showContext": "บริบทการสนทนา", "hideContext": "ซ่อนบริบท", "contextTitle": "บริบทการสนทนา", @@ -1614,7 +1651,8 @@ "work_item_closed": "รายการงานนี้ปิดแล้ว ดูได้อย่างเดียว การจัดการและการแก้ไขถูกปิดใช้งาน", "reparse_in_progress": "PDF นี้กำลังถูกระบุใหม่ โปรดรอให้เสร็จก่อนดำเนินการตรวจทานต่อ", "restored": "การระบุใหม่ล้มเหลวและกู้คืนเวอร์ชันก่อนหน้าแล้ว คุณสามารถแก้ไขต่อได้", - "draft_version_conflict": "เวอร์ชันฉบับร่างขัดแย้ง: การแก้ไขในเครื่องล้าสมัยแล้ว โปรดโหลดเวอร์ชันล่าสุดก่อนดำเนินการต่อ" + "draft_version_conflict": "เวอร์ชันฉบับร่างขัดแย้ง: การแก้ไขในเครื่องล้าสมัยแล้ว โปรดโหลดเวอร์ชันล่าสุดก่อนดำเนินการต่อ", + "unknown": "สถานะคำสั่งซื้อมีการเปลี่ยนแปลง โปรดรีเฟรชก่อนดำเนินการต่อ" }, "versionHistory": { "title": "ประวัติเวอร์ชัน", @@ -1626,31 +1664,33 @@ "open": "เปิด" }, "buildEligibility": { - "title": "คุณสมบัติการสร้างคำสั่ง", - "subtitle": "Reservation และการตรวจสอบแหล่งสต็อกหลังตรวจร่าง", + "title": "ตรวจสอบคำสั่งซื้อ", + "subtitle": "ตรวจสอบว่าข้อมูลคำสั่งซื้อและแหล่งสต็อกพร้อมสำหรับสร้างคำสั่งซื้อหรือไม่", "canBuildYes": "สร้างได้", "canBuildNo": "ยังสร้างไม่ได้", "statusLabel": "สถานะคุณสมบัติ", - "blockingSummary": "สรุปการบล็อก", - "lineProjections": "การฉายแถว", + "blockingSummary": "รายการที่ต้องดำเนินการ", + "lineProjections": "ผลตรวจสอบรายละเอียด", "lineCanBuild": "ผ่าน", - "lineBlocked": "ถูกบล็อก", - "reservation": "Reservation ที่ใช้ได้", - "routingStatusLabel": "สถานะการกำหนดเส้นทาง", + "lineBlocked": "ต้องดำเนินการ", + "reservation": "หมายเลขการจอง", + "routingStatusLabel": "สถานะแหล่งสต็อก", "sourceHint": "คำใบ้สต็อก", "candidates": "แหล่งสต็อกที่เป็นไปได้", - "blockReason": "เหตุผลการบล็อก", + "blockReason": "เหตุผลที่ต้องดำเนินการ", "manualReason": "เหตุผลด้วยตนเอง", "confirmBlocked": "ร่างยังไม่ผ่านคุณสมบัติการสร้างคำสั่ง โปรดแก้ปัญหาแหล่งสต็อกหรือการตรวจสอบก่อนยืนยัน", "status": { "ready": "พร้อมสร้าง", - "needs_review": "ต้องตรวจสอบ" + "needs_review": "ต้องตรวจสอบ", + "unknown": "รอยืนยัน" }, "routingStatus": { "resolved": "แก้ไขแล้ว", "ambiguous": "หลายตัวเลือก", "unresolved": "ยังไม่แก้", - "conflicted": "ต้องตรวจสอบด้วยตนเอง" + "conflicted": "ต้องยืนยันด้วยตนเอง", + "unknown": "รอยืนยัน" }, "blockReasons": { "require_manual_review": "กฎต้องตรวจสอบแหล่งสต็อกด้วยตนเอง", @@ -1658,20 +1698,33 @@ "manual_inventory_source_reason_required": "ต้องระบุเหตุผลการเลือกด้วยตนเอง", "manual_inventory_source_invalid": "แหล่งสต็อกที่เลือกไม่ถูกต้องหรือปิดใช้งาน", "inventory_source_unresolved": "ยังไม่ระบุแหล่งสต็อก", - "effective_reservation_missing": "ไม่มี Reservation ที่ใช้ได้" + "effective_reservation_missing": "ไม่มีหมายเลขการจองที่ถูกต้อง", + "unknown": "ระบบพบรายการที่ต้องยืนยันด้วยตนเอง" } }, "inventoryCandidates": { "title": "เลือกแหล่งสต็อกด้วยตนเอง", - "subtitle": "เลือกแหล่งสต็อกที่เปิดใช้งานอย่างน้อยหนึ่งแหล่งสำหรับแถวที่ยังไม่ชัดเจน พร้อมเหตุผล", + "subtitle": "เลือกแหล่งสต็อกที่เปิดใช้งานอย่างน้อยหนึ่งแหล่งสำหรับแถวที่ยังไม่ชัดเจน พร้อมเหตุผล หรือจับคู่กฎใหม่/จัดการคำแนะนำที่ค้างอยู่", "selectSources": "เลือกตัวเลือก", "selectEnabledSources": "เลือกจากแหล่งสต็อกที่เปิดใช้งาน", - "noCandidates": "ไม่มีแหล่งที่เลือกได้ ตรวจสอบกฎการกำหนดเส้นทางหรือติดต่อผู้ดูแล", + "noCandidates": "ไม่มีแหล่งสต็อกที่เลือกได้ โปรดติดต่อผู้ดูแลเพื่อตรวจสอบการตั้งค่า", "noEnabledSources": "ยังไม่มีแหล่งสต็อกที่เปิดใช้งาน กรุณาให้ผู้ดูแลเปิดใช้งานก่อน", "reasonLabel": "เหตุผล (จำเป็น)", "reasonPlaceholder": "อธิบายว่าทำไมจึงเลือกแหล่งสต็อกเหล่านี้...", "submit": "ส่งตัวเลือก" }, + "inventoryRouting": { + "reroute": "จับคู่เส้นทางใหม่", + "adoptSuggestion": "ใช้ผลจากกฎ", + "keepManual": "คงผลที่เลือกเอง", + "suggestionPending": "คำแนะนำจากกฎมีการอัปเดตและต่างจากผลที่เลือกเอง กรุณาใช้ผลจากกฎหรือคงผลที่เลือกเอง", + "rawCandidates": "ตัวเลือกดิบจากกฎ", + "unavailableCandidates": "ตัวเลือกที่ใช้ไม่ได้", + "ruleSuggestion": "แหล่งที่กฎแนะนำ", + "ruleVersions": "เวอร์ชันกฎ", + "hint": "คำใบ้แหล่งสต็อก", + "rerouteHint": "สามารถจับคู่กฎเส้นทางใหม่ได้ตลอดเวลา หากมีคำแนะนำค้างอยู่ ให้ตัดสินใจใช้ผลจากกฎหรือคงผลที่เลือกเองก่อน" + }, "confirmDialog": { "reasonLabel": "เหตุผล (จำเป็น)", "reasonPlaceholder": "อธิบายเหตุผลของการดำเนินการ...", @@ -1782,7 +1835,7 @@ }, "itemStatus": { "queued": "รอคิว", - "layout_parsing": "กำลังอ่านเลย์เอาต์", + "layout_parsing": "กำลังอ่านเนื้อหาในหน้า", "extracting": "กำลังดึงข้อมูล", "building_order": "กำลังสร้างออเดอร์", "inventory_matching": "กำลังจับคู่สต็อก", @@ -1792,7 +1845,8 @@ "failed": "ล้มเหลว", "closed": "เสร็จแล้ว", "cancelled": "ยกเลิกแล้ว", - "manual_upload_pending": "รอลงทะเบียนอัปโหลด" + "manual_upload_pending": "รอลงทะเบียนอัปโหลด", + "unknown": "รอยืนยันสถานะ" }, "closedReason": { "confirmed": "ยืนยันสร้างออเดอร์แล้ว", @@ -1802,11 +1856,21 @@ }, "actions": { "refresh": "รีเฟรช", + "openReview": "เปิดเวิร์กสเปซตรวจสอบ", "viewProgress": "ดูความคืบหน้า", "cancelFile": "ยกเลิกไฟล์นี้", "reparse": "ระบุใหม่", "retryFailedRun": "ลองรันที่ล้มเหลวอีกครั้ง" }, + "reparseError": { + "title": "การระบุใหม่ไม่เสร็จสมบูรณ์", + "schemaUnavailable": "ไม่สามารถใช้กฎฟิลด์คำสั่งซื้อเวอร์ชันปัจจุบัน จึงยังไม่มีผลการระบุใหม่", + "fallback": "ระบบเก็บเวอร์ชันเดิมไว้แล้ว โปรดเปิดเวิร์กสเปซตรวจสอบเพื่อจัดการด้วยตนเอง", + "contactAdmin": "หากเกิดกับหลายไฟล์ โปรดติดต่อผู้ดูแลระบบให้ตรวจสอบเวอร์ชันกฎฟิลด์คำสั่งซื้อ", + "pending": "ไฟล์นี้กำลังระบุใหม่อยู่ โปรดรอให้งานปัจจุบันเสร็จสิ้น", + "generic": "การระบุใหม่ไม่เสร็จสมบูรณ์ โปรดดูรายละเอียดหรือลองอีกครั้งภายหลัง", + "requestId": "รหัสคำขอ: {id}" + }, "reasonDialog": { "cancelTitle": "ยกเลิกไฟล์นี้", "reparseTitle": "ลองใหม่ / ระบุใหม่", @@ -1825,14 +1889,17 @@ "filename": "ชื่อไฟล์", "status": "สถานะ", "stage": "ขั้นตอน", - "runNo": "รอบดึงข้อมูล", - "caseNo": "เคสรีวิว", + "runNo": "ชุดการระบุข้อมูล", + "caseNo": "หมายเลขการตรวจสอบ", "lastActivity": "กิจกรรมล่าสุด", "closedReason": "เหตุผลที่ปิด", "eventsTitle": "ไทม์ไลน์เหตุการณ์", "eventsEmpty": "ยังไม่มีเหตุการณ์", "empty": "ยังไม่ได้เลือกไฟล์" }, - "versionHistoryNote": "API ประวัติเวอร์ชันฉบับเต็มยังไม่มี — แสดงเฉพาะเวอร์ชันปัจจุบัน" + "event": { + "unknown": "อัปเดตสถานะการประมวลผลแล้ว" + }, + "versionHistoryNote": "แสดงเวอร์ชันที่พร้อมใช้งานสำหรับไฟล์นี้" } } diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index 9cd547bf..41a4413a 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -248,7 +248,8 @@ "SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "การแยกข้อความใบแจ้งจัดส่งหมดเวลา โปรดลองใหม่หรือลบแล้วอัปโหลดใหม่", "SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "บันทึกอีเมลหรือไฟล์แนบที่ประมวลผลเบื้องต้นไม่สำเร็จ โปรดลองแยกข้อความใหม่", "SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "ไฟล์แนบใบแจ้งจัดส่งแยกข้อความไม่ครบ โปรดลองแยกใหม่หรือลบแล้วอัปโหลดใหม่", - "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "บันทึก intake ถูกใช้งานไปแล้ว", + "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "ไฟล์นี้เข้าสู่กระบวนการคำสั่งซื้อแล้ว โปรดดูผลลัพธ์เดิมโดยไม่ต้องส่งซ้ำ", + "SHIPPING_NOTICE_ORDER_EXTRACTION_ALREADY_CONSUMED": "ไฟล์นี้มีผลการประมวลผลคำสั่งซื้อแล้ว โปรดดูผลลัพธ์หรือใช้การรู้จำใหม่", "SHIPPING_NOTICE_INTAKE_EXPIRED": "บันทึก intake หมดอายุแล้ว", "SHIPPING_NOTICE_INTAKE_INVALID_STATUS": "สถานะ intake ปัจจุบันไม่อนุญาตการดำเนินการนี้", "SHIPPING_NOTICE_DUPLICATE_RESOLUTION_REQUIRED": "พบใบแจ้งจัดส่งซ้ำ กรุณาเลือกวิธีดำเนินการก่อน", @@ -370,6 +371,8 @@ "SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "ร่างถูกแก้ไขจากหน้าต่างอื่น โปรดรีเฟรชแล้วลองใหม่", "SHIPPING_REVIEW_FIELD_INVALID": "ฟิลด์ตรวจทานไม่อยู่ใน Schema ที่ตรึงไว้ของคำสั่งซื้อนี้", "SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "ตัวเลือกแหล่งสินค้าคงคลังไม่ถูกต้อง โปรดเลือกแหล่งที่เปิดใช้และระบุเหตุผล", + "SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "ไม่สามารถใช้คำแนะนำจากกฎได้ เพราะแถวนี้ไม่มีผลกฎที่ค้างอยู่ซึ่งถูกต้อง", + "SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "ไม่สามารถคงผลที่เลือกเองได้ เพราะแถวนี้ไม่มีคำแนะนำจากกฎที่ค้างอยู่", "SHIPPING_REVIEW_BUILD_ELIGIBILITY_BLOCKED": "คุณสมบัติการสร้างงานไม่ผ่าน โปรดแก้ปัญหาที่บล็อกหรือเติมแหล่งสินค้าคงคลังก่อนยืนยัน", "SHIPPING_REVIEW_LINE_NOT_FOUND": "ไม่พบรายการคำสั่งซื้อหรือรายการถูกลบแล้ว", "SHIPPING_REVIEW_DOCUMENT_NOT_FOUND": "ไม่พบ PDF สำหรับตรวจทานหรือไม่มีสิทธิ์เข้าถึง", @@ -397,6 +400,18 @@ "SHIPPING_REVIEW_QUALITY_COMMENT_REQUIRED": "ต้องระบุรายละเอียดเมื่อเลือกเหตุผลเป็น อื่นๆ", "SHIPPING_NOTICE_SESSION_WORK_ITEM_CLOSE_REASON_REQUIRED": "ต้องระบุเหตุผลเมื่อยกเลิกรายการงานนี้", "SHIPPING_NOTICE_SESSION_WORK_ITEM_LOCK_VERSION_INVALID": "หมายเลขเวอร์ชันรายการงานไม่ถูกต้อง โปรดรีเฟรชแล้วลองใหม่", - "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "รายการงานถูกอัปเดตโดยการดำเนินการอื่น โปรดรีเฟรชแล้วลองใหม่" + "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "รายการงานถูกอัปเดตโดยการดำเนินการอื่น โปรดรีเฟรชแล้วลองใหม่", + "SHIPPING.PROCESS_EXECUTION_NOT_FOUND": "ไม่พบ process execution", + "SHIPPING.PROCESS_GATE_NOT_FOUND": "ไม่พบ process gate", + "SHIPPING.PROCESS_GATE_ACTION_INVALID": "การกู้คืน process gate ไม่ถูกต้อง", + "SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN": "คำขอมีฟิลด์ควบคุมการทำงานที่ห้ามส่ง", + "SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED": "การกระทำนี้ไม่ใช่การกู้คืนหลักที่อนุญาตสำหรับ gate ปัจจุบัน", + "SHIPPING.PROCESS_GATE_VERSION_MISMATCH": "เวอร์ชัน gate เปลี่ยนแล้ว โปรดรีเฟรชแล้วลองใหม่", + "SHIPPING.PROCESS_GATE_BUSY": "gate กำลังทำงานอยู่ โปรดลองใหม่ภายหลัง", + "SHIPPING.PROCESS_GATE_ALREADY_PASSED": "gate นี้ผ่านแล้ว", + "SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND": "ไม่พบ process gate attempt", + "SHIPPING.PROCESS_GATE_PERMISSION_DENIED": "คุณไม่มีสิทธิ์เข้าถึงหรือกู้คืน gate นี้", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED": "คำขอกู้คืนไม่มี idempotency key", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT": "idempotency key ขัดแย้งกับคำขอ gate อื่น กรุณาใช้คีย์ใหม่แล้วลองอีกครั้ง" } } diff --git a/frontend/src/locales/th/workspace.json b/frontend/src/locales/th/workspace.json index 1ee14139..39a7c9ca 100644 --- a/frontend/src/locales/th/workspace.json +++ b/frontend/src/locales/th/workspace.json @@ -122,11 +122,57 @@ "adminViewOnlyShort": "ดูอย่างเดียว", "lastActivity": "กิจกรรมล่าสุด", "terminateReason": "เหตุผลยุติ", - "workflowItem": "Workflow Item", + "workflowItem": "รายการไฟล์", "downloadExcel": "ดาวน์โหลด Excel", "manualUploadEndNote": "สร้าง Excel แล้ว โปรดดาวน์โหลด อัปโหลดบนแพลตฟอร์มขนส่ง แล้วลงทะเบียนหลักฐานในระบบนี้", "waitingManualUploadNote": "สร้าง Excel แล้ว โปรดดาวน์โหลด อัปโหลดบนแพลตฟอร์มขนส่ง แล้วลงทะเบียนหลักฐานในระบบนี้" }, + "processGate": { + "title": "รายการที่ต้องดำเนินการ", + "currentGate": "ขั้นตอนปัจจุบัน", + "blockingMessage": "เหตุผลที่ต้องดำเนินการ", + "reasonCode": "เหตุผล", + "diagnosticHint": "คำแนะนำในการดำเนินการ", + "noAction": "ขณะนี้ไม่มีการดำเนินการที่ใช้ได้", + "versionMissing": "ข้อมูลนี้มีการเปลี่ยนแปลง โปรดรีเฟรชแล้วลองใหม่", + "navigationMissing": "ไม่มีข้อมูลสำหรับนำทาง โปรดรีเฟรชแล้วลองใหม่", + "genericBlocking": "ขั้นตอนนี้ต้องดำเนินการด้วยตนเอง", + "unknownStep": "ขั้นตอนปัจจุบัน", + "continueAction": "ดำเนินการต่อ", + "actionSubmitted": "ส่งการดำเนินการแล้ว", + "submitting": "กำลังส่ง…", + "actionCodes": { + "retry_with_latest_rules": "ลองใหม่ด้วยกฎล่าสุด", + "open_inventory_source_review": "เปิดการตรวจสอบแหล่งสต็อก", + "open_order_review": "เปิดการตรวจทานคำสั่งซื้อ", + "open_profile_review": "เปิดการตรวจทานโปรไฟล์", + "edit_order_fields": "แก้ไขฟิลด์คำสั่งซื้อ", + "confirm_customer": "ยืนยันลูกค้า", + "adjudicate_duplicate": "ตัดสินคำสั่งซื้อซ้ำ", + "resolve_field_conflicts": "แก้ไขความขัดแย้งฟิลด์", + "open_inventory_match_review": "เปิดการตรวจสอบการจับคู่สต็อก", + "open_shortage_review": "เปิดการตรวจสอบสินค้าขาด", + "upload_inventory_file": "อัปโหลดไฟล์สต็อก", + "adopt_rule_suggestion": "ยอมรับคำแนะนำกฎ", + "keep_manual_inventory_decision": "คงการตัดสินใจด้วยตนเอง", + "retry_task_creation": "ลองสร้างงานใหม่", + "retry_inventory_preparation": "ลองเตรียมสต็อกใหม่", + "regenerate_excel_artifact": "สร้าง Excel ใหม่", + "regenerate_manual_upload_todo": "สร้างงานอัปโหลดด้วยตนเองใหม่" + }, + "reasons": { + "freeze_not_ready": "คำสั่งซื้อยังไม่พร้อมสร้างหรือ freeze", + "profile_not_auto_freeze_approved": "โปรไฟล์เอกสารยังไม่ได้รับอนุมัติ auto build", + "profile_manual_confirmation_required": "โปรไฟล์เอกสารต้องยืนยันด้วยตนเอง", + "customer_unresolved": "ยังระบุลูกค้าไม่ได้", + "customer_ambiguous": "การระบุลูกค้ามีความคลุมเครือ", + "field_conflict": "ฟิลด์ขัดแย้ง ต้องตัดสินด้วยตนเอง", + "duplicate_unresolved": "คำสั่งซื้อซ้ำยังไม่ได้รับการแก้ไข", + "require_manual_review": "ต้องตรวจทานด้วยตนเอง", + "no_inventory_source_candidates": "ไม่พบแหล่งสต็อกที่ใช้ได้", + "inventory_source_unavailable": "แหล่งสต็อกไม่พร้อมใช้งาน" + } + }, "myTodos": { "title": "งานของฉัน", "subtitle": "รวมรายการรอบทบทวน ข้อยกเว้น และรอลงทะเบียนอัปโหลดด้วยตนเองข้ามเซสชัน", @@ -178,8 +224,28 @@ "empty": "ยังไม่มีเหตุการณ์", "detail": "ดูรายละเอียด", "sourceTask": "เหตุการณ์งาน", - "sourceWorkflow": "เหตุการณ์ Workflow", - "workflowEvent": "เหตุการณ์ Workflow" + "sourceWorkflow": "บันทึกการประมวลผลไฟล์", + "workflowEvent": "บันทึกการประมวลผลไฟล์", + "updated": "อัปเดตสถานะการประมวลผลแล้ว", + "actors": { + "user": "ผู้ใช้งานธุรกิจ", + "system": "ระบบ", + "admin": "ผู้ดูแลระบบ" + } + }, + "workflowStatus": { + "created": "สร้างแล้ว", + "queued": "รอดำเนินการ", + "extracting": "กำลังอ่านข้อมูล", + "pending_review": "รอตรวจสอบ", + "waiting_manual_upload": "รออัปโหลดด้วยตนเอง", + "failed": "ดำเนินการไม่สำเร็จ", + "completed": "เสร็จสิ้น", + "closed": "สิ้นสุดแล้ว" + }, + "workflowReasons": { + "user_cancelled": "ผู้ใช้ยกเลิกแล้ว", + "completed": "ดำเนินการเสร็จสิ้นแล้ว" }, "stpFacts": { "title": "ความคืบหน้า STP", diff --git a/frontend/src/locales/zh-CN/admin.json b/frontend/src/locales/zh-CN/admin.json index 80d0217f..e6bc85a2 100644 --- a/frontend/src/locales/zh-CN/admin.json +++ b/frontend/src/locales/zh-CN/admin.json @@ -40,7 +40,8 @@ "shippingIdentityRules": "客户识别", "shippingOrderExtractionRuns": "识别任务", "shippingOrderDocumentProfiles": "文档模板", - "shippingAudit": "运行与审计中心" + "shippingAudit": "运行与审计中心", + "shippingProcessGates": "门禁诊断" }, "shippingFieldAssets": { "title": "字段资产库", @@ -3690,5 +3691,81 @@ "chainTruncated": "(已截断)", "eventHash": "事件哈希", "previousEventHash": "前序哈希" + }, + "shippingProcessGates": { + "title": "Process Gate 诊断", + "subtitle": "只读查看 Execution 门禁轨道、阻断状态与 Attempt 历史,供运维排查恢复链路。", + "refresh": "刷新", + "loading": "加载中…", + "empty": "暂无 Execution", + "loadFailed": "加载 Execution 列表失败", + "detailFailed": "加载 Execution 详情失败", + "attemptsFailed": "加载 Attempt 失败", + "detailTitle": "Execution 诊断", + "executionNo": "Execution 编号", + "status": "状态", + "allStatuses": "全部状态", + "currentGate": "当前 Gate", + "nextAction": "主动作", + "updatedAt": "更新时间", + "actions": "操作", + "viewDetail": "查看详情", + "viewAttempts": "查看 Attempt", + "viewSnapshots": "查看输入/输出快照", + "total": "共 {count} 条", + "previous": "上一页", + "next": "下一页", + "gates": "Gate 轨道", + "gateCode": "Gate 编码", + "gateStatus": "Gate 状态", + "blockingReason": "阻断原因码", + "blockingReasonDetail": "阻断原因详情", + "gateDiagnostics": "当前 Gate 诊断", + "findings": "Findings", + "effectiveResult": "有效结果", + "attempts": "Attempt 列表", + "noAttempts": "暂无 Attempt", + "taskNo": "任务编号", + "caseNo": "复核 Case", + "scrollHint": "表格可左右滑动查看完整列", + "filterGate": "Gate 编码筛选", + "filterReason": "阻断原因码筛选", + "filterParty": "责任方筛选", + "filterSearch": "关键字搜索", + "filterFrom": "更新时间起", + "filterTo": "更新时间止", + "applyFilters": "应用筛选", + "resetFilters": "重置筛选", + "findingsStructured": "结构化 Findings", + "severity": "严重级别", + "field": "字段", + "party": "责任方", + "reason": "原因码", + "message": "说明", + "noFindings": "暂无 Finding", + "attemptDiff": "{scope}:新增 {added}、删除 {removed}、变更 {changed}", + "auditLink": "可在审计中心查看该 Execution 的 process_gate_ 事件", + "openAudit": "打开审计中心", + "responsibleParty": "责任方", + "blockingReasonCode": "阻断原因码", + "statusLabels": { + "active": "进行中", + "blocked": "已阻断", + "waiting_external": "等待外部", + "completed": "已完成", + "failed": "失败", + "cancelled": "已取消", + "pending": "待处理", + "queued": "已排队", + "running": "执行中", + "passed": "已通过", + "blocked_retryable": "可重试阻断", + "blocked_manual": "需人工处理", + "failed_terminal": "终态失败", + "invalidated": "已失效", + "skipped": "已跳过", + "succeeded": "成功", + "superseded": "已替代" + } } } diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index ba1e73e0..d674ee80 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -198,7 +198,7 @@ "nonOrderReasonPrompt": "请填写标记非订单的原因", "reparseReasonPrompt": "请填写重新识别的原因", "reasonRequired": "必须填写原因后才能继续", - "caseRequired": "当前工作项缺少复核 Case,请先进入人工复核", + "caseRequired": "当前文件尚未生成复核单,请稍后再进入人工复核", "versionHistoryTitle": "版本历史", "currentVersion": "当前", "readonlyVersion": "只读", @@ -378,7 +378,8 @@ "candidate_ready": "候选已生成", "review_required": "需要人工复核", "failed": "处理失败", - "cancelled": "已取消" + "cancelled": "已取消", + "unknown": "状态待确认" }, "shippingOrderExtractionReason": { "profile_not_found": "未找到适用的已发布订单模板。", @@ -429,12 +430,14 @@ "generic_deterministic": "通用规则确定性解析", "llm_assisted_review": "AI 辅助复核", "manual_review": "人工复核", - "rejected": "已拒识" + "rejected": "已拒识", + "unknown": "处理方式待确认" }, "shippingOrderExtractionFreezeSource": { "profile_deterministic": "自动冻结来源:异型模板", "generic_deterministic": "自动冻结来源:通用规则", - "manual_confirmation": "冻结来源:人工确认" + "manual_confirmation": "确认方式:人工确认", + "unknown": "确认方式待确认" }, "shippingOrderExtractionPlanSummary": "本轮从 {total} 个附件中规划 {groups} 个订单组,首轮最多识别 {attachments} 个附件,并发 {concurrency} 个。", "shippingOrderExtractionPlanSelected": "已选 {count} 个附件", @@ -473,7 +476,8 @@ }, "shippingOrderExtractionEmailSupplementRelation": { "po_mpn": "关联方式:PO + 料号", - "po_fallback": "关联方式:按 PO 回退" + "po_fallback": "关联方式:按 PO 匹配", + "unknown": "关联方式待确认" }, "shippingOrderExtractionEmailSupplementField": { "reservation": "Reservation:", @@ -1469,7 +1473,7 @@ "unknown": "状态未知" }, "previewTitle": "PDF 预览", - "buildGateRail": "建单资格与库存候选", + "buildGateRail": "订单检查与库存来源", "previewLoading": "正在加载 PDF 预览...", "previewUnavailable": "PDF 预览不可用,草稿编辑不受影响。", "previewCollapsed": "该证据只有页码和引文,没有可靠坐标;已收起 PDF 预览。", @@ -1480,15 +1484,36 @@ "viewEvidence": "查看证据", "locateSource": "定位原文:{field}", "orderFields": "订单字段", - "schemaVersion": "冻结 Schema #{version}", + "schemaVersion": "订单字段版本 V{version}", "issues": "待处理问题", - "machineSource": "来源:机器识别", + "issueCodes": { + "customer_unresolved": "客户信息尚未确认", + "machine_order_unavailable": "未识别到可复核的订单内容", + "machine_multiple_orders_legacy": "文件中可能包含多份订单,请人工确认", + "required_field_missing": "缺少创建订单所需的信息", + "field_value_invalid": "部分订单信息格式不正确", + "invalid_order_line": "部分订单明细不完整或格式不正确", + "effective_reservation_missing": "缺少有效的预约单号", + "reservation_duplicated_in_order": "订单内存在重复的预约单号", + "require_manual_review": "库存来源需要人工确认", + "no_inventory_source_candidates": "未找到可用的库存来源", + "manual_inventory_source_reason_required": "请选择库存来源并填写原因", + "manual_inventory_source_invalid": "所选库存来源当前不可用", + "inventory_source_unresolved": "库存来源尚未确定", + "auto_build_gate_approved_template": "该文件需要人工复核后创建订单", + "auto_build_gate_fields_complete": "请补全订单信息后继续", + "auto_build_gate_evidence_passed": "部分识别结果需要人工核对", + "auto_build_gate_no_conflict_or_duplicate": "请确认订单是否重复或存在信息冲突", + "auto_build_gate_quality_gate_passed": "自动建单策略尚未放行,需人工确认", + "unknown": "系统发现一项需要人工确认的内容" + }, + "machineSource": "来源:系统识别", "manualSource": "来源:人工修改", "derivedSource": "来源:规则派生", "overrideSource": "来源:人工覆盖(已锁定)", "skippedSource": "来源:派生跳过", "valueSources": { - "machine": "机器识别", + "machine": "系统识别", "manual": "人工修改", "manual_override": "人工覆盖", "derived": "规则派生", @@ -1504,10 +1529,11 @@ "compare": "对比建议", "scope": "证据范围:{level}", "evidenceLevel": { - "L1_field": "字段原文", + "L1_field": "当前字段内容", "L2_table": "所在表格", "L3_page": "所在页面", - "L4_pdf": "整份 PDF(需授权)" + "L4_pdf": "整份 PDF(需授权)", + "unknown": "相关文档内容" }, "review": "裁决", "empty": "尚无 AI 建议。选择字段后点击请求。", @@ -1527,7 +1553,8 @@ "accepted": "已接受", "modified": "已修改", "rejected": "已拒绝", - "failed": "不可用" + "failed": "不可用", + "unknown": "状态待确认" }, "decisions": { "accept": "接受", @@ -1558,7 +1585,7 @@ "other": "其他" } }, - "restoreMachine": "恢复机器值", + "restoreMachine": "恢复系统识别值", "restorePriorProjection": "恢复识别/派生值", "lineNoUnsavedHint": "未保存 · 失焦后填写覆盖原因", "lockedHint": "已锁定", @@ -1591,7 +1618,7 @@ "addLine": "新增行", "copyLine": "复制行", "deleteLine": "删除行", - "noMachineOrder": "机器识别结果待人工确认,可创建草稿进行修正。", + "noMachineOrder": "系统识别结果需要人工确认,可创建草稿进行修正。", "lines": "订单明细", "line": "第 {index} 行", "noLines": "未识别到订单明细。", @@ -1634,9 +1661,19 @@ "manual_upload_pending": "待人工上传登记" } }, + "reparseProgress": { + "title": "PDF 重新识别进度", + "subtitle": "进度来自当前工作项,完成后将自动打开新版复核草稿。", + "polling": "正在刷新真实进度…", + "refreshFailed": "暂时无法刷新进度,正在保留当前阶段并自动重试。", + "failed": "重新识别未完成,已保留上一版本。您可以直接再次识别。", + "retry": "重新识别", + "stages": { "submitted": "已提交", "layout_parsing": "读取页面内容", "extracting": "提取订单信息", "draft_ready": "准备复核内容" } + }, "backToSession": "返回本次处理", "workItemHeader": "工作项 {itemNo} · {version}", "jumpToCurrentVersion": "跳转当前版本", + "currentVersionUnavailable": "当前版本尚未生成或进度暂时无法刷新,请稍后重试。", "showContext": "对话上下文", "hideContext": "收起对话上下文", "contextTitle": "对话上下文", @@ -1649,6 +1686,7 @@ "reparse_in_progress": "此 PDF 正在重新识别,请等待完成后继续复核。", "restored": "重识别失败已恢复上一版本,可继续编辑。", "draft_version_conflict": "草稿版本冲突:本地编辑已过期,请重新加载最新版本后再继续。" + ,"unknown": "订单状态已更新,请刷新后继续处理。" }, "versionHistory": { "title": "版本历史", @@ -1660,31 +1698,33 @@ "open": "打开" }, "buildEligibility": { - "title": "建单资格", - "subtitle": "校验草稿后汇总的 Reservation 与库存源门禁。", + "title": "订单检查", + "subtitle": "检查订单信息和库存来源是否满足创建条件。", "canBuildYes": "可建单", "canBuildNo": "暂不可建单", "statusLabel": "资格状态", - "blockingSummary": "阻断摘要", - "lineProjections": "明细投影", + "blockingSummary": "需要处理", + "lineProjections": "明细检查结果", "lineCanBuild": "可建单", - "lineBlocked": "阻断", - "reservation": "有效 Reservation", - "routingStatusLabel": "路由状态", + "lineBlocked": "需要处理", + "reservation": "预约单号", + "routingStatusLabel": "库存来源状态", "sourceHint": "库存线索", "candidates": "候选库存源", - "blockReason": "阻断原因", + "blockReason": "需要处理的原因", "manualReason": "人工说明", "confirmBlocked": "当前草稿未满足建单资格,请先处理库存源或校验问题后再确认。", "status": { "ready": "可建单", - "needs_review": "待复核" + "needs_review": "待复核", + "unknown": "待确认" }, "routingStatus": { "resolved": "已解析", "ambiguous": "多候选", "unresolved": "未解析", - "conflicted": "需人工复核" + "conflicted": "需人工确认", + "unknown": "待确认" }, "blockReasons": { "require_manual_review": "规则要求人工复核库存源", @@ -1692,20 +1732,33 @@ "manual_inventory_source_reason_required": "须填写人工选源原因", "manual_inventory_source_invalid": "所选库存源无效或未启用", "inventory_source_unresolved": "库存源未解析", - "effective_reservation_missing": "缺少有效 Reservation" + "effective_reservation_missing": "缺少有效的预约单号", + "unknown": "系统发现一项需要人工确认的内容" } }, "inventoryCandidates": { "title": "人工选择库存源", - "subtitle": "为未决明细选择一个或多个已启用库存源,并说明原因。", + "subtitle": "为未决明细选择一个或多个已启用库存源,并说明原因;也可重新匹配规则或处理待决建议。", "selectSources": "选择候选源", "selectEnabledSources": "从已启用库存源中选择", - "noCandidates": "暂无可选库存源,请检查路由规则或联系管理员。", + "noCandidates": "暂无可选库存来源,请联系管理员检查相关配置。", "noEnabledSources": "系统中没有已启用的库存源,请联系管理员启用后再选择。", "reasonLabel": "选择原因(必填)", "reasonPlaceholder": "请说明为何选择这些库存源...", "submit": "提交候选" }, + "inventoryRouting": { + "reroute": "重新匹配路由", + "adoptSuggestion": "采用规则结果", + "keepManual": "保留人工结果", + "suggestionPending": "规则建议与当前人工结果不一致,请选择采用或保留。", + "rawCandidates": "规则原始候选", + "unavailableCandidates": "不可用候选", + "ruleSuggestion": "规则建议源", + "ruleVersions": "规则版本", + "hint": "库存源提示", + "rerouteHint": "可随时重新匹配路由;若存在待决规则建议,请选择采用或保留人工结果。" + }, "confirmDialog": { "reasonLabel": "原因(必填)", "reasonPlaceholder": "请说明操作原因...", @@ -1734,7 +1787,7 @@ "reasonCodeRequired": "请选择原因类型", "quality_issue": { "title": "标记文件质量异常", - "impact": "保留当前 PDF、草稿与机器识别结果,供补件或重新识别;须选择原因并在选择「其他」时填写说明。", + "impact": "保留当前 PDF、草稿与系统识别结果,供补件或重新识别;须选择原因并在选择「其他」时填写说明。", "confirm": "确认标记" }, "qualityReasons": { @@ -1782,7 +1835,7 @@ }, "itemStatus": { "queued": "排队中", - "layout_parsing": "版面解析中", + "layout_parsing": "读取页面内容中", "extracting": "识别中", "building_order": "建单中", "inventory_matching": "库存匹配中", @@ -1792,7 +1845,8 @@ "failed": "失败", "closed": "已完成", "cancelled": "已取消", - "manual_upload_pending": "待人工上传登记" + "manual_upload_pending": "待人工上传登记", + "unknown": "状态待确认" }, "closedReason": { "confirmed": "已确认建单", @@ -1802,11 +1856,21 @@ }, "actions": { "refresh": "刷新", + "openReview": "进入复核工作台", "viewProgress": "查看进度", "cancelFile": "取消此文件", "reparse": "重新识别", "retryFailedRun": "重试失败识别" }, + "reparseError": { + "title": "重新识别未完成", + "schemaUnavailable": "当前订单字段规则版本不可用,系统没有生成新的识别结果。", + "fallback": "原有识别版本已保留,建议进入复核工作台人工处理。", + "contactAdmin": "如果多个文件同时出现此问题,请联系管理员检查订单字段规则版本。", + "pending": "该文件正在重新识别,请等待当前任务完成后再操作。", + "generic": "重新识别未完成,请查看处理详情或稍后重试。", + "requestId": "处理编号:{id}" + }, "reasonDialog": { "cancelTitle": "取消此文件", "reparseTitle": "重试/重新识别", @@ -1825,14 +1889,17 @@ "filename": "文件名", "status": "状态", "stage": "阶段", - "runNo": "抽取 Run", - "caseNo": "复核 Case", + "runNo": "识别批次", + "caseNo": "复核编号", "lastActivity": "最近活动", "closedReason": "关闭原因", "eventsTitle": "事件时间线", "eventsEmpty": "暂无事件记录", "empty": "未选择文件" }, + "event": { + "unknown": "处理状态已更新" + }, "versionHistoryNote": "完整版本历史待后端接口补齐;当前仅展示工作项最新版本。" } } diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index 45fb5f1f..14751e2c 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -248,7 +248,8 @@ "SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "发货通知解析超时,请重试或移除后重新上传。", "SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "发货通知正文或附件预处理保存失败,请重试解析。", "SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "发货通知附件解析不完整,请重试解析或移除后重新上传。", - "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "发货通知接入记录已被消费。", + "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "该文件已进入订单处理,请查看现有处理结果,无需重复提交。", + "SHIPPING_NOTICE_ORDER_EXTRACTION_ALREADY_CONSUMED": "该文件已完成一次订单处理,请查看现有结果或使用重新识别。", "SHIPPING_NOTICE_INTAKE_EXPIRED": "发货通知接入记录已过期。", "SHIPPING_NOTICE_INTAKE_INVALID_STATUS": "当前接入状态不允许该操作。", "SHIPPING_NOTICE_DUPLICATE_RESOLUTION_REQUIRED": "检测到重复发货通知,请先选择处理方式。", @@ -370,6 +371,8 @@ "SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "草稿已被其他窗口更新,请刷新后重试。", "SHIPPING_REVIEW_FIELD_INVALID": "复核字段不属于该订单的冻结模板。", "SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "人工库存源候选无效:请选择已启用的库存源并填写原因。", + "SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "无法采用规则建议:当前行没有有效的待决规则结果。", + "SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "无法保留人工结果:当前行没有待决的规则建议。", "SHIPPING_REVIEW_BUILD_ELIGIBILITY_BLOCKED": "建单资格未通过,请先处理阻断问题或补齐库存源候选后再确认。", "SHIPPING_REVIEW_LINE_NOT_FOUND": "订单明细行不存在或已被删除。", "SHIPPING_REVIEW_DOCUMENT_NOT_FOUND": "复核 PDF 不存在或无权访问。", @@ -397,6 +400,18 @@ "SHIPPING_REVIEW_QUALITY_COMMENT_REQUIRED": "选择「其他」时必须填写质量异常说明。", "SHIPPING_NOTICE_SESSION_WORK_ITEM_CLOSE_REASON_REQUIRED": "取消本次处理必须填写原因。", "SHIPPING_NOTICE_SESSION_WORK_ITEM_LOCK_VERSION_INVALID": "工作项版本号无效,请刷新后重试。", - "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "工作项已被其他操作更新,请刷新后重试。" + "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "工作项已被其他操作更新,请刷新后重试。", + "SHIPPING.PROCESS_EXECUTION_NOT_FOUND": "未找到流程执行实例。", + "SHIPPING.PROCESS_GATE_NOT_FOUND": "未找到门禁实例。", + "SHIPPING.PROCESS_GATE_ACTION_INVALID": "门禁恢复动作无效。", + "SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN": "请求包含禁止提交的执行控制字段。", + "SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED": "该动作不是当前门禁允许的主要恢复动作。", + "SHIPPING.PROCESS_GATE_VERSION_MISMATCH": "门禁版本已变更,请刷新后重试。", + "SHIPPING.PROCESS_GATE_BUSY": "门禁正在执行中,请稍后再试。", + "SHIPPING.PROCESS_GATE_ALREADY_PASSED": "该门禁已通过,无需重复恢复。", + "SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND": "未找到门禁执行尝试。", + "SHIPPING.PROCESS_GATE_PERMISSION_DENIED": "无权访问或恢复该门禁。", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED": "恢复请求缺少幂等键。", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT": "幂等键与其他门禁请求冲突,请使用新的幂等键后重试。" } } diff --git a/frontend/src/locales/zh-CN/workspace.json b/frontend/src/locales/zh-CN/workspace.json index cd1547b7..120def6d 100644 --- a/frontend/src/locales/zh-CN/workspace.json +++ b/frontend/src/locales/zh-CN/workspace.json @@ -182,11 +182,57 @@ "adminViewOnlyShort": "只读", "lastActivity": "最后活动", "terminateReason": "终止原因", - "workflowItem": "Workflow Item", + "workflowItem": "文件处理项", "downloadExcel": "下载发货 Excel", "manualUploadEndNote": "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", "waitingManualUploadNote": "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。" }, + "processGate": { + "title": "待处理事项", + "currentGate": "当前处理环节", + "blockingMessage": "需要处理的原因", + "reasonCode": "处理原因", + "diagnosticHint": "处理建议", + "noAction": "当前没有可执行的处理操作", + "versionMissing": "当前信息已更新,请刷新后重试", + "navigationMissing": "缺少跳转所需的任务或复核信息,请刷新后重试", + "genericBlocking": "当前步骤需要人工处理", + "unknownStep": "当前步骤", + "continueAction": "继续处理", + "actionSubmitted": "操作已提交", + "submitting": "提交中…", + "actionCodes": { + "retry_with_latest_rules": "按最新规则重试", + "open_inventory_source_review": "打开库存源复核", + "open_order_review": "打开订单复核", + "open_profile_review": "打开模板复核", + "edit_order_fields": "编辑订单字段", + "confirm_customer": "确认客户", + "adjudicate_duplicate": "处理重复订单", + "resolve_field_conflicts": "解决字段冲突", + "open_inventory_match_review": "打开库存匹配复核", + "open_shortage_review": "打开缺货复核", + "upload_inventory_file": "上传库存文件", + "adopt_rule_suggestion": "采用规则建议", + "keep_manual_inventory_decision": "保留人工决定", + "retry_task_creation": "重试创建任务", + "retry_inventory_preparation": "重试库存准备", + "regenerate_excel_artifact": "重新生成 Excel", + "regenerate_manual_upload_todo": "重新生成待上传待办" + }, + "reasons": { + "freeze_not_ready": "订单尚未满足建单/冻结条件", + "profile_not_auto_freeze_approved": "文档模板未通过自动建单审批", + "profile_manual_confirmation_required": "文档模板需要人工确认", + "customer_unresolved": "客户尚未识别", + "customer_ambiguous": "客户识别存在歧义", + "field_conflict": "字段存在冲突,需人工裁决", + "duplicate_unresolved": "重复订单尚未处理", + "require_manual_review": "需要人工复核", + "no_inventory_source_candidates": "未找到可用库存源", + "inventory_source_unavailable": "库存源不可用" + } + }, "myTodos": { "title": "我的待办", "subtitle": "跨会话聚合待复核、异常与待人工上传登记事项。", @@ -238,8 +284,28 @@ "empty": "暂无事件记录", "detail": "查看详情", "sourceTask": "任务事件", - "sourceWorkflow": "Workflow 事件", - "workflowEvent": "Workflow 事件" + "sourceWorkflow": "文件处理记录", + "workflowEvent": "文件处理记录", + "updated": "处理状态已更新", + "actors": { + "user": "业务人员", + "system": "系统", + "admin": "管理员" + } + }, + "workflowStatus": { + "created": "已创建", + "queued": "等待处理", + "extracting": "正在识别", + "pending_review": "待复核", + "waiting_manual_upload": "待人工上传", + "failed": "处理失败", + "completed": "已完成", + "closed": "已结束" + }, + "workflowReasons": { + "user_cancelled": "已由用户取消", + "completed": "处理已完成" }, "stpFacts": { "title": "STP 履约进度", diff --git a/frontend/src/locales/zh-TW/admin.json b/frontend/src/locales/zh-TW/admin.json index 647686f8..6970a30e 100644 --- a/frontend/src/locales/zh-TW/admin.json +++ b/frontend/src/locales/zh-TW/admin.json @@ -39,7 +39,8 @@ "shippingOrderDocumentProfiles": "文件範本", "shippingFieldAssets": "欄位資產庫", "shippingOrderSchema": "訂單 Schema", - "shippingAudit": "運行與稽核中心" + "shippingAudit": "運行與稽核中心", + "shippingProcessGates": "門禁診斷" }, "shippingOrderExtractionRuns": { "eyebrow": "唯讀執行診斷", @@ -3580,5 +3581,81 @@ "chainTruncated": "(已截斷)", "eventHash": "事件雜湊", "previousEventHash": "前序雜湊" + }, + "shippingProcessGates": { + "title": "Process Gate 診斷", + "subtitle": "唯讀檢視 Execution 門禁軌道、阻斷狀態與 Attempt 歷史,供維運排查恢復鏈路。", + "refresh": "重新整理", + "loading": "載入中…", + "empty": "暫無 Execution", + "loadFailed": "載入 Execution 列表失敗", + "detailFailed": "載入 Execution 詳情失敗", + "attemptsFailed": "載入 Attempt 失敗", + "detailTitle": "Execution 診斷", + "executionNo": "Execution 編號", + "status": "狀態", + "allStatuses": "全部狀態", + "currentGate": "當前 Gate", + "nextAction": "主動作", + "updatedAt": "更新時間", + "actions": "操作", + "viewDetail": "檢視詳情", + "viewAttempts": "檢視 Attempt", + "viewSnapshots": "檢視輸入/輸出快照", + "total": "共 {count} 條", + "previous": "上一頁", + "next": "下一頁", + "gates": "Gate 軌道", + "gateCode": "Gate 編碼", + "gateStatus": "Gate 狀態", + "blockingReason": "阻斷原因碼", + "blockingReasonDetail": "阻斷原因詳情", + "gateDiagnostics": "目前 Gate 診斷", + "findings": "Findings", + "effectiveResult": "有效結果", + "attempts": "Attempt 列表", + "noAttempts": "暫無 Attempt", + "taskNo": "任務編號", + "caseNo": "覆核 Case", + "scrollHint": "表格可左右滑動查看完整欄位", + "filterGate": "Gate 編碼篩選", + "filterReason": "阻斷原因碼篩選", + "filterParty": "責任方篩選", + "filterSearch": "關鍵字搜尋", + "filterFrom": "更新時間起", + "filterTo": "更新時間止", + "applyFilters": "套用篩選", + "resetFilters": "重設篩選", + "findingsStructured": "結構化 Findings", + "severity": "嚴重級別", + "field": "欄位", + "party": "責任方", + "reason": "原因碼", + "message": "說明", + "noFindings": "暫無 Finding", + "attemptDiff": "{scope}:新增 {added}、刪除 {removed}、變更 {changed}", + "auditLink": "可在審計中心檢視該 Execution 的 process_gate_ 事件", + "openAudit": "開啟審計中心", + "responsibleParty": "責任方", + "blockingReasonCode": "阻斷原因碼", + "statusLabels": { + "active": "進行中", + "blocked": "已阻斷", + "waiting_external": "等待外部", + "completed": "已完成", + "failed": "失敗", + "cancelled": "已取消", + "pending": "待處理", + "queued": "已排隊", + "running": "執行中", + "passed": "已通過", + "blocked_retryable": "可重試阻斷", + "blocked_manual": "需人工處理", + "failed_terminal": "終態失敗", + "invalidated": "已失效", + "skipped": "已跳過", + "succeeded": "成功", + "superseded": "已替代" + } } } diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index 3f69a85e..4dd08c65 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -198,7 +198,7 @@ "nonOrderReasonPrompt": "請填寫標記非訂單的原因", "reparseReasonPrompt": "請填寫重新識別的原因", "reasonRequired": "必須填寫原因後才能繼續", - "caseRequired": "目前工作項缺少覆核 Case,請先進入人工覆核", + "caseRequired": "目前檔案尚未產生複核單,請稍後再進入人工複核", "versionHistoryTitle": "版本歷史", "currentVersion": "目前", "readonlyVersion": "唯讀", @@ -344,7 +344,8 @@ "candidate_ready": "候選已生成", "review_required": "需要人工覆核", "failed": "處理失敗", - "cancelled": "已取消" + "cancelled": "已取消", + "unknown": "狀態待確認" }, "shippingOrderExtractionReason": { "profile_not_found": "未找到適用的已發佈訂單模板。", @@ -395,12 +396,14 @@ "generic_deterministic": "通用規則確定性解析", "llm_assisted_review": "AI 輔助複核", "manual_review": "人工複核", - "rejected": "已拒識" + "rejected": "已拒識", + "unknown": "處理方式待確認" }, "shippingOrderExtractionFreezeSource": { "profile_deterministic": "自動凍結來源:異型模板", "generic_deterministic": "自動凍結來源:通用規則", - "manual_confirmation": "凍結來源:人工確認" + "manual_confirmation": "確認方式:人工確認", + "unknown": "確認方式待確認" }, "shippingOrderExtractionPlanSummary": "本輪從 {total} 個附件中規劃 {groups} 個訂單組,首輪最多識別 {attachments} 個附件,並發 {concurrency} 個。", "shippingOrderExtractionPlanSelected": "已選 {count} 個附件", @@ -439,7 +442,8 @@ }, "shippingOrderExtractionEmailSupplementRelation": { "po_mpn": "關聯方式:PO + 料號", - "po_fallback": "關聯方式:依 PO 回退" + "po_fallback": "關聯方式:依 PO 配對", + "unknown": "關聯方式待確認" }, "shippingOrderExtractionEmailSupplementField": { "reservation": "Reservation:", @@ -1435,7 +1439,7 @@ "unknown": "狀態未知" }, "previewTitle": "PDF 預覽", - "buildGateRail": "建單資格與庫存候選", + "buildGateRail": "訂單檢查與庫存來源", "previewLoading": "正在載入 PDF 預覽...", "previewUnavailable": "PDF 預覽不可用,草稿編輯不受影響。", "previewCollapsed": "此證據只有頁碼和引文,沒有可靠座標;已收起 PDF 預覽。", @@ -1446,15 +1450,36 @@ "viewEvidence": "查看證據", "locateSource": "定位原文:{field}", "orderFields": "訂單欄位", - "schemaVersion": "凍結 Schema #{version}", + "schemaVersion": "訂單欄位版本 V{version}", "issues": "待處理問題", - "machineSource": "來源:機器識別", + "issueCodes": { + "customer_unresolved": "客戶資訊尚未確認", + "machine_order_unavailable": "未識別到可複核的訂單內容", + "machine_multiple_orders_legacy": "檔案中可能包含多份訂單,請人工確認", + "required_field_missing": "缺少建立訂單所需的資訊", + "field_value_invalid": "部分訂單資訊格式不正確", + "invalid_order_line": "部分訂單明細不完整或格式不正確", + "effective_reservation_missing": "缺少有效的預約單號", + "reservation_duplicated_in_order": "訂單內存在重複的預約單號", + "require_manual_review": "庫存來源需要人工確認", + "no_inventory_source_candidates": "未找到可用的庫存來源", + "manual_inventory_source_reason_required": "請選擇庫存來源並填寫原因", + "manual_inventory_source_invalid": "所選庫存來源目前不可用", + "inventory_source_unresolved": "庫存來源尚未確定", + "auto_build_gate_approved_template": "此檔案需要人工複核後建立訂單", + "auto_build_gate_fields_complete": "請補全訂單資訊後繼續", + "auto_build_gate_evidence_passed": "部分識別結果需要人工核對", + "auto_build_gate_no_conflict_or_duplicate": "請確認訂單是否重複或存在資訊衝突", + "auto_build_gate_quality_gate_passed": "自動建單策略尚未放行,需人工確認", + "unknown": "系統發現一項需要人工確認的內容" + }, + "machineSource": "來源:系統識別", "manualSource": "來源:人工修改", "derivedSource": "來源:規則派生", "overrideSource": "來源:人工覆蓋(已鎖定)", "skippedSource": "來源:派生跳過", "valueSources": { - "machine": "機器識別", + "machine": "系統識別", "manual": "人工修改", "manual_override": "人工覆蓋", "derived": "規則派生", @@ -1470,10 +1495,11 @@ "compare": "對比建議", "scope": "證據範圍:{level}", "evidenceLevel": { - "L1_field": "欄位原文", + "L1_field": "目前欄位內容", "L2_table": "所在表格", "L3_page": "所在頁面", - "L4_pdf": "整份 PDF(需授權)" + "L4_pdf": "整份 PDF(需授權)", + "unknown": "相關文件內容" }, "review": "裁決", "empty": "尚無 AI 建議。選擇欄位後點擊請求。", @@ -1493,7 +1519,8 @@ "accepted": "已接受", "modified": "已修改", "rejected": "已拒絕", - "failed": "不可用" + "failed": "不可用", + "unknown": "狀態待確認" }, "decisions": { "accept": "接受", @@ -1524,7 +1551,7 @@ "other": "其他" } }, - "restoreMachine": "恢復機器值", + "restoreMachine": "恢復系統識別值", "restorePriorProjection": "恢復識別/派生值", "lineNoUnsavedHint": "未儲存 · 失焦後填寫覆蓋原因", "lockedHint": "已鎖定", @@ -1557,7 +1584,7 @@ "addLine": "新增行", "copyLine": "複製行", "deleteLine": "刪除行", - "noMachineOrder": "機器識別結果待人工確認,可建立草稿進行修正。", + "noMachineOrder": "系統識別結果需要人工確認,可建立草稿進行修正。", "lines": "訂單明細", "line": "第 {index} 行", "noLines": "未識別到訂單明細。", @@ -1600,9 +1627,19 @@ "manual_upload_pending": "待人工上傳登記" } }, + "reparseProgress": { + "title": "PDF 重新識別進度", + "subtitle": "進度來自目前工作項,完成後將自動開啟新版複核草稿。", + "polling": "正在重新整理實際進度…", + "refreshFailed": "暫時無法重新整理進度,將保留目前階段並自動重試。", + "failed": "重新識別未完成,已保留上一版本。您可以直接再次識別。", + "retry": "重新識別", + "stages": { "submitted": "已提交", "layout_parsing": "讀取頁面內容", "extracting": "提取訂單資訊", "draft_ready": "準備複核內容" } + }, "backToSession": "返回本次處理", "workItemHeader": "工作項 {itemNo} · {version}", "jumpToCurrentVersion": "跳轉目前版本", + "currentVersionUnavailable": "目前版本尚未產生或進度暫時無法重新整理,請稍後重試。", "showContext": "對話上下文", "hideContext": "收起對話上下文", "contextTitle": "對話上下文", @@ -1614,7 +1651,8 @@ "work_item_closed": "此工作項已關閉,僅可唯讀追溯;處置與編輯已停用。", "reparse_in_progress": "此 PDF 正在重新識別,請等待完成後繼續覆核。", "restored": "重識別失敗已恢復上一版本,可繼續編輯。", - "draft_version_conflict": "草稿版本衝突:本機編輯已過期,請重新載入最新版本後再繼續。" + "draft_version_conflict": "草稿版本衝突:本機編輯已過期,請重新載入最新版本後再繼續。", + "unknown": "訂單狀態已更新,請重新整理後繼續處理。" }, "versionHistory": { "title": "版本歷史", @@ -1626,31 +1664,33 @@ "open": "開啟" }, "buildEligibility": { - "title": "建單資格", - "subtitle": "校驗草稿後彙總的 Reservation 與庫存源門禁。", + "title": "訂單檢查", + "subtitle": "檢查訂單資訊和庫存來源是否符合建立條件。", "canBuildYes": "可建單", "canBuildNo": "暫不可建單", "statusLabel": "資格狀態", - "blockingSummary": "阻斷摘要", - "lineProjections": "明細投影", + "blockingSummary": "需要處理", + "lineProjections": "明細檢查結果", "lineCanBuild": "可建單", - "lineBlocked": "阻斷", - "reservation": "有效 Reservation", - "routingStatusLabel": "路由狀態", + "lineBlocked": "需要處理", + "reservation": "預約單號", + "routingStatusLabel": "庫存來源狀態", "sourceHint": "庫存線索", "candidates": "候選庫存源", - "blockReason": "阻斷原因", + "blockReason": "需要處理的原因", "manualReason": "人工說明", "confirmBlocked": "目前草稿未滿足建單資格,請先處理庫存源或校驗問題後再確認。", "status": { "ready": "可建單", - "needs_review": "待複核" + "needs_review": "待複核", + "unknown": "待確認" }, "routingStatus": { "resolved": "已解析", "ambiguous": "多候選", "unresolved": "未解析", - "conflicted": "需人工複核" + "conflicted": "需人工確認", + "unknown": "待確認" }, "blockReasons": { "require_manual_review": "規則要求人工複核庫存源", @@ -1658,20 +1698,33 @@ "manual_inventory_source_reason_required": "須填寫人工選源原因", "manual_inventory_source_invalid": "所選庫存源無效或未啟用", "inventory_source_unresolved": "庫存源未解析", - "effective_reservation_missing": "缺少有效 Reservation" + "effective_reservation_missing": "缺少有效的預約單號", + "unknown": "系統發現一項需要人工確認的內容" } }, "inventoryCandidates": { "title": "人工選擇庫存源", - "subtitle": "為未決明細選擇一個或多個已啟用庫存源,並說明原因。", + "subtitle": "為未決明細選擇一個或多個已啟用庫存源,並說明原因;亦可重新匹配規則或處理待決建議。", "selectSources": "選擇候選源", "selectEnabledSources": "從已啟用庫存源中選擇", - "noCandidates": "暫無可選庫存源,請檢查路由規則或聯絡管理員。", + "noCandidates": "暫無可選庫存來源,請聯絡管理員檢查相關設定。", "noEnabledSources": "系統中沒有已啟用的庫存源,請聯絡管理員啟用後再選擇。", "reasonLabel": "選擇原因(必填)", "reasonPlaceholder": "請說明為何選擇這些庫存源...", "submit": "提交候選" }, + "inventoryRouting": { + "reroute": "重新匹配路由", + "adoptSuggestion": "採用規則結果", + "keepManual": "保留人工結果", + "suggestionPending": "規則建議與目前人工結果不一致,請選擇採用或保留。", + "rawCandidates": "規則原始候選", + "unavailableCandidates": "不可用候選", + "ruleSuggestion": "規則建議源", + "ruleVersions": "規則版本", + "hint": "庫存源提示", + "rerouteHint": "可隨時重新匹配路由;若存在待決規則建議,請選擇採用或保留人工結果。" + }, "confirmDialog": { "reasonLabel": "原因(必填)", "reasonPlaceholder": "請說明操作原因...", @@ -1700,7 +1753,7 @@ "reasonCodeRequired": "請選擇原因類型", "quality_issue": { "title": "標記檔案品質異常", - "impact": "保留目前 PDF、草稿與機器識別結果,供補件或重新識別;須選擇原因並在選擇「其他」時填寫說明。", + "impact": "保留目前 PDF、草稿與系統識別結果,供補件或重新識別;須選擇原因並在選擇「其他」時填寫說明。", "confirm": "確認標記" }, "qualityReasons": { @@ -1782,7 +1835,7 @@ }, "itemStatus": { "queued": "排隊中", - "layout_parsing": "版面解析中", + "layout_parsing": "讀取頁面內容中", "extracting": "識別中", "building_order": "建單中", "inventory_matching": "庫存匹配中", @@ -1792,7 +1845,8 @@ "failed": "失敗", "closed": "已完成", "cancelled": "已取消", - "manual_upload_pending": "待人工上傳登記" + "manual_upload_pending": "待人工上傳登記", + "unknown": "狀態待確認" }, "closedReason": { "confirmed": "已確認建單", @@ -1802,11 +1856,21 @@ }, "actions": { "refresh": "重新整理", + "openReview": "進入複核工作台", "viewProgress": "查看進度", "cancelFile": "取消此檔案", "reparse": "重新識別", "retryFailedRun": "重試失敗識別" }, + "reparseError": { + "title": "重新識別未完成", + "schemaUnavailable": "目前訂單欄位規則版本不可用,系統未產生新的識別結果。", + "fallback": "原有識別版本已保留,建議進入複核工作台人工處理。", + "contactAdmin": "若多個檔案同時出現此問題,請聯絡管理員檢查訂單欄位規則版本。", + "pending": "此檔案正在重新識別,請等待目前任務完成後再操作。", + "generic": "重新識別未完成,請查看處理詳情或稍後重試。", + "requestId": "處理編號:{id}" + }, "reasonDialog": { "cancelTitle": "取消此檔案", "reparseTitle": "重試/重新識別", @@ -1825,14 +1889,17 @@ "filename": "檔名", "status": "狀態", "stage": "階段", - "runNo": "抽取 Run", - "caseNo": "覆核 Case", + "runNo": "識別批次", + "caseNo": "複核編號", "lastActivity": "最近活動", "closedReason": "關閉原因", "eventsTitle": "事件時間線", "eventsEmpty": "暫無事件記錄", "empty": "未選擇檔案" }, - "versionHistoryNote": "完整版本歷史待後端介面補齊;目前僅顯示工作項最新版本。" + "event": { + "unknown": "處理狀態已更新" + }, + "versionHistoryNote": "目前顯示此檔案可用的版本記錄。" } } diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index 679cb3f9..2bccd5cb 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -248,7 +248,8 @@ "SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "發貨通知解析逾時,請重試或移除後重新上傳。", "SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "發貨通知正文或附件預處理儲存失敗,請重試解析。", "SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "發貨通知附件解析不完整,請重試解析或移除後重新上傳。", - "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "發貨通知接入記錄已被消費。", + "SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "此檔案已進入訂單處理,請查看現有處理結果,無需重複提交。", + "SHIPPING_NOTICE_ORDER_EXTRACTION_ALREADY_CONSUMED": "此檔案已完成一次訂單處理,請查看現有結果或使用重新識別。", "SHIPPING_NOTICE_INTAKE_EXPIRED": "發貨通知接入記錄已過期。", "SHIPPING_NOTICE_INTAKE_INVALID_STATUS": "目前接入狀態不允許此操作。", "SHIPPING_NOTICE_DUPLICATE_RESOLUTION_REQUIRED": "偵測到重複發貨通知,請先選擇處理方式。", @@ -370,6 +371,8 @@ "SHIPPING_REVIEW_DRAFT_VERSION_MISMATCH": "草稿已被其他視窗更新,請重新整理後再試。", "SHIPPING_REVIEW_FIELD_INVALID": "覆核欄位不屬於此訂單的凍結範本。", "SHIPPING_REVIEW_INVENTORY_CANDIDATES_INVALID": "人工庫存源候選無效:請選擇已啟用的庫存源並填寫原因。", + "SHIPPING_REVIEW_INVENTORY_ROUTING_ADOPT_INVALID": "無法採用規則建議:目前明細沒有有效的待決規則結果。", + "SHIPPING_REVIEW_INVENTORY_ROUTING_KEEP_INVALID": "無法保留人工結果:目前明細沒有待決的規則建議。", "SHIPPING_REVIEW_BUILD_ELIGIBILITY_BLOCKED": "建單資格未通過,請先處理阻斷問題或補齊庫存源候選後再確認。", "SHIPPING_REVIEW_LINE_NOT_FOUND": "訂單明細行不存在或已被刪除。", "SHIPPING_REVIEW_DOCUMENT_NOT_FOUND": "覆核 PDF 不存在或無權存取。", @@ -397,6 +400,18 @@ "SHIPPING_REVIEW_QUALITY_COMMENT_REQUIRED": "選擇「其他」時必須填寫品質異常說明。", "SHIPPING_NOTICE_SESSION_WORK_ITEM_CLOSE_REASON_REQUIRED": "取消本次處理必須填寫原因。", "SHIPPING_NOTICE_SESSION_WORK_ITEM_LOCK_VERSION_INVALID": "工作項版本號無效,請重新整理後再試。", - "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "工作項已被其他操作更新,請重新整理後再試。" + "SHIPPING_NOTICE_SESSION_WORK_ITEM_VERSION_CONFLICT": "工作項已被其他操作更新,請重新整理後再試。", + "SHIPPING.PROCESS_EXECUTION_NOT_FOUND": "未找到流程執行個體。", + "SHIPPING.PROCESS_GATE_NOT_FOUND": "未找到門禁個體。", + "SHIPPING.PROCESS_GATE_ACTION_INVALID": "門禁恢復動作無效。", + "SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN": "請求包含禁止提交的執行控制欄位。", + "SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED": "該動作不是當前門禁允許的主要恢復動作。", + "SHIPPING.PROCESS_GATE_VERSION_MISMATCH": "門禁版本已變更,請重新整理後再試。", + "SHIPPING.PROCESS_GATE_BUSY": "門禁正在執行中,請稍後再試。", + "SHIPPING.PROCESS_GATE_ALREADY_PASSED": "該門禁已通過,無需重複恢復。", + "SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND": "未找到門禁執行嘗試。", + "SHIPPING.PROCESS_GATE_PERMISSION_DENIED": "無權存取或恢復該門禁。", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED": "恢復請求缺少冪等鍵。", + "SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT": "冪等鍵與其他門禁請求衝突,請使用新的冪等鍵後重試。" } } diff --git a/frontend/src/locales/zh-TW/workspace.json b/frontend/src/locales/zh-TW/workspace.json index 40d64df6..61950b35 100644 --- a/frontend/src/locales/zh-TW/workspace.json +++ b/frontend/src/locales/zh-TW/workspace.json @@ -182,11 +182,57 @@ "adminViewOnlyShort": "唯讀", "lastActivity": "最後活動", "terminateReason": "終止原因", - "workflowItem": "Workflow Item", + "workflowItem": "檔案處理項", "downloadExcel": "下載發貨 Excel", "manualUploadEndNote": "Excel 已產生,請下載後在貨代平台上傳,並在本系統登記憑據。", "waitingManualUploadNote": "Excel 已產生,請下載後在貨代平台上傳,並在本系統登記憑據。" }, + "processGate": { + "title": "待處理事項", + "currentGate": "目前處理環節", + "blockingMessage": "需要處理的原因", + "reasonCode": "處理原因", + "diagnosticHint": "處理建議", + "noAction": "目前沒有可執行的處理操作", + "versionMissing": "目前資訊已更新,請重新整理後再試", + "navigationMissing": "缺少跳轉所需的任務或覆核資訊,請重新整理後再試", + "genericBlocking": "目前步驟需要人工處理", + "unknownStep": "目前步驟", + "continueAction": "繼續處理", + "actionSubmitted": "操作已提交", + "submitting": "提交中…", + "actionCodes": { + "retry_with_latest_rules": "依最新規則重試", + "open_inventory_source_review": "開啟庫存源覆核", + "open_order_review": "開啟訂單覆核", + "open_profile_review": "開啟模板覆核", + "edit_order_fields": "編輯訂單欄位", + "confirm_customer": "確認客戶", + "adjudicate_duplicate": "處理重複訂單", + "resolve_field_conflicts": "解決欄位衝突", + "open_inventory_match_review": "開啟庫存匹配覆核", + "open_shortage_review": "開啟缺貨覆核", + "upload_inventory_file": "上傳庫存檔案", + "adopt_rule_suggestion": "採用規則建議", + "keep_manual_inventory_decision": "保留人工決定", + "retry_task_creation": "重試建立任務", + "retry_inventory_preparation": "重試庫存準備", + "regenerate_excel_artifact": "重新產生 Excel", + "regenerate_manual_upload_todo": "重新產生待上傳待辦" + }, + "reasons": { + "freeze_not_ready": "訂單尚未滿足建單/凍結條件", + "profile_not_auto_freeze_approved": "文件模板未通過自動建單審批", + "profile_manual_confirmation_required": "文件模板需要人工確認", + "customer_unresolved": "客戶尚未識別", + "customer_ambiguous": "客戶識別存在歧義", + "field_conflict": "欄位存在衝突,需人工裁決", + "duplicate_unresolved": "重複訂單尚未處理", + "require_manual_review": "需要人工覆核", + "no_inventory_source_candidates": "未找到可用庫存源", + "inventory_source_unavailable": "庫存源不可用" + } + }, "myTodos": { "title": "我的待辦", "subtitle": "跨會話聚合待複核、異常與待人工上傳登記事項。", @@ -238,8 +284,28 @@ "empty": "暫無事件記錄", "detail": "查看詳情", "sourceTask": "任務事件", - "sourceWorkflow": "Workflow 事件", - "workflowEvent": "Workflow 事件" + "sourceWorkflow": "檔案處理記錄", + "workflowEvent": "檔案處理記錄", + "updated": "處理狀態已更新", + "actors": { + "user": "業務人員", + "system": "系統", + "admin": "管理員" + } + }, + "workflowStatus": { + "created": "已建立", + "queued": "等待處理", + "extracting": "正在識別", + "pending_review": "待覆核", + "waiting_manual_upload": "待人工上傳", + "failed": "處理失敗", + "completed": "已完成", + "closed": "已結束" + }, + "workflowReasons": { + "user_cancelled": "已由使用者取消", + "completed": "處理已完成" }, "stpFacts": { "title": "STP 履約進度", diff --git a/scripts/healthcheck.sh b/scripts/healthcheck.sh index d8eeaf32..a9aa94a2 100755 --- a/scripts/healthcheck.sh +++ b/scripts/healthcheck.sh @@ -1,4 +1,10 @@ #!/usr/bin/env bash +# +# scripts/healthcheck.sh +# 用途:部署后健康检查——核心服务运行中,并校验 shipping-worker 可感知 Process Gate 配置。 +# 依赖:docker compose、docker-compose.yml、可选 .env 文件。 +# 逻辑:由 deploy_compose.sh 在 compose up 后调用;失败则阻断发布继续。 +# set -euo pipefail ENV_NAME="${1:-default}" @@ -21,18 +27,76 @@ fi max_attempts=20 sleep_seconds=3 +required_services=(hxops-backend hxops-shipping-worker) for ((i=1; i<=max_attempts; i++)); do - status=$("${DC_CMD[@]}" "${compose_args[@]}" ps --status running --services | wc -l) - if [[ "${status}" -ge 2 ]]; then - echo "Healthcheck passed for ${ENV_NAME} environment." - exit 0 + running=$("${DC_CMD[@]}" "${compose_args[@]}" ps --status running --services || true) + missing=() + for svc in "${required_services[@]}"; do + if ! grep -qx "${svc}" <<<"${running}"; then + missing+=("${svc}") + fi + done + if [[ ${#missing[@]} -eq 0 ]]; then + echo "Core services running for ${ENV_NAME}." + break fi - - echo "Healthcheck waiting (${i}/${max_attempts})..." + if [[ "${i}" -eq "${max_attempts}" ]]; then + echo "Healthcheck failed for ${ENV_NAME}: missing ${missing[*]}" + "${DC_CMD[@]}" "${compose_args[@]}" ps + exit 1 + fi + echo "Healthcheck waiting (${i}/${max_attempts}): missing ${missing[*]}..." sleep "${sleep_seconds}" done -echo "Healthcheck failed for ${ENV_NAME} environment." -"${DC_CMD[@]}" "${compose_args[@]}" ps -exit 1 +# [STEP] Process Gate:确认 shipping-worker 注入了租约/心跳环境变量(领取 Job 的前提配置)。 +gate_env=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-shipping-worker \ + sh -c 'printf "%s" "${SHIPPING_PROCESS_GATE_LEASE_SECONDS:-}"' 2>/dev/null || true) +if [[ -z "${gate_env}" ]]; then + echo "Healthcheck failed: hxops-shipping-worker missing SHIPPING_PROCESS_GATE_LEASE_SECONDS" + exit 1 +fi +echo "Process Gate worker env OK (LEASE_SECONDS=${gate_env})." + +# [STEP] 迁移门禁:确认门禁表已存在(Alembic upgrade 后应有 shipping_process_executions)。 +table_check=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-backend \ + python - <<'PY' 2>/dev/null || true +from app import create_app, db +from sqlalchemy import inspect +app = create_app() +with app.app_context(): + names = set(inspect(db.engine).get_table_names()) + need = { + 'shipping_process_executions', + 'shipping_process_gates', + 'shipping_process_gate_attempts', + } + missing = sorted(need - names) + print('ok' if not missing else 'missing:' + ','.join(missing)) +PY +) +if [[ "${table_check}" != "ok" ]]; then + echo "Healthcheck failed: Process Gate tables not ready (${table_check:-empty})" + exit 1 +fi +echo "Process Gate migration tables OK." + +# [STEP] 领取能力:确认 JobType 已注册且 shipping_process_gate handler 可导入。 +handler_check=$("${DC_CMD[@]}" "${compose_args[@]}" exec -T hxops-shipping-worker \ + python - <<'PY' 2>/dev/null || true +from app.jobs.types import JobType +from app.jobs.registry import get_handler +import app.jobs.handlers # noqa: F401 # 注册全部 handler +handler = get_handler(JobType.SHIPPING_PROCESS_GATE) +print('ok' if callable(handler) else 'missing_handler') +PY +) +if [[ "${handler_check}" != "ok" ]]; then + echo "Healthcheck failed: shipping_process_gate handler not claimable (${handler_check:-empty})" + exit 1 +fi +echo "Process Gate job handler OK." + +echo "Healthcheck passed for ${ENV_NAME} environment." +exit 0