From 7cfd5d167e9723b083d8ab5175d6c846af47617d Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Sun, 23 Aug 2026 00:27:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E9=80=9A=E7=94=A8=E8=A7=A3=E6=9E=90=E8=83=BD=E5=8A=9B=EF=BC=8C?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=80=A7=E8=83=BD=E5=B9=B6=E6=B8=85=E7=90=86?= =?UTF-8?q?=E9=81=97=E7=95=99=E5=BA=9F=E5=BC=83=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/admin/__init__.py | 1 - .../app/api/admin/shipping_legacy_stp_jobs.py | 63 - .../api/admin/shipping_order_extraction.py | 34 + backend/app/api/chat.py | 11 +- backend/app/api/chat/completions.py | 4 - backend/app/api/chat/core.py | 8 +- backend/app/api/chat_turns.py | 24 +- backend/app/api/shipping_notice_tools.py | 53 +- backend/app/api/workspace/shipping_notice.py | 291 +-- backend/app/jobs/handlers/__init__.py | 1 - .../jobs/handlers/shipping_auto_progress.py | 27 - .../handlers/shipping_order_extraction.py | 6 +- backend/app/jobs/types.py | 3 - backend/app/models/job.py | 19 - .../services/agent_registry/handlers/base.py | 3 +- .../handlers/shipping_notice.py | 50 +- .../services/agent_runtime_context/parser.py | 2 - backend/app/services/chat/action_registry.py | 4 +- backend/app/services/chat/turn_events.py | 2 - .../shipping_notice/apx_runtime_audit.py | 57 - .../shipping_notice/attachment_integrity.py | 2 +- .../auto_progress_controller.py | 77 +- .../batch_create_idempotency.py | 167 +- .../shipping_notice/batch_from_intakes.py | 50 - .../shipping_notice/batch_from_notices.py | 142 -- .../shipping_notice/batch_legacy_removed.py | 40 - .../shipping_notice/batch_orchestrator.py | 189 +- .../candidate_qualification_service.py | 73 +- .../chat_action_extended_handlers.py | 23 +- .../shipping_notice/chat_action_handlers.py | 64 - .../services/shipping_notice/chat_actions.py | 1 - .../shipping_notice/chat_tool_capability.py | 10 +- .../shipping_notice/context_adapter.py | 3 +- .../services/shipping_notice/dify_inputs.py | 33 +- .../document_candidate_persist.py | 83 +- .../coordinate_table_reconstruction.py | 177 +- .../document_layout/coordinate_transform.py | 133 ++ .../on_demand_coordinate_evidence.py | 23 +- .../document_layout/order_field_extraction.py | 35 +- .../document_layout/order_profile.py | 14 +- .../document_layout/order_profile_matcher.py | 242 ++- .../email_allocation_table_parser.py | 35 +- .../app/services/shipping_notice/export.py | 4 + .../shipping_notice/export_archive.py | 48 +- .../shipping_notice/generic_order_gate.py | 25 +- .../shipping_notice/generic_parse_plan.py | 137 ++ .../shipping_notice/intake_service.py | 26 +- .../shipping_notice/inventory_file_store.py | 14 +- .../shipping_notice/inventory_workflow.py | 8 +- .../legacy_stp_job_admin_service.py | 297 --- ...upplement_conflict_reassessment_service.py | 296 +++ .../shipping_notice/lifecycle_projection.py | 66 +- .../open_existing_reservation_backfill.py | 4 +- .../order_auto_freeze_execution.py | 353 ---- ...r_document_profile_pdf_automark_service.py | 17 +- .../order_document_profile_service.py | 247 ++- .../shipping_notice/order_extraction.py | 194 +- .../order_extraction_run_service.py | 171 +- .../order_extraction_workflow.py | 101 +- .../order_extraction_workspace_projection.py | 10 +- .../order_review_confirmation_service.py | 20 +- .../order_review_disposition_service.py | 38 +- .../order_review_field_conflict_service.py | 75 +- ...der_review_fulfillment_decision_service.py | 154 +- .../order_review_projection.py | 212 ++- .../shipping_notice/order_review_service.py | 24 +- .../order_review_workbench_projection.py | 15 +- .../shipping_notice/order_schema/runtime.py | 48 +- .../order_stp_auto_create_service.py | 11 + .../shipping_notice/order_supplement_merge.py | 216 ++- .../process_gate_projection.py | 96 +- .../shipping_notice/process_gate_service.py | 4 +- .../processing_projection_invariants.py | 220 +-- .../progress_audit_contract.py | 6 +- .../services/shipping_notice/query_service.py | 220 +-- .../services/shipping_notice/queue_service.py | 5 - .../reconciliation_projector.py | 119 +- .../shipping_notice/reconciliation_service.py | 82 +- .../shipping_notice/reference_context.py | 20 +- .../shipping_notice/runtime_context.py | 52 +- .../shipping_processing_projection.py | 1329 ++++++++++--- .../shipping_notice/shipping_turn_context.py | 21 +- .../shipping_notice/shipping_turn_helpers.py | 30 +- .../task_candidate_reconciliation.py | 2 +- .../task_retry_decision_service.py | 1036 ---------- .../services/shipping_notice/task_workflow.py | 55 - .../services/shipping_notice/tool_common.py | 28 +- .../services/shipping_notice/tool_response.py | 2 +- backend/app/services/shipping_notice/tools.py | 4 +- .../app/services/shipping_notice/ui_state.py | 156 +- ...9q0r_remove_legacy_shipping_apx_runtime.py | 67 + backend/scripts/audit_apx_runtime_state.py | 25 - backend/tests/jobs/test_runner.py | 2 +- .../test_reconciliation_phase34_contract.py | 75 +- backend/tests/test_agent_registry_handlers.py | 1 - backend/tests/test_chat_turn_runtime.py | 130 +- backend/tests/test_email_supplement_merge.py | 155 +- ...legacy_supplement_conflict_reassessment.py | 108 ++ .../tests/test_post_ot_fulfillment_wave_p0.py | 27 + .../tests/test_shipping_auto_progress_p0_3.py | 88 +- .../test_shipping_candidate_qualification.py | 104 +- .../test_shipping_chat_action_handlers.py | 5 + ...st_shipping_conversation_processing_api.py | 124 ++ ...hipping_coordinate_table_reconstruction.py | 126 ++ ...test_shipping_document_layout_lifecycle.py | 59 + .../tests/test_shipping_generic_order_gate.py | 26 +- .../tests/test_shipping_generic_parse_plan.py | 95 + .../test_shipping_notice_business_case.py | 58 +- .../test_shipping_notice_intakes_lifecycle.py | 56 + .../test_shipping_notice_order_extraction.py | 132 +- .../test_shipping_notice_query_service.py | 29 +- .../test_shipping_notice_stp_acceptance.py | 22 - backend/tests/test_shipping_notice_tools.py | 73 - .../tests/test_shipping_notice_ui_state.py | 34 +- ...st_shipping_order_auto_freeze_execution.py | 55 - ...shipping_order_document_profile_service.py | 116 +- .../test_shipping_order_extraction_runs.py | 249 +-- .../test_shipping_order_field_extraction.py | 28 + .../test_shipping_order_profile_matcher.py | 154 +- ...st_shipping_order_review_field_conflict.py | 135 ++ ...st_shipping_order_review_resume_service.py | 32 + .../test_shipping_order_review_service.py | 89 +- .../test_shipping_order_schema_runtime.py | 79 + backend/tests/test_shipping_pdf_automark.py | 14 +- .../test_shipping_process_gate_contract.py | 55 - .../test_shipping_process_recovery_plan.py | 35 - ...ipping_processing_projection_invariants.py | 29 +- ...t_shipping_processing_projection_stage4.py | 661 +++++-- ...t_shipping_review_confirm_auto_progress.py | 7 +- ...ipping_review_line_fulfillment_decision.py | 64 - .../test_shipping_stp_auto_create_enqueue.py | 38 +- .../test_shipping_stp_match_completed_gate.py | 63 +- .../test_shipping_stp_phase3_auto_create.py | 104 +- ...test_shipping_workbench_action_contract.py | 10 +- .../test_shipping_workspace_legacy_audit.py | 92 - ...st_shipping_xfa_formal_extraction_route.py | 6 + .../tests/test_task_retry_decision_service.py | 292 --- docs/demand.md | 3 + ...-transit-transfer-source-instance-mvp.html | 39 +- .../minimum-implementation-spec.md | 74 +- ...-requirements-and-prototype-review-pack.md | 8 +- docs/features/in-transit-transfer/roadmap.md | 42 +- docs/features/shipping-notice/business.md | 3 + ...eview-workbench-file-switch-performance.md | 145 ++ docs/features/shipping-notice/technical.md | 50 +- docs/funclist.md | 5 +- ...20-shipping-notice-five-stage-lifecycle.md | 176 ++ ...026-08-21-shipping-profile-anchor-frame.md | 264 +++ docs/tec.md | 3 + .../src/app/router/routes/admin.routes.ts | 8 - frontend/src/app/router/routes/chat.routes.ts | 13 - .../admin/api/shipping-legacy-stp-jobs.api.ts | 131 -- .../src/features/admin/constants/modules.ts | 2 - .../ShippingLegacyStpJobsPage.vue | 420 ----- .../OrderProfileEditorPage.vue | 297 ++- .../components/OrderProfileDocumentCanvas.vue | 14 +- .../orderProfileForm.utils.spec.ts | 59 + .../orderProfileForm.utils.ts | 79 + .../src/features/admin/types/admin.types.ts | 1 - .../shipping-order-document-profile.types.ts | 20 + .../api/shipping.api.request-dedupe.spec.ts | 112 ++ .../src/features/chat/api/shipping.api.ts | 187 +- .../chat/components/ChatViewContent.vue | 69 +- .../chat/components/ChatViewOverlays.vue | 10 - .../ReviewCurrentProcessingCard.spec.ts | 15 +- .../ReviewCurrentProcessingCard.vue | 24 +- .../ReviewFieldConflictPanel.spec.ts | 17 +- .../ReviewFieldConflictPanel.vue | 17 + .../ReviewWorkbenchFooter.spec.ts | 21 +- .../shipping-review/ReviewWorkbenchFooter.vue | 11 +- ...ShippingConversationProcessingCard.spec.ts | 398 ++-- .../ShippingConversationProcessingCard.vue | 28 +- .../ShippingOrderExtractionCard.spec.ts | 66 +- .../shipping/ShippingOrderExtractionCard.vue | 82 +- .../shipping/ShippingWorkflowTimeline.spec.ts | 67 +- .../shipping/ShippingWorkflowTimeline.vue | 194 +- .../features/chat/composables/useChat.spec.ts | 31 +- .../src/features/chat/composables/useChat.ts | 24 +- .../features/chat/composables/useChatPage.ts | 46 +- .../chat/composables/useChatRouteSync.ts | 12 +- .../chat/composables/useChatShipping.spec.ts | 134 +- .../chat/composables/useChatShipping.ts | 399 +--- .../chat/page/useChatPageConversation.spec.ts | 6 - .../chat/page/useChatPageConversation.ts | 6 +- .../features/chat/page/useChatPageDialogs.ts | 39 +- .../src/features/chat/page/useChatPageSend.ts | 4 +- .../showReviewResumeOutcome.spec.ts | 49 + .../showReviewResumeOutcome.ts | 19 +- .../useShippingOrderReview.spec.ts | 29 +- .../shipping-review/useShippingOrderReview.ts | 19 +- .../shipping/conversationProcessingDisplay.ts | 21 +- .../conversationProcessingProjection.spec.ts | 1672 +---------------- .../conversationProcessingProjection.ts | 619 +----- .../normalizeShippingProcessing.spec.ts | 31 +- .../shipping/normalizeShippingProcessing.ts | 62 +- .../chat/shipping/shippingConversation.ts | 2 +- .../chat/shipping/shippingDownload.ts | 3 +- .../chat/shipping/shippingTurnActions.ts | 4 +- .../chat/shipping/shippingUploadPrompt.ts | 12 +- .../useChatShippingMenuHandler.spec.ts | 1 - .../shipping/useChatShippingMenuHandler.ts | 5 + .../shipping/useChatShippingRefresh.spec.ts | 18 +- .../chat/shipping/useChatShippingRefresh.ts | 10 +- .../useChatShippingSendHandler.spec.ts | 3 - .../shipping/useChatShippingSendHandler.ts | 5 +- .../useChatShippingUploadHandler.spec.ts | 11 - .../shipping/useChatShippingUploadHandler.ts | 28 +- .../useShippingNoticeWorkflow.spec.ts | 67 +- .../shipping/useShippingNoticeWorkflow.ts | 66 +- .../useShippingOrderExtractionRuns.spec.ts | 47 +- .../useShippingOrderExtractionRuns.ts | 94 +- .../features/chat/types/chat-turn.types.ts | 3 +- .../src/features/chat/types/chat.types.ts | 4 +- .../features/chat/types/shipping.api.types.ts | 150 +- .../views/ShippingOrderReviewView.spec.ts | 101 +- .../chat/views/ShippingOrderReviewView.vue | 245 +-- .../actionPresentation.spec.ts | 112 +- .../shipping-progress/actionPresentation.ts | 142 +- .../workbenchActionRegistry.spec.ts | 16 +- .../workbenchActionRegistry.ts | 28 +- .../ShippingRunProgressTable.vue | 2 +- .../ShippingTaskCenterPage.vue | 2 - frontend/src/locales/en/admin.json | 8 + frontend/src/locales/en/chat.json | 23 +- frontend/src/locales/th/admin.json | 8 + frontend/src/locales/th/chat.json | 23 +- frontend/src/locales/zh-CN/admin.json | 8 + frontend/src/locales/zh-CN/chat.json | 23 +- frontend/src/locales/zh-TW/admin.json | 8 + frontend/src/locales/zh-TW/chat.json | 23 +- 230 files changed, 9337 insertions(+), 10989 deletions(-) delete mode 100644 backend/app/api/admin/shipping_legacy_stp_jobs.py delete mode 100644 backend/app/jobs/handlers/shipping_auto_progress.py delete mode 100644 backend/app/services/shipping_notice/apx_runtime_audit.py delete mode 100644 backend/app/services/shipping_notice/batch_from_intakes.py delete mode 100644 backend/app/services/shipping_notice/batch_from_notices.py delete mode 100644 backend/app/services/shipping_notice/batch_legacy_removed.py delete mode 100644 backend/app/services/shipping_notice/chat_action_handlers.py create mode 100644 backend/app/services/shipping_notice/document_layout/coordinate_transform.py create mode 100644 backend/app/services/shipping_notice/generic_parse_plan.py delete mode 100644 backend/app/services/shipping_notice/legacy_stp_job_admin_service.py create mode 100644 backend/app/services/shipping_notice/legacy_supplement_conflict_reassessment_service.py delete mode 100644 backend/app/services/shipping_notice/order_auto_freeze_execution.py delete mode 100644 backend/app/services/shipping_notice/task_retry_decision_service.py create mode 100644 backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py delete mode 100644 backend/scripts/audit_apx_runtime_state.py create mode 100644 backend/tests/test_legacy_supplement_conflict_reassessment.py create mode 100644 backend/tests/test_shipping_generic_parse_plan.py delete mode 100644 backend/tests/test_shipping_order_auto_freeze_execution.py delete mode 100644 backend/tests/test_shipping_workspace_legacy_audit.py delete mode 100644 backend/tests/test_task_retry_decision_service.py create mode 100644 docs/features/shipping-notice/review-workbench-file-switch-performance.md create mode 100644 docs/superpowers/plans/2026-08-20-shipping-notice-five-stage-lifecycle.md create mode 100644 docs/superpowers/plans/2026-08-21-shipping-profile-anchor-frame.md delete mode 100644 frontend/src/features/admin/api/shipping-legacy-stp-jobs.api.ts delete mode 100644 frontend/src/features/admin/modules/shipping-legacy-stp-jobs/ShippingLegacyStpJobsPage.vue create mode 100644 frontend/src/features/chat/api/shipping.api.request-dedupe.spec.ts create mode 100644 frontend/src/features/chat/shipping-review/showReviewResumeOutcome.spec.ts diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index ce18d649..a1818571 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -28,7 +28,6 @@ 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 -import app.api.admin.shipping_legacy_stp_jobs # noqa: F401 import app.api.admin.linked_services # noqa: F401 import app.api.admin.procurement_contract # noqa: F401 import app.api.admin.training_configs # noqa: F401 diff --git a/backend/app/api/admin/shipping_legacy_stp_jobs.py b/backend/app/api/admin/shipping_legacy_stp_jobs.py deleted file mode 100644 index bb06262d..00000000 --- a/backend/app/api/admin/shipping_legacy_stp_jobs.py +++ /dev/null @@ -1,63 +0,0 @@ -""" -backend/app/api/admin/shipping_legacy_stp_jobs.py - -用途:Phase 5-1 —— 管理后台「货代历史 STP Job(928/929)运维面板」只读 API。 -依赖:admin Blueprint、require_admin、legacy_stp_job_admin_service。 -逻辑: - • GET /admin/shipping-notice/legacy-stp-jobs 分页列表(支持 q/case_no/error_code/created_from/created_to) - • GET /admin/shipping-notice/legacy-stp-jobs/ 单条详情 + 回链 Review Case - • 所有接口严格 require_admin;不允许写任何 DB。 -""" - -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.legacy_stp_job_admin_service import ( - get_admin_legacy_stp_job, - list_admin_legacy_stp_jobs, -) - - -def _qint(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/legacy-stp-jobs', methods=['GET']) -@require_admin -def admin_list_legacy_stp_jobs(): - """历史失败 STP Job(failed/dead)分页列表,供管理员做 928/929 回放前筛选。""" - page = _qint('page', 1) - page_size = _qint('page_size', 25) - payload = list_admin_legacy_stp_jobs( - page=page, - page_size=page_size, - status=request.args.get('status'), - job_type=request.args.get('job_type'), - q=request.args.get('q'), - case_no=request.args.get('case_no'), - error_code=request.args.get('error_code'), - blocking_reason=request.args.get('blocking_reason'), - created_from=request.args.get('created_from'), - created_to=request.args.get('created_to'), - sort=request.args.get('sort') or '-created_at', - ) - return ok(payload, request_id=getattr(g, 'request_id', None)) - - -@admin_bp.route('/shipping-notice/legacy-stp-jobs/', methods=['GET']) -@require_admin -def admin_get_legacy_stp_job(job_id: int): - """单条历史失败 STP Job 详情 + 回链 Review Case + 回放建议(replay_plan)。""" - payload = get_admin_legacy_stp_job(int(job_id)) - return ok(payload, request_id=getattr(g, 'request_id', None)) diff --git a/backend/app/api/admin/shipping_order_extraction.py b/backend/app/api/admin/shipping_order_extraction.py index 580d9541..7335e5c8 100644 --- a/backend/app/api/admin/shipping_order_extraction.py +++ b/backend/app/api/admin/shipping_order_extraction.py @@ -32,6 +32,40 @@ def _query_int(name: str, default: int) -> int: raise ValidationError(f'{name} must be an integer') from exc +@admin_bp.route('/shipping-notice/legacy-supplement-conflicts/reassess', methods=['POST']) +@require_admin +def reassess_shipping_legacy_supplement_conflicts(): + """受控重评估历史正文补充冲突;全量操作必须显式确认,结果只返回脱敏统计。""" + body = request.get_json(silent=True) + if body is None: + body = {} + if not isinstance(body, dict): + raise ValidationError('JSON body must be an object') + include_all_raw = body.get('include_all', False) + if not isinstance(include_all_raw, bool): + raise ValidationError('include_all must be a boolean') + include_all = include_all_raw + if include_all and str(body.get('confirmation') or '') != 'REASSESS_LEGACY_SUPPLEMENT_CONFLICTS': + raise ValidationError('confirmation is required for include_all') + candidate_no = str(body.get('candidate_no') or '').strip() or None + run_no = str(body.get('run_no') or '').strip() or None + if not (candidate_no or run_no or include_all): + raise ValidationError('candidate_no, run_no, or include_all is required') + from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import ( + reassess_legacy_supplement_conflicts, + ) + + result = reassess_legacy_supplement_conflicts( + actor_id=int(g.current_user.id), + request_id=getattr(g, 'request_id', None), + candidate_no=candidate_no, + run_no=run_no, + include_all=include_all, + ) + db.session.commit() + return ok(result, request_id=getattr(g, 'request_id', None)) + + @admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET']) @require_admin def get_shipping_order_extraction_health(): diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index eaea5da6..62001c0a 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -137,24 +137,21 @@ def _merge_user_attachments_from_terminal_event( def _build_chat_adapter_hints( *, shipping_task_id: str | None = None, - shipping_batch_no: str | None = None, shipping_intake_nos: list[str] | None = None, ) -> dict | None: """ 构建聊天入口分发给领域 adapter 的提示字典。 - 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示, + 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示, 统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。 """ task_id = str(shipping_task_id or '').strip() - batch_no = str(shipping_batch_no or '').strip() intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()}) - if not task_id and not batch_no and not intake_nos: + if not task_id and not intake_nos: return None return { 'shipping_notice': { 'task_id': task_id or None, - 'batch_no': batch_no or None, 'intake_nos': intake_nos, 'capability': 'order_extraction' if intake_nos else None, 'contract_version': 'shipping-order-extraction-v1' if intake_nos else None, @@ -1574,7 +1571,6 @@ def chat_completions(): # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() - shipping_batch_no = str(data.get('batch_no') or '').strip() raw_shipping_intakes = data.get('shipping_intake_nos') if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list): raise ValidationError('shipping_intake_nos must be a list') @@ -1720,11 +1716,9 @@ def chat_completions(): normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, shipping_intake_nos=shipping_intake_nos, ), shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, kb_type=kb_type, ) @@ -1763,7 +1757,6 @@ def chat_completions(): user_role=user_proxy.role, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, shipping_intake_nos=shipping_intake_nos, ), ), diff --git a/backend/app/api/chat/completions.py b/backend/app/api/chat/completions.py index b00a8731..a0af212a 100644 --- a/backend/app/api/chat/completions.py +++ b/backend/app/api/chat/completions.py @@ -39,7 +39,6 @@ def chat_completions(): # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() - shipping_batch_no = str(data.get('batch_no') or '').strip() kb_type = data.get('kb_type', '企业知识库') files = data.get('files') request_id = uuid.uuid4().hex[:12] @@ -168,10 +167,8 @@ def chat_completions(): normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, ), shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, kb_type=kb_type, ) @@ -210,7 +207,6 @@ def chat_completions(): user_role=user_proxy.role, adapter_hints=_build_chat_adapter_hints( shipping_task_id=shipping_task_id, - shipping_batch_no=shipping_batch_no, ), ), ) diff --git a/backend/app/api/chat/core.py b/backend/app/api/chat/core.py index 63861bcc..285b4f6b 100644 --- a/backend/app/api/chat/core.py +++ b/backend/app/api/chat/core.py @@ -10,21 +10,19 @@ from __future__ import annotations from .shared import * # noqa: F403 -def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None: +def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None: """ 构建聊天入口分发给领域 adapter 的提示字典。 - 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示, + 核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示, 统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。 """ task_id = str(shipping_task_id or '').strip() - batch_no = str(shipping_batch_no or '').strip() - if not task_id and not batch_no: + if not task_id: return None return { 'shipping_notice': { 'task_id': task_id or None, - 'batch_no': batch_no or None, } } diff --git a/backend/app/api/chat_turns.py b/backend/app/api/chat_turns.py index ec2402f5..2edaed82 100644 --- a/backend/app/api/chat_turns.py +++ b/backend/app/api/chat_turns.py @@ -2,7 +2,7 @@ backend/app/api/chat_turns.py 用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。 -依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。 +依赖:app.core.decorators、ChatTurnRuntime、chat_bp。 逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。 """ @@ -77,7 +77,6 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None: """ 将 multipart 附件写入 Turn input.payload。 - - shipping.create_batch_from_notices:预检 notice_items - shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节 """ if not uploads: @@ -87,26 +86,7 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None: payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {} payload = dict(payload) - if action_type == "shipping.create_batch_from_notices": - from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch - from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads - - temp_request_id = uuid.uuid4().hex - try: - notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads) - finally: - cleanup_temp_notice_uploads(temp_request_id) - if not notice_items: - raise ValidationError( - "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试", - details={"file_summary": file_summary}, - ) - payload["notice_items"] = notice_items - payload["file_summary"] = file_summary - conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip() - if conversation_id: - payload["conversation_id"] = conversation_id - elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"): + if action_type in ("shipping.upload_inventory", "shipping.replace_notice"): staged = _stage_upload_files(uploads) if not staged: raise ValidationError("file is required") diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 5d54b9fd..674459d1 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -3,15 +3,13 @@ api/shipping_notice_tools.py 用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。 依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、 - batch_legacy_removed(create_batch 410)。 + tool_api_url。 逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError; `_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计; - co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。 + 历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。 """ from __future__ import annotations -import uuid - from flask import Blueprint, current_app, jsonify, request, send_file from app import db @@ -118,11 +116,11 @@ def _payload() -> dict: return payload -def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None: +def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None: """Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。""" from app.models import ShippingAuditEvent from app.services.shipping_notice.chat_tool_capability import require_chat_capability - claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no, batch_no=batch_no) + claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no) db.session.add(ShippingAuditEvent( event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']), task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']), @@ -130,10 +128,6 @@ def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True}, )) -def _generate_batch_no() -> str: - from datetime import datetime - return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" - @shipping_notice_bp.route('/tools/openapi.json', methods=['GET']) def openapi_spec(): """返回 Dify 导入用的 OpenAPI JSON 文档。""" @@ -192,19 +186,6 @@ def tool_confirm_temporary_inventory_use(): """ return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload())) -@shipping_notice_bp.route('/tools/create_batch', methods=['POST']) -def tool_create_batch(): - """ - 历史建批 Tool(已下线)。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='tools.create_batch') - @shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST']) def tool_update_notice_fields(): """ @@ -328,32 +309,6 @@ def tool_get_task_status(): _require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None) return jsonify(shipping_tools.get_task_status(payload)) -@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST']) -def tool_get_batch_status(): - """ - 历史批次状态查询(已下线)。 - 【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='tools.get_batch_status') - -@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST']) -def tool_switch_focus_task(): - """ - 历史批次焦点切换(已下线)。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='tools.switch_focus_task') - @shipping_notice_bp.route('/rpa/heartbeat', methods=['POST']) def rpa_worker_heartbeat(): """ diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index dcb8f5b1..8d879f95 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -3,16 +3,17 @@ backend/app/api/workspace/shipping_notice.py 用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。 依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service / - tools / notice_upload / ui_state、shipping_processing_projection、batch_legacy_removed。 + tools / notice_upload / ui_state、shipping_processing_projection。 逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与 统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint; - `/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404; + `/shipping-processing/*` 为统一进度读源;历史 `/shipping-batches*` 已删除; Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。 """ from __future__ import annotations import uuid from io import BytesIO +from time import perf_counter from typing import Any from flask import Blueprint, Response, current_app, g, request, send_file @@ -32,9 +33,7 @@ from app.services.shipping_notice.processing_ownership import assert_notice_task from app.services.shipping_notice.query_service import ( EXPORT_MIME_TYPE, count_my_todos, - get_conversation_batch_workspace, get_task_for_user, - list_batches_for_user, list_my_todos, list_tasks_page_for_user, resolve_task_export_download, @@ -148,9 +147,8 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): - """分页列出当前用户可见的发货任务,可按批次与处理状态过滤。""" + """分页列出当前用户可见的发货任务,可按处理状态过滤。""" user = _require_user() - batch_no = str(request.args.get('batch_no') or '').strip() or None lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None try: page = int(request.args.get('page') or 1) @@ -161,7 +159,6 @@ def workspace_shipping_tasks(): raise ValidationError('page must be positive and page_size must be between 1 and 100') return _ok(list_tasks_page_for_user( user.id, - batch_no=batch_no, lifecycle_status=lifecycle_status, page=page, page_size=page_size, @@ -309,116 +306,16 @@ def workspace_batch_restore_shipping_tasks(): """批量恢复回收站内仍为 active 的纯误建任务。""" return _batch_dispose('restore') -@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET']) -def workspace_shipping_batches(): - """列出当前用户的发货批次摘要;co8 后 shipping_batches 已 DROP,恒返回空列表。""" - user = _require_user() - limit = int(request.args.get('limit') or 100) - return _ok(list_batches_for_user(user.id, limit=limit)) - - -@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST']) -def workspace_create_shipping_batch_from_notices(): - """ - 历史:多附件建批(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - raise_shipping_batches_removed(action='workspace.create_from_notices') - - -@workspace_shipping_notice_bp.route('/shipping-batches/', methods=['GET']) -def workspace_shipping_batch_detail(batch_no: str): - """批次详情;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//ui-state', methods=['GET']) -def workspace_shipping_batch_ui_state(batch_no: str): - """批次 UI State;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//tasks', methods=['GET']) -def workspace_shipping_batch_tasks(batch_no: str): - """批次任务列表;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['GET']) -def workspace_shipping_batch_focus_task(batch_no: str): - """批次焦点任务;shipping_batches 已 DROP,恒 404。""" - _require_user() - del batch_no - raise NotFoundError('Not found') - - -@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['POST']) -def workspace_switch_shipping_batch_focus_task(batch_no: str): - """ - 切换批次焦点(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - del batch_no - raise_shipping_batches_removed(action='workspace.switch_batch_focus') - - -@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST']) -def workspace_create_shipping_batch_from_intakes(): - """ - 历史:从 Intake 建批(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - raise_shipping_batches_removed(action='workspace.create_from_intakes') - - -@workspace_shipping_notice_bp.route('/shipping-batches//retry-pending', methods=['POST']) -def workspace_retry_shipping_batch_pending(batch_no: str): - """ - 历史:重试批次待推进任务(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - _require_user() - del batch_no - raise_shipping_batches_removed(action='workspace.retry_batch_pending') - - @workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST']) def workspace_shipping_export_archive(): - """按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" + """按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" user = _require_user() data = request.get_json(silent=True) or {} task_nos = data.get('task_nos') if task_nos is not None and not isinstance(task_nos, list): raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') from app.services.shipping_notice.export_archive import build_export_archive - stream, filename, _manifest = build_export_archive( - user_id=user.id, batch_no=str(data.get('batch_no') or '').strip() or None, task_nos=task_nos, - ) + stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or []) response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') response.call_on_close(stream.close) return response @@ -565,13 +462,6 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str): db.session.commit() return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) -def workspace_shipping_conversation_batch_workspace(conversation_id: str): - """返回一个 Agent 会话下的多批次执行工作台快照;co8 后恒为空工作台。""" - user = _require_user() - return _ok(get_conversation_batch_workspace(conversation_id, user.id)) - - @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) def workspace_create_shipping_task_from_notice(): """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" @@ -719,60 +609,6 @@ def workspace_shipping_task_chat_actions(task_no: str): raise NotFoundError('Not found') return _ok(build_chat_actions_payload(task)) -@workspace_shipping_notice_bp.route('/shipping-tasks//retry', methods=['POST']) -def workspace_retry_shipping_task(task_no: str): - """ - 用户侧重试当前正式 OT:统一决策器选择 resolve_source / fetch / rematch / auto_progress。 - - 核心逻辑:委托 task_retry_decision_service.retry_task_with_decision(scope=task); - 不再直接调用通用 retry_task 重置编排器。 - """ - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision - - return _ok(retry_task_with_decision( - task_no=str(task.task_no), - user_id=int(user.id), - scope='task', - reason=str(data.get('reason') or data.get('comment') or 'user_retry'), - trigger='user_retry', - continue_auto_progress=False, - )) - - -@workspace_shipping_notice_bp.route( - '/shipping-tasks//lines//retry', - methods=['POST'], -) -def workspace_retry_shipping_task_line(task_no: str, line_key: str): - """ - 行级统一「重试」:与任务级共用决策器,scope=line。 - - 核心逻辑:前端不传内部动作码;后端按行库存事实选择 fetch/rematch/needs_human。 - """ - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - _assert_fulfillment_task_ownership(task, user.id) - data = request.get_json(silent=True) or {} - from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision - - return _ok(retry_task_with_decision( - task_no=str(task.task_no), - user_id=int(user.id), - scope='line', - line_key=str(line_key or '').strip(), - reason=str(data.get('reason') or 'user_retry_inventory'), - trigger='user_line_retry', - continue_auto_progress=False, - )) - - @workspace_shipping_notice_bp.route('/shipping-tasks//update-notice-fields', methods=['POST']) def workspace_update_shipping_notice_fields(task_no: str): """更新发货通知单头字段。""" @@ -1265,11 +1101,17 @@ def workspace_get_shipping_processing_conversation(conversation_id: str): user = _require_user() from app.services.shipping_notice.shipping_processing_projection import ( project_conversation_processing_items, + project_conversation_processing_summary, ) agent_raw = request.args.get('agent_id') agent_id = int(agent_raw) if agent_raw not in (None, '') else None - payload = project_conversation_processing_items( + projector = ( + project_conversation_processing_summary + if str(request.args.get('view') or '').strip().lower() == 'summary' + else project_conversation_processing_items + ) + payload = projector( user_id=user.id, conversation_id=str(conversation_id or '').strip(), agent_id=agent_id, @@ -1352,7 +1194,21 @@ def workspace_mark_conversation_task_viewed(task_no: str): @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/', methods=['GET']) def workspace_get_shipping_order_extraction_run(run_no: str): - """查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端;访问留痕。""" + """ + 查询当前用户的一次订单抽取 Run,并返回可与浏览器 HAR 对齐的读取分段耗时。 + + 核心逻辑:先按当前用户加载 Run,再投影为工作台 DTO;保留原有访问审计,响应仅新增 + `Server-Timing` 指标,不暴露正文快照或改变业务数据。 + + Args: + run_no: 当前用户有权访问的订单抽取 Run 业务编号。 + + Returns: + Flask 成功响应,正文为既有 Run DTO,Header 含 run_lookup 和 workspace_projection 耗时。 + + Raises: + AppError: Run 不存在或当前用户无权访问时由服务层抛出。 + """ user = _require_user() from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.order_extraction_run_service import ( @@ -1360,8 +1216,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str): serialize_order_extraction_run, ) + lookup_started = perf_counter() run = get_order_extraction_run(user_id=user.id, run_no=run_no) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() payload = serialize_order_extraction_run(run) + projection_ms = (perf_counter() - projection_started) * 1000 # 轮询接口 60s 节流:窗口内复用最近访问痕迹,仍可追溯访问者与范围。 record_access_audit( action='view_order_extraction_run', @@ -1372,7 +1232,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str): conversation_id=run.conversation_id, metadata={'status': str(run.status or ''), 'poll': True}, ) - return _ok(payload) + response = current_app.make_response(_ok(payload)) + response.headers['Server-Timing'] = ( + f'run_lookup;dur={lookup_ms:.1f}, ' + f'workspace_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//progress-events', methods=['GET']) @@ -1575,21 +1440,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str): source_content_hash = ( str(payload.get('source_content_hash') or '').strip() or None ) - # [Phase 4] 管理员专用扩展:legacy_job_id(历史 Job 928/929 replay)与 replay_mode 透传; - # 非管理员若传入 → 直接 422 拒绝(与 reconcile_and_progress PRE-CHECK 一致)。 - legacy_job_id_raw = payload.get('legacy_job_id') - legacy_job_id: int | None = None - if legacy_job_id_raw is not None: - try: - legacy_job_id = int(legacy_job_id_raw) - except (TypeError, ValueError): - raise ValidationError( - 'legacy_job_id must be integer if provided', - code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION', - ) - replay_mode_raw = payload.get('replay_mode') - replay_mode = bool(replay_mode_raw) if replay_mode_raw is not None else False - from app.services.shipping_notice.reconciliation_service import reconcile_and_progress result = reconcile_and_progress( @@ -1600,8 +1450,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str): expected_case_version=expected_case_version, source_content_hash=source_content_hash, is_admin=is_admin, - legacy_job_id=legacy_job_id, - replay_mode=replay_mode, ) return _ok(result.to_public()) @@ -2001,24 +1849,13 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): 为选中完整明细行创建履约波次。 Body: line_keys[], expected_draft_version, idempotency_key, reason? - 已有正式 OT 时走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress; - 禁止调用 schedule_auto_progress_after_review_confirm。 - 无正式 OT 时保留历史 create_fulfillment_wave(BE-8 兼容分支,仅建单前兜底; - 响应标记 legacy_pre_ot_wave=true,后续版本可收敛删除)。 + 只允许正式 OT 走 create_post_ot_fulfillment_wave + + schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须 + 先完成正式建单,避免同一业务动作存在两套推进事实。 """ - import logging - user = _require_user() data = request.get_json(silent=True) or {} - from app.services.shipping_notice.order_review_confirmation_service import ( - finalize_sync_auto_progress_after_commit, - resolve_confirm_outcome, - schedule_auto_progress_after_review_confirm, - ) from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit - from app.services.shipping_notice.order_review_fulfillment_decision_service import ( - create_fulfillment_wave, - ) from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, @@ -2062,40 +1899,12 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): result['auto_progress'] = progress result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started')) result['post_ot_wave'] = True - result['legacy_pre_ot_wave'] = False return _ok(result) - # [STEP] BE-8:无正式 OT 的历史 wave→confirm 路径;仅兼容,不作为 OT 后主路径。 - logging.getLogger(__name__).warning( - 'shipping_review_fulfillment_wave_legacy_pre_ot case_no=%s line_count=%s', - case_no, - len(line_keys), + raise ValidationError( + 'A formal order task is required before creating a fulfillment wave', + code='SHIPPING.FORMAL_OT_REQUIRED', ) - result = create_fulfillment_wave( - user_id=user.id, - case_no=case_no, - line_keys=line_keys, - expected_draft_version=data.get('expected_draft_version'), - idempotency_key=idem, - reason=reason, - ) - progress = schedule_auto_progress_after_review_confirm( - task_no=result.get('task_no'), - idempotent_replay=bool(result.get('idempotent_replay')), - created_by_id=int(user.id), - commit=False, - ) - db.session.commit() - progress = finalize_sync_auto_progress_after_commit(progress) - result = dict(result) - result.pop('trigger_auto_progress', None) - result['confirm_ok'] = True - result['confirm_outcome'] = resolve_confirm_outcome(progress) - result['auto_progress'] = progress - result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started')) - result['post_ot_wave'] = False - result['legacy_pre_ot_wave'] = True - return _ok(result) @workspace_shipping_notice_bp.route( @@ -2842,8 +2651,8 @@ def workspace_list_shipping_order_extraction_runs(): page_raw = request.args.get('page') page_size_raw = request.args.get('page_size') from app.services.shipping_notice.order_extraction_run_service import ( - list_order_extraction_runs, - serialize_order_extraction_run, + list_order_extraction_run_summaries, + serialize_order_extraction_run_list_item, ) if page_raw is not None or page_size_raw is not None: @@ -2852,7 +2661,7 @@ def workspace_list_shipping_order_extraction_runs(): page_size = int(page_size_raw or 20) except (TypeError, ValueError) as exc: raise ValidationError('page and page_size must be integers') from exc - payload = list_order_extraction_runs( + payload = list_order_extraction_run_summaries( user_id=user.id, conversation_id=conversation_id, status=status, @@ -2861,7 +2670,7 @@ def workspace_list_shipping_order_extraction_runs(): ) assert isinstance(payload, dict) return _ok({ - 'items': [serialize_order_extraction_run(row) for row in payload['items']], + 'items': [serialize_order_extraction_run_list_item(row) for row in payload['items']], 'total': payload['total'], 'page': payload['page'], 'page_size': payload['page_size'], @@ -2871,14 +2680,14 @@ def workspace_list_shipping_order_extraction_runs(): limit = int(request.args.get('limit') or 50) except (TypeError, ValueError) as exc: raise ValidationError('limit must be an integer') from exc - rows = list_order_extraction_runs( + rows = list_order_extraction_run_summaries( user_id=user.id, conversation_id=conversation_id, status=status, limit=limit, ) assert isinstance(rows, list) - return _ok({'items': [serialize_order_extraction_run(row) for row in rows]}) + return _ok({'items': [serialize_order_extraction_run_list_item(row) for row in rows]}) @workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST']) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 8fecd313..f0589dcd 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -17,7 +17,6 @@ from app.jobs.handlers import ( # noqa: F401 shipping_notice_run, shipping_order_extraction, shipping_process_gate, - shipping_auto_progress, shipping_stp_auto_create, shipping_line_auto_fulfill, shipping_post_ot_wave_progress, diff --git a/backend/app/jobs/handlers/shipping_auto_progress.py b/backend/app/jobs/handlers/shipping_auto_progress.py deleted file mode 100644 index 50f2aa56..00000000 --- a/backend/app/jobs/handlers/shipping_auto_progress.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -jobs/handlers/shipping_auto_progress.py - -用途:终态化历史 APX AutoProgress Job。 -依赖:JobContext、auto_progress_controller。 -逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX - Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。 -""" - -from __future__ import annotations - -from app.jobs.context import JobContext -from app.jobs.registry import register_handler -from app.jobs.types import JobType -from app.services.shipping_notice.auto_progress_controller import run_auto_progress_job - - -@register_handler(JobType.SHIPPING_AUTO_PROGRESS) -def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None: - """终态化历史 APX Job;payload 必须含队列注入的 job_id。""" - raw_job_id = payload.get('job_id') - if not raw_job_id: - raise RuntimeError('missing_job_id_for_shipping_auto_progress') - run_auto_progress_job( - job_id=int(raw_job_id), - worker_id=str(ctx.extras.get('worker_label') or f'shipping-auto-progress-{raw_job_id}'), - ) diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 9ff29f28..bf1f4cd2 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -1018,7 +1018,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: 1 for order in merged_unit_orders if isinstance(order, dict) for conflict in order.get('conflicts') or [] if isinstance(conflict, dict) - if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous' + if str(conflict.get('reason') or '').strip() in { + 'supplement_relation_ambiguous', 'supplement_field_conflict', + } ) supplement_status = ( 'conflict' @@ -1148,7 +1150,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: ) # 收口摘要保留可投影的处理事实,供 Run 级 handling_items 区分待补/冲突/冻结/复核。 summary = { - 'run_no': run.run_no, 'batch_no': result.get('batch_no'), + 'run_no': run.run_no, 'created_count': int(result.get('created_count') or 0), 'opened_existing_count': int(result.get('opened_existing_count') or 0), 'pending_count': int(result.get('pending_count') or 0), diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 775246ed..5d4b6f54 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -22,8 +22,6 @@ class JobType(StrEnum): SHIPPING_PROCESS_GATE = 'shipping_process_gate' # RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process' - # 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。 - SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress' # 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。 SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark' # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) @@ -72,7 +70,6 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', 'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_inventory_callback_process', - 'shipping_auto_progress', 'shipping_stp_auto_create', 'shipping_line_auto_fulfill', 'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress', }), diff --git a/backend/app/models/job.py b/backend/app/models/job.py index aa83ff33..df7ef9cd 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -30,25 +30,6 @@ class Job(Base): Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'), Index('ix_jobs_locked_at', 'locked_at'), Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'), - # P0-3:同一 Task 同时只允许一个正式 AutoProgress 决策 Job。库存源 RPA - # Attempt 不使用该索引,因此可以按 source 并行执行。 - Index( - 'uq_jobs_shipping_auto_progress_one_active_task', - 'task_id', - unique=True, - postgresql_where=text( - "domain = 'shipping_notice' " - "AND job_type = 'shipping_auto_progress' " - "AND status IN ('queued', 'running') " - "AND task_id IS NOT NULL" - ), - sqlite_where=text( - "domain = 'shipping_notice' " - "AND job_type = 'shipping_auto_progress' " - "AND status IN ('queued', 'running') " - "AND task_id IS NOT NULL" - ), - ), # 仅预解析 Job:同业务锚点同时只允许一条 queued # (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限) Index( diff --git a/backend/app/services/agent_registry/handlers/base.py b/backend/app/services/agent_registry/handlers/base.py index 2fde91ab..caafabc2 100644 --- a/backend/app/services/agent_registry/handlers/base.py +++ b/backend/app/services/agent_registry/handlers/base.py @@ -17,7 +17,7 @@ class ChatStreamContext: """ /api/chat/completions 单次流式请求上下文。 - 核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id/batch_no)。 + 核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id)。 """ query: str @@ -30,7 +30,6 @@ class ChatStreamContext: normalized_files: list[dict] | None = None adapter_hints: dict[str, Any] | None = None shipping_task_id: str = '' - shipping_batch_no: str = '' kb_type: str = '企业知识库' hxops_turn_id: str | None = None diff --git a/backend/app/services/agent_registry/handlers/shipping_notice.py b/backend/app/services/agent_registry/handlers/shipping_notice.py index d0320efc..09fe96a9 100644 --- a/backend/app/services/agent_registry/handlers/shipping_notice.py +++ b/backend/app/services/agent_registry/handlers/shipping_notice.py @@ -1,5 +1,5 @@ """ -用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。 +用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务 UI State。 依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。 逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。 """ @@ -36,7 +36,7 @@ class ShippingNoticeHandler(AgentHandler): """ 货代发货通知业务 Handler。 - 核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。 + 核心逻辑:按 adapter_hints / task_id 构造 shipping_ui_state,供实时消息使用。 订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。 """ @@ -51,57 +51,36 @@ class ShippingNoticeHandler(AgentHandler): """ 构造 shipping_ui_state SSE 事件。 - 核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。 + 核心逻辑:只接受显式 task_id;失败时记录日志并返回 None。 """ if not _uses_shipping_ui_state_progress(ctx.agent): return None task_id = str(ctx.shipping_task_id or '').strip() - batch_no = str(ctx.shipping_batch_no or '').strip() shipping_hints = self._shipping_hints(ctx) - if not task_id and not batch_no: + if not task_id: task_id = str(shipping_hints.get('task_id') or '').strip() - batch_no = str(shipping_hints.get('batch_no') or '').strip() - if not task_id and not batch_no: + if not task_id: return None try: - from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref - from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state + from app.services.shipping_notice.query_service import get_task_by_ref + from app.services.shipping_notice.ui_state import build_task_ui_state - task = get_task_by_ref(task_id) if task_id else None - batch = get_batch_by_no(batch_no) if batch_no else None + task = get_task_by_ref(task_id) session_id = str(getattr(ctx.session, 'session_id', '') or '') if task is not None: return { 'event': 'shipping_ui_state', 'conversation_id': session_id, 'task_no': task.task_no, - 'batch_no': None, 'ui_state': build_task_ui_state(task), } - if batch is not None: - batch_ui_state = build_batch_ui_state(batch) - focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {} - focus_ui_state = ( - batch_ui_state.get('focus_task_ui_state') - if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) - else None - ) - return { - 'event': 'shipping_ui_state', - 'conversation_id': session_id, - 'batch_no': batch.batch_no, - 'task_no': focus_task.get('task_no'), - 'batch_ui_state': batch_ui_state, - **({'ui_state': focus_ui_state} if focus_ui_state is not None else {}), - } except Exception: if current_app: current_app.logger.exception( - '[shipping-handler] build_ui_state failed request_id=%s task_id=%s batch_no=%s', + '[shipping-handler] build_ui_state failed request_id=%s task_id=%s', ctx.request_id, task_id, - batch_no, ) return None @@ -110,18 +89,11 @@ class ShippingNoticeHandler(AgentHandler): if str(event.get('event') or '') != 'shipping_ui_state': return None ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {} - batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {} - focus_state = ( - batch_ui_state.get('focus_task_ui_state') - if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) - else {} - ) - checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint') + checkpoint = ui_state.get('checkpoint') return json.dumps({ 'task_no': event.get('task_no'), - 'batch_no': event.get('batch_no'), 'checkpoint': checkpoint, - 'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'), + 'updated_at': ui_state.get('updated_at'), }, ensure_ascii=False, sort_keys=True) @staticmethod diff --git a/backend/app/services/agent_runtime_context/parser.py b/backend/app/services/agent_runtime_context/parser.py index 2f7c9c61..7ac4e006 100644 --- a/backend/app/services/agent_runtime_context/parser.py +++ b/backend/app/services/agent_runtime_context/parser.py @@ -28,7 +28,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset( "platform.request_id", "platform.locale", "platform.trigger_source", - "refs.batch_no", "refs.task_no", "refs.run_purpose", "refs.capability", @@ -40,7 +39,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset( "refs.hxops_turn_id", "domain.type", "domain.summary", - "domain.state_hint.batch_no", "domain.state_hint.focus_task_no", "domain.state_hint.schedule_task_id", "domain.state_hint.hxops_turn_id", diff --git a/backend/app/services/chat/action_registry.py b/backend/app/services/chat/action_registry.py index 9f96c1d9..21ddb00f 100644 --- a/backend/app/services/chat/action_registry.py +++ b/backend/app/services/chat/action_registry.py @@ -3,7 +3,7 @@ backend/app/services/chat/action_registry.py 用途:Chat Turn Action Handler 注册与解析。 依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。 -逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。 +逻辑:各领域在各自 action handler 模块注册 handler;turn_runtime 调用 resolve。 """ from __future__ import annotations @@ -78,8 +78,6 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler: def ensure_handlers_loaded() -> None: """延迟导入各领域 handler 模块以完成注册。""" - from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401 from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401 - _ = _shipping_handlers _ = _shipping_extended diff --git a/backend/app/services/chat/turn_events.py b/backend/app/services/chat/turn_events.py index 74deb1a0..af2394ab 100644 --- a/backend/app/services/chat/turn_events.py +++ b/backend/app/services/chat/turn_events.py @@ -73,8 +73,6 @@ def emit_ui_state_updated(*, domain: str, conversation_id: str, payload: dict[st shipping_payload["ui_state"] = payload["ui_state"] if payload.get("task_no"): shipping_payload["task_no"] = payload["task_no"] - if payload.get("batch_no"): - shipping_payload["batch_no"] = payload["batch_no"] return modern + sse_frame(shipping_payload) diff --git a/backend/app/services/shipping_notice/apx_runtime_audit.py b/backend/app/services/shipping_notice/apx_runtime_audit.py deleted file mode 100644 index 1843f057..00000000 --- a/backend/app/services/shipping_notice/apx_runtime_audit.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -APX 历史运行时只读清点。 - -用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。 -依赖:ShippingProcessExecution、Job ORM 模型。 -逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。 -""" - -from __future__ import annotations - -from app.models import Job, ShippingProcessExecution - - -_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external') -_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active') - - -def audit_apx_runtime_state() -> dict[str, object]: - """只读统计 APX Execution/Job 运行态与历史态数量。 - - Returns: - 包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或 - payload 中的 execution_id 关联;任何写操作都不在此函数执行。 - """ - apx_executions = ShippingProcessExecution.query.filter( - ShippingProcessExecution.execution_no.ilike('APX-%') - ).all() - runtime_execution_ids = { - int(row.id) for row in apx_executions - if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES - } - apx_jobs = Job.query.filter( - Job.domain == 'shipping_notice', - Job.status.in_(_JOB_RUNTIME_STATUSES), - ).all() - runtime_job_count = 0 - for job in apx_jobs: - if int(job.execution_id or 0) in runtime_execution_ids: - runtime_job_count += 1 - continue - if str(job.business_ref or '').upper().find('APX-') >= 0: - runtime_job_count += 1 - continue - payload = job.payload_json if isinstance(job.payload_json, dict) else {} - if str(payload.get('execution_no') or '').upper().startswith('APX-'): - runtime_job_count += 1 - - return { - 'execution': { - 'active_count': len(runtime_execution_ids), - 'historical_count': len(apx_executions) - len(runtime_execution_ids), - }, - 'job': { - 'active_count': runtime_job_count, - }, - } - diff --git a/backend/app/services/shipping_notice/attachment_integrity.py b/backend/app/services/shipping_notice/attachment_integrity.py index c2268ec2..90eca8e8 100644 --- a/backend/app/services/shipping_notice/attachment_integrity.py +++ b/backend/app/services/shipping_notice/attachment_integrity.py @@ -3,7 +3,7 @@ services/shipping_notice/attachment_integrity.py 用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。 依赖:error_explainability_contract(warning→稳定原因码)、标准库。 -逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用; +逻辑:由 intake_service.retry_intake_parse 调用; BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致 (由 tests 校验两端前缀集合);可投影 attachment_reason_codes 供审计/UI。 """ diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index a14435c4..8d255bd7 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -24,14 +24,6 @@ from app.services.shipping_notice.process_gate_contract import action_belongs_to from app.services.shipping_notice.tool_common import log_task_event -AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = ( - 'inventory_candidates_calculated', - 'inventory_candidates_frozen', - 'inventory_snapshots_ready', - 'inventory_matched', - 'excel_generated', - 'upload_receipt_recorded', -) _ACTIVE_JOB_STATUSES = ('queued', 'running') _CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'}) @@ -107,16 +99,6 @@ def _new_execution_no() -> str: return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}' -def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: - """ - 禁止创建 APX 六 Gate Execution。 - - APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate - ``ensure_execution_for_workflow_version`` 创建 Execution。 - """ - raise RuntimeError('shipping_apx_creation_disabled') - - def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool: """按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。""" from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES @@ -200,8 +182,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | """ 锁定并取得当前唯一活动 Execution。 - 核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读, - 不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。 + 核心逻辑:正式 20-Gate 链是唯一运行时状态机;候选版本变化仍按原规则 superseded。 """ all_active = ( ShippingProcessExecution.query @@ -230,6 +211,10 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | formal.updated_at = _utc_now() db.session.flush() return formal + if all_active: + raise RuntimeError('shipping_process_execution_contract_invalid') + if execution is not None and not _is_formal_process_execution(execution): + raise RuntimeError('shipping_process_execution_contract_invalid') if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0): # 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。 execution.status = 'superseded' @@ -238,7 +223,6 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')), ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) execution = None - # APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。 if execution is not None: execution.status = 'superseded' execution.updated_at = _utc_now() @@ -286,10 +270,7 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) Job.query.filter( Job.domain == 'shipping_notice', - Job.job_type.in_(( - JobType.SHIPPING_AUTO_PROGRESS.value, - JobType.SHIPPING_PROCESS_GATE.value, - )), + Job.job_type == JobType.SHIPPING_PROCESS_GATE.value, Job.task_id == int(task.id), Job.status == 'queued', ).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False) @@ -305,8 +286,7 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi ShippingProcessGate.query.filter_by(execution_id=int(execution.id)) .order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all() ) - # 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史 - # APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。 + # 正式运行时只接受 20-Gate 合同。 from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES expected = list(PROCESS_GATE_CODES) @@ -385,9 +365,8 @@ def submit_auto_progress( candidate_set_id = int(candidate.id) if candidate is not None else None execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id) if _is_formal_process_execution(execution): - # 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容 - # 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一 - # ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。 + # 正式 20-Gate Execution 是唯一业务真相;先同步已落库事实,再把当前技术 + # Gate 交给唯一 ProcessGate Job/Attempt 通道。 from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_contract import is_technical_gate_party from app.services.shipping_notice.process_gate_executor import is_navigation_action @@ -496,39 +475,5 @@ def submit_auto_progress( if commit: db.session.commit() return result - # 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现 - # 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。 - if not _is_formal_process_execution(execution): - if commit: - db.session.commit() - return { - 'status': 'legacy_readonly', - 'reason_code': 'shipping_apx_runtime_disabled', - 'execution_id': int(execution.id), - } - - -def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]: - """ - 将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。 - - APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job, - 但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。 - """ - job = Job.query.filter_by(id=int(job_id)).with_for_update().first() - if job is None or job.status != 'running': - return {'status': 'noop'} - now = _utc_now() - gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first() - job.status = 'cancelled' - job.finished_at = now - job.message = 'APX historical auto-progress runtime disabled' - if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}: - gate.status = 'cancelled' - gate.updated_at = now - db.session.commit() - return { - 'status': 'legacy_readonly', - 'reason_code': 'shipping_apx_runtime_disabled', - 'execution_id': int(job.execution_id) if job.execution_id else None, - } + # 运行时只接受正式合同;数据不一致时 fail-closed。 + raise RuntimeError('shipping_process_execution_contract_invalid') diff --git a/backend/app/services/shipping_notice/batch_create_idempotency.py b/backend/app/services/shipping_notice/batch_create_idempotency.py index 6c951f96..e5c25563 100644 --- a/backend/app/services/shipping_notice/batch_create_idempotency.py +++ b/backend/app/services/shipping_notice/batch_create_idempotency.py @@ -1,136 +1,22 @@ """ services/shipping_notice/batch_create_idempotency.py -用途:发货通知建单幂等键标准化、跨请求文件内容重复校验(co8 起批次回查已移除)。 -依赖:models.ShippingNotice、query_service、batch_legacy_removed。 -逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。 +用途:发货通知跨请求文件内容重复校验。 +依赖:models.ShippingNotice。 +逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。 """ from __future__ import annotations -import hashlib -import logging import re import zlib -from typing import Any, Iterable +from typing import Iterable from sqlalchemy import text -from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import AppError, ConflictError from app.models import ShippingNotice -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - -logger = logging.getLogger(__name__) - -_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128 -_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$") - - - -def normalize_create_idempotency_key(raw: str | None) -> str | None: - """ - 标准化建单幂等键:去首尾空格、校验长度与安全字符集。 - - Args: - raw: HTTP Header / payload 中的原始幂等键。 - - Returns: - 标准化后的幂等键;空值返回 None。 - - Raises: - ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。 - """ - value = str(raw or "").strip() - if not value: - return None - if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN: - raise AppError( - code="SHIPPING.IDEMPOTENCY_KEY_INVALID", - message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符", - http_status=400, - ) - if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value): - raise AppError( - code="SHIPPING.IDEMPOTENCY_KEY_INVALID", - message="幂等键仅允许字母、数字及 . _ : - 字符", - http_status=400, - ) - return value - - -def warn_missing_create_idempotency_key(*, source: str) -> None: - """兼容期记录缺少建单幂等键的告警,不阻断旧客户端。""" - logger.warning( - "shipping batch create without create_idempotency_key source=%s", - source, - ) - - -def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str: - """ - 根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。 - - 核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。 - """ - hashes: list[str] = [] - for item in notice_items: - if not isinstance(item, dict): - continue - source_hash = str(item.get("source_content_hash") or "").strip().lower() - if not source_hash: - continue - candidate_id = str(item.get("source_candidate_id") or "").strip() - if candidate_id: - hashes.append( - "|".join( - [ - candidate_id, - source_hash, - str(item.get("business_fingerprint") or "").strip().lower(), - str(item.get("content_fingerprint") or "").strip().lower(), - ] - ) - ) - else: - # 旧单文件/直接上传路径保持纯文件哈希,兼容历史批次回放。 - hashes.append(source_hash) - hashes = sorted(set(hashes)) - if not hashes: - return "" - return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower() - - -def batch_stored_content_fingerprint(batch: Any) -> str | None: - """shipping_batches 已删除;保留签名供过渡调用方,固定返回 None。""" - del batch - return None - - -def assert_idempotent_batch_content_matches( - batch: Any, - notice_items: list[dict[str, Any]], -) -> None: - """shipping_batches 已删除;幂等批次内容校验不再适用。""" - del batch, notice_items - - -def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> None: - """ - 按用户与建单幂等键查找已有批次。 - - Returns: - 固定 None(shipping_batches 已删除)。 - """ - del user_id, create_idempotency_key - return None - - -def build_existing_batch_tool_response(batch: Any, *, user_id: int) -> dict[str, Any]: - """shipping_batches 已删除;禁止构建批次重放响应。""" - del batch, user_id - raise_shipping_batches_removed() def _advisory_lock_key(*parts: str) -> int: @@ -161,7 +47,6 @@ def assert_no_exact_duplicate_notices( user_id: int, notice_items: list[dict[str, Any]], *, - exclude_batch_id: int | None = None, exclude_task_ids: Iterable[int] | None = None, ) -> None: """ @@ -175,7 +60,6 @@ def assert_no_exact_duplicate_notices( Args: user_id: 建单用户。 notice_items: 含 source_content_hash / duplicate_resolution_type 的通知项。 - exclude_batch_id: 可选;忽略同批次内任务。 exclude_task_ids: 可选;忽略这些已存在 Task(同 Case 既有波次)。 Raises: @@ -234,28 +118,25 @@ def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> l return unique -def handle_batch_create_integrity_error( - *, - user_id: int, - create_idempotency_key: str | None, - exc: IntegrityError, -) -> dict[str, Any] | None: - """ - 捕获批次建单唯一约束竞争,回滚后回查已有批次。 +_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128 +_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$") - Returns: - 幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。 - """ - db.session.rollback() - key = str(create_idempotency_key or "").strip() - if not key: + +def normalize_create_idempotency_key(raw: str | None) -> str | None: + """标准化 Review Case 确认幂等键,防止同一确认请求重复创建任务。""" + value = str(raw or "").strip() + if not value: return None - batch = find_batch_by_create_idempotency(user_id, key) - if not batch: - return None - logger.info( - "shipping batch create idempotency race resolved batch_no=%s user_id=%s", - batch.batch_no, - user_id, - ) - return build_existing_batch_tool_response(batch, user_id=user_id) + if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN: + raise AppError( + code="SHIPPING.IDEMPOTENCY_KEY_INVALID", + message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符", + http_status=400, + ) + if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value): + raise AppError( + code="SHIPPING.IDEMPOTENCY_KEY_INVALID", + message="幂等键仅允许字母、数字及 . _ : - 字符", + http_status=400, + ) + return value diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py deleted file mode 100644 index 1004a076..00000000 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -backend/app/services/shipping_notice/batch_from_intakes.py - -用途:从已解析 ShippingOrderIntake 确认建批的共享编排(co8 起 shipping_batches 已删除,入口阻断)。 -依赖:batch_legacy_removed。 -逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块; - create_shipping_batch_from_intakes / create_shipping_batch_from_candidates 在入口抛出 ValidationError。 -""" - -from __future__ import annotations - -from typing import Any - -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - -def create_shipping_batch_from_candidates( - *, - user_id: int, - conversation_id: str | None, - intake_nos: list[str], - candidate_nos: list[str], - create_idempotency_key: str | None = None, -) -> dict[str, Any]: - """ - 根据选定 Candidate 创建批次。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key - raise_shipping_batches_removed() - - -def create_shipping_batch_from_intakes( - *, - user_id: int, - conversation_id: str | None, - intake_nos: list[str], - candidate_nos: list[str] | None = None, - create_idempotency_key: str | None = None, -) -> dict[str, Any]: - """ - 根据已解析且未消费的 intake 列表创建批次。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key - raise_shipping_batches_removed() diff --git a/backend/app/services/shipping_notice/batch_from_notices.py b/backend/app/services/shipping_notice/batch_from_notices.py deleted file mode 100644 index 3f32af09..00000000 --- a/backend/app/services/shipping_notice/batch_from_notices.py +++ /dev/null @@ -1,142 +0,0 @@ -""" -services/shipping_notice/batch_from_notices.py - -用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。 -依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。 -逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。 -""" - -from __future__ import annotations - -from typing import Any - -from flask import current_app -from sqlalchemy.exc import IntegrityError - -from app.services.shipping_notice import tools as shipping_tools -from app.services.shipping_notice.batch_create_idempotency import ( - assert_idempotent_batch_content_matches, - build_existing_batch_tool_response, - dedupe_notice_items_by_content_hash, - find_batch_by_create_idempotency, - handle_batch_create_integrity_error, - normalize_create_idempotency_key, - warn_missing_create_idempotency_key, -) -from app.services.shipping_notice.notice_upload import build_notice_file_summary -from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary - - -def create_shipping_batch_from_notice_items( - *, - user_id: int, - conversation_id: str | None, - notice_items: list[dict[str, Any]], - file_summary: dict[str, Any] | None = None, - create_idempotency_key: str | None = None, - defer_commit: bool = False, - start_orchestrator: bool | None = None, -) -> dict[str, Any]: - """ - 根据已抽取的发货通知条目创建批次并可选启动编排器。 - - 核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。 - intake 路径应传 defer_commit=True,避免批次先提交导致上层 ingested 关联/审计断点。 - - Args: - user_id: 当前用户 ID。 - conversation_id: 可选 Agent 会话 ID。 - notice_items: notice_upload 产出的 notice item 列表。 - file_summary: 可选文件预检摘要,写入响应供前端展示。 - create_idempotency_key: 建单幂等键(与 ShippingNotice.idempotency_key 货代上传幂等分离)。 - defer_commit: True 时下层仅 flush,由调用方最终 commit。 - start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。 - - Returns: - 与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。 - - Raises: - ValidationError: notice_items 为空,或 shipping_batches 已删除(co8)。 - """ - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed() - - -def format_batch_created_assistant_message( - result: dict[str, Any], - *, - file_count: int = 0, -) -> str: - """ - 格式化建批成功后写入 Chat Turn assistant 气泡的文案。 - - 核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。 - """ - if bool(result.get("idempotent_replay")): - batch_no = str(result.get("batch_no") or "").strip() - return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。" - - data = result.get("data") if isinstance(result.get("data"), dict) else {} - batch = data.get("batch") if isinstance(data.get("batch"), dict) else {} - tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else [] - focus_task = tasks[0] if tasks and isinstance(tasks[0], dict) else {} - task_id = str( - (data.get("focus_task") or {}).get("task_no") - if isinstance(data.get("focus_task"), dict) - else "" - ).strip() or str(result.get("task_id") or focus_task.get("task_id") or "").strip() - batch_no = str(result.get("batch_no") or batch.get("batch_no") or "").strip() - focus_progress = "" - if focus_task.get("batch_index") and focus_task.get("batch_total"): - focus_progress = f"当前第 {focus_task['batch_index']}/{focus_task['batch_total']} 票" - count = int(file_count or batch.get("file_count") or len(tasks) or 0) - hint = str(result.get("message") or "").strip() - status = str(result.get("status") or "").strip() - orchestrator_started = bool(data.get("orchestrator_started")) - tail = "请根据提示进行确认/驳回。" if status == "needs_human" else "" - lines = [ - hint or f"已处理 {count} 份发货通知附件", - f"批次编号:{batch_no}" if batch_no else "", - f"当前任务:{task_id}" if task_id else "", - focus_progress, - f"后台已开始按票拆分处理,本批 {count} 票会逐步更新状态。" if orchestrator_started else "", - tail, - ] - return "\n".join(line for line in lines if line) - - -def intake_notice_uploads_for_batch( - request_id: str, - uploads: list, -) -> tuple[list[dict[str, Any]], dict[str, Any]]: - """ - 预检并抽取发货通知附件,返回 notice_items 与 file_summary。 - - Args: - request_id: 请求级临时目录 ID。 - uploads: Werkzeug FileStorage 列表。 - - Returns: - (notice_items, file_summary) - """ - max_files = max(int(current_app.config.get('SHIPPING_NOTICE_BATCH_MAX_FILES', 20) or 20), 1) - if len(uploads) > max_files: - from app.core.errors import ValidationError - - raise ValidationError( - '批量上传文件数超过限制', - code='SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED', - details={'max_files': max_files, 'received_files': len(uploads)}, - ) - from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads - - accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads) - file_summary = build_notice_file_summary( - total_files=len(uploads), - accepted=accepted, - rejected=rejected, - duplicate_files=duplicate_files, - ) - notice_items = [item.to_notice_item() for item in accepted] - return notice_items, file_summary diff --git a/backend/app/services/shipping_notice/batch_legacy_removed.py b/backend/app/services/shipping_notice/batch_legacy_removed.py deleted file mode 100644 index f50cf156..00000000 --- a/backend/app/services/shipping_notice/batch_legacy_removed.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -backend/app/services/shipping_notice/batch_legacy_removed.py - -用途:shipping_batches 表物理删除(co8e9f0a1b2c)后的统一阻断与文案常量。 -依赖:app.core.errors.AppError。 -逻辑:create_batch / batch_from_* 等写路径在入口调用 raise_shipping_batches_removed(HTTP 410); - 读路径 list API 返回空集,按 batch_no 查询返回 None。 -""" - -from __future__ import annotations - -from app.core.errors import AppError - -SHIPPING_BATCHES_REMOVED_MESSAGE = ( - "shipping_batches removed (migration co8e9f0a1b2c)" -) - - -def raise_shipping_batches_removed(*, action: str | None = None) -> None: - """ - 阻断仍依赖 shipping_batches 表的写路径。 - - 核心逻辑:ORM 已移除 ShippingBatch;调用方须在入口尽早抛出,避免 SQLAlchemy 访问已 DROP 表。 - - Args: - action: 可选调用方动作名,写入 error.details 便于排查。 - - Raises: - AppError: HTTP 410,code=SHIPPING.BATCHES_REMOVED。 - """ - details = {'migration': 'co8e9f0a1b2c', 'replacement': 'order-extraction-submissions'} - if action: - details['action'] = str(action) - raise AppError( - code='SHIPPING.BATCHES_REMOVED', - message=SHIPPING_BATCHES_REMOVED_MESSAGE, - http_status=410, - details=details, - retryable=False, - ) diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index be58573b..0bba968a 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -1,34 +1,29 @@ """ services/shipping_notice/batch_orchestrator.py -用途:发货通知批次/单票后台编排器。 -依赖:query_service、task_workflow、shipping_notice.tools、tool_common。 -逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止; +用途:发货通知单票后台编排器。 +依赖:query_service、shipping_notice.tools、tool_common。 +逻辑:持久化队列只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止; 复核/STP 确认后已挂 current_order_extraction_id 的 created 任务走 auto_progress。 """ from __future__ import annotations -from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any from flask import current_app from app import db -from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING +from app.services.shipping_notice.constants import PH_RPA_PENDING from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job -from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks -from app.services.shipping_notice.task_workflow import recompute_batch_summary +from app.services.shipping_notice.query_service import get_task_by_ref from app.services.shipping_notice.tool_common import ( auto_progress_enabled, cfg_bool, - cfg_int, log_task_event, - switch_batch_focus, ) -from app.services.shipping_notice.tools import auto_progress, submit_decision +from app.services.shipping_notice.tools import auto_progress -_RUNNING_BATCHES: set[str] = set() _RUNNING_TASKS: set[str] = set() @@ -37,11 +32,6 @@ def batch_orchestrator_enabled() -> bool: return cfg_bool("SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED", True) -def batch_dispatch_concurrency() -> int: - """单个批次最多并发派发多少张票。""" - return cfg_int("SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY", 3, min_value=1) - - def _normalize_ref(value: str | None) -> str: return str(value or "").strip().upper() @@ -85,29 +75,6 @@ def _should_orchestrate_task(task: Any) -> bool: return True -def _is_retryable_task(task: Any) -> bool: - """判断任务是否允许由批次重试入口重新派发。""" - from app.services.shipping_notice.task_disposition_service import task_is_active - - if not task_is_active(task): - return False - pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() - if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}: - return False - if getattr(task, "review_status", None): - return False - if pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}: - return True - if getattr(task, "pending_human_reason", None): - return False - return True - - -def _refresh_batch_focus(task_no: str) -> None: - """shipping_batches 已删除;批次焦点刷新无操作。""" - del task_no - - def _run_single_task(task_no: str) -> dict[str, str | None]: """ 后台执行单票任务的一轮推进。 @@ -141,9 +108,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: ), } - _refresh_batch_focus(task.task_no) - task = get_task_by_ref(normalized_task_no) - assert task is not None log_task_event( task, "backend_orchestrator_task_started", @@ -235,70 +199,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: _unmark_running(_RUNNING_TASKS, normalized_task_no) -def _background_task_runner(app: Any, task_no: str) -> None: - try: - with app.app_context(): - _run_single_task(task_no) - finally: - _unmark_running(_RUNNING_BATCHES, f"TASK::{task_no}") - - -def _background_batch_runner(app: Any, batch_no: str) -> None: - normalized_batch_no = _normalize_ref(batch_no) - try: - with app.app_context(): - batch = get_batch_by_no(normalized_batch_no) - if not batch: - return - recompute_batch_summary(batch) - db.session.commit() - - task_nos = [task.task_no for task in list_sorted_batch_tasks(batch)] - if not task_nos: - return - - max_workers = min(batch_dispatch_concurrency(), len(task_nos)) - if max_workers <= 1: - for task_no in task_nos: - _refresh_batch_focus(task_no) - _run_single_task(task_no) - batch = get_batch_by_no(normalized_batch_no) - if not batch: - break - else: - app_obj = current_app._get_current_object() - with ThreadPoolExecutor( - max_workers=max_workers, - thread_name_prefix=f"shipping-batch-{normalized_batch_no}", - ) as executor: - future_map = { - executor.submit(_run_task_with_app_context, app_obj, task_no): task_no - for task_no in task_nos - } - for future in as_completed(future_map): - task_no = future_map[future] - try: - future.result() - except Exception as exc: - task = get_task_by_ref(task_no) - if task: - task.error_message = str(exc) - log_task_event( - task, - "backend_orchestrator_task_failed", - {"error": str(exc)[:1000], "source": "batch_dispatcher"}, - ) - db.session.commit() - - batch = get_batch_by_no(normalized_batch_no) - if batch: - recompute_batch_summary(batch) - db.session.commit() - finally: - db.session.remove() - _unmark_running(_RUNNING_BATCHES, normalized_batch_no) - - def start_task_orchestrator(task_no: str | None) -> bool: """将单票后台任务写入持久化队列。""" normalized_task_no = _normalize_ref(task_no) @@ -308,80 +208,3 @@ def start_task_orchestrator(task_no: str | None) -> bool: return ok and result in {"queued_for_worker", "already_queued", "done", "ok", "running", "needs_human", "skipped"} -def start_batch_orchestrator(batch_no: str | None) -> bool: - """批次入口改为逐票入队,由 worker 消费,不再在 web 进程内起长线程。""" - normalized_batch_no = _normalize_ref(batch_no) - if not normalized_batch_no or not batch_orchestrator_enabled(): - return False - batch = get_batch_by_no(normalized_batch_no) - if not batch: - return False - - started = False - for task in list_sorted_batch_tasks(batch): - ok, _result = enqueue_shipping_notice_job( - task_no=task.task_no, - created_by_id=getattr(batch, "user_id", None), - batch_no=batch.batch_no, - ) - started = started or ok - recompute_batch_summary(batch) - db.session.commit() - return started - - -def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]: - """重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。""" - normalized_batch_no = _normalize_ref(batch_no) - if not normalized_batch_no: - return {"status": "failed", "message": "batch_no is required"} - batch = get_batch_by_no(normalized_batch_no) - if not batch: - return {"status": "failed", "message": "batch not found"} - - started = 0 - skipped = 0 - for task in list_sorted_batch_tasks(batch): - if not _is_retryable_task(task): - skipped += 1 - continue - pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() - if pending_reason == PH_RPA_PENDING and not getattr(task, "inventory_lines_json", None): - # 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。 - from app.services.shipping_notice.progress_workflow import run_task_auto_progress - - result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator') - status = str(result.get("status") or "").strip().lower() - if status in {"ok", "running", "needs_human"}: - started += 1 - else: - skipped += 1 - continue - if pending_reason == PH_RPA_EXHAUSTED: - result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"}) - status = str(result.get("status") or "").strip().lower() - if status in {"ok", "running", "needs_human"}: - started += 1 - else: - skipped += 1 - continue - if start_task_orchestrator(task.task_no): - started += 1 - else: - skipped += 1 - - recompute_batch_summary(batch) - db.session.commit() - return { - "status": "ok", - "batch_no": batch.batch_no, - "started": started, - "skipped": skipped, - "message": f"已为批次 {batch.batch_no} 重试 {started} 个任务,跳过 {skipped} 个任务。", - } - - -def _run_task_with_app_context(app: Any, task_no: str) -> dict[str, str | None]: - """批次派发时为单票补充独立 app/db 上下文,避免批次线程串行阻塞。""" - with app.app_context(): - return _run_single_task(task_no) diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index e24516f8..076b3c3d 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -26,6 +26,7 @@ from app.extensions import db from app.models import ( ShippingOrderCandidate, ShippingOrderCandidateQualification, + ShippingOrderExtraction, ShippingOrderCustomerMatch, ) from app.services.shipping_notice.candidate_qualification_contract import ( @@ -75,6 +76,47 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85' # 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。 # 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。 _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'}) +_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'}) +_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) + + +def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool: + """按冻结字段配置判断证据缺失是否只是可选字段诊断。 + + 核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有 + ``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法 + 追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知 + 字段继续 fail-closed。 + """ + reason = str(item.get('reason') or item.get('code') or '').strip() + if reason not in _EVIDENCE_GAP_REASONS: + return False + field_code = str(item.get('field') or item.get('field_code') or '').strip() + if not field_code: + return False + + config = item.get('field_config') if isinstance(item.get('field_config'), dict) else None + extraction_id = getattr(candidate, 'order_extraction_id', None) + if config is None and extraction_id is not None: + try: + extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) + definition = ( + extraction.schema_version.definition_json + if extraction is not None and extraction.schema_version is not None + else {} + ) + config = next( + ( + raw for raw in (definition.get('fields') or []) + if isinstance(raw, dict) and str(raw.get('field_code') or '').strip() == field_code + ), + None, + ) + except Exception: # noqa: BLE001 - 门禁读取配置失败时继续保守阻断 + config = None + if config is not None: + return not bool(config.get('required')) and not bool(config.get('auto_create_key_field')) + return field_code in _OPTIONAL_INTERNAL_FIELD_CODES def blocking_candidate_conflicts(candidate: Any) -> list[Any]: @@ -97,14 +139,29 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]: conflicts = getattr(candidate, 'conflicts_json', None) if not isinstance(conflicts, list): return [] if not conflicts else [conflicts] - return [ - item for item in conflicts - if not ( - isinstance(item, dict) - and str(item.get('reason') or item.get('code') or '').strip() - in _NON_BLOCKING_CONFLICT_REASONS - ) - ] + blocking: list[Any] = [] + for item in conflicts: + # 非字典遗留值无法判明严重度与裁决状态,继续 fail-closed。 + if not isinstance(item, dict): + blocking.append(item) + continue + reason = str(item.get('reason') or item.get('code') or '').strip() + if reason in _NON_BLOCKING_CONFLICT_REASONS: + continue + if field_evidence_gap_is_non_blocking(candidate, item): + continue + # 新 Finding 有稳定 key 时,Gate 只消费未解决的 blocking 项;禁止把可提示 + # 的 review_required 误升级为自动建单硬阻断。 + if str(item.get('conflict_key') or '').strip(): + if ( + str(item.get('severity') or '').strip() == 'blocking' + and str(item.get('resolution_status') or 'unresolved').strip() == 'unresolved' + ): + blocking.append(item) + continue + # 旧结构无稳定键/裁决状态,不能安全推定其已解决,保持历史 fail-closed。 + blocking.append(item) + return blocking # --------------------------------------------------------------------------- diff --git a/backend/app/services/shipping_notice/chat_action_extended_handlers.py b/backend/app/services/shipping_notice/chat_action_extended_handlers.py index a64d3c54..82f08c51 100644 --- a/backend/app/services/shipping_notice/chat_action_extended_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_extended_handlers.py @@ -1,10 +1,10 @@ """ backend/app/services/shipping_notice/chat_action_extended_handlers.py -用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。 -依赖:shipping_tools、task_workflow、batch_legacy_removed、shipping_turn_helpers、action_registry。 +用途:货代 Chat Turn 扩展 Action Handler(通知重传/缺口查询)。 +依赖:shipping_tools、task_workflow、shipping_turn_helpers、action_registry。 逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大; - co8 后 switch_batch_focus 固定 410。 + 历史批次焦点切换动作已删除。 """ from __future__ import annotations @@ -16,7 +16,6 @@ from app.services.chat.action_registry import register_action_handler from app.services.chat.action_schema import TurnEvent from app.services.chat.turn_context import TurnContext from app.services.shipping_notice import tools as shipping_tools -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.query_service import ( get_task_by_ref, get_task_for_user, @@ -164,21 +163,6 @@ class ShippingUploadInventoryAction: yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"}) -class ShippingSwitchBatchFocusAction: - action_type = "shipping.switch_batch_focus" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - """ - 历史批次切票(已下线)。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。 - """ - del ctx - raise_shipping_batches_removed(action='shipping.switch_batch_focus') - yield from () # pragma: no cover — raise 后不可达,满足 Iterator 注解 - - class ShippingQueryShortageDetailsAction: action_type = "shipping.query_shortage_details" @@ -194,7 +178,6 @@ class ShippingQueryShortageDetailsAction: _HANDLERS = ( ShippingReplaceNoticeAction(), ShippingUploadInventoryAction(), - ShippingSwitchBatchFocusAction(), ShippingQueryShortageDetailsAction(), ) diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py deleted file mode 100644 index 1cb907e6..00000000 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -backend/app/services/shipping_notice/chat_action_handlers.py - -用途:货代发货通知 Chat Turn Action Handler 注册实现。 -依赖:query_service、ui_state、action_registry、 - batch_legacy_removed。 -逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow; - co8 后 create_batch_* 动作统一 raise_shipping_batches_removed,改走 order-extraction-submissions。 -""" - -from __future__ import annotations - -from typing import Iterator - -from app.services.chat.action_registry import register_action_handler -from app.services.chat.action_schema import TurnEvent -from app.services.chat.turn_context import TurnContext - - -class ShippingCreateBatchFromNoticesAction: - """历史:上传发货通知并创建 shipping_batches;co8 后已下线。""" - - action_type = "shipping.create_batch_from_notices" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - """ - 拒绝旧建批 Turn。 - - 核心逻辑:shipping_batches 已 DROP;客户端须走 Intake + order-extraction-submissions。 - """ - del ctx - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='shipping.create_batch_from_notices') - if False: # pragma: no cover — 满足 Iterator 注解 - yield TurnEvent(event='step.started', data={}) - - -class ShippingCreateBatchFromIntakesAction: - """历史:基于 Intake 确认建批;co8 后已下线,改走订单抽取提交。""" - - action_type = "shipping.create_batch_from_intakes" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - """ - 拒绝旧建批 Turn。 - - 核心逻辑:请使用 POST /order-extraction-submissions 创建 OT/Run。 - """ - del ctx - from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed - - raise_shipping_batches_removed(action='shipping.create_batch_from_intakes') - if False: # pragma: no cover - yield TurnEvent(event='step.started', data={}) - - -_HANDLERS = ( - ShippingCreateBatchFromNoticesAction(), - ShippingCreateBatchFromIntakesAction(), -) - -for _handler in _HANDLERS: - register_action_handler(_handler) diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py index 31a8928c..44368a67 100644 --- a/backend/app/services/shipping_notice/chat_actions.py +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -26,7 +26,6 @@ def build_chat_actions_payload(task) -> dict: state = build_task_ui_state(task) return { "task_no": state.get("task_no"), - "batch_no": state.get("batch_no"), "checkpoint": state.get("checkpoint"), "stage": state.get("stage"), "todo": state.get("todo"), diff --git a/backend/app/services/shipping_notice/chat_tool_capability.py b/backend/app/services/shipping_notice/chat_tool_capability.py index 90499145..7174b069 100644 --- a/backend/app/services/shipping_notice/chat_tool_capability.py +++ b/backend/app/services/shipping_notice/chat_tool_capability.py @@ -16,7 +16,7 @@ from app.core.errors import ForbiddenError from app.models import ChatSession, ShippingNotice -READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'}) +READ_SCOPES = frozenset({'get_shipping_status'}) def _secret() -> bytes: @@ -26,15 +26,15 @@ def _secret() -> bytes: return value.encode('utf-8') -def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None, batch_no: str | None) -> str: +def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None) -> str: """为单次 Chatflow 注入签名、短效且绑定会话/对象的只读令牌。""" - body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'batch': str(batch_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex} + body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex} raw = json.dumps(body, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() signature = hmac.new(_secret(), raw, hashlib.sha256).digest() return base64.urlsafe_b64encode(raw).decode().rstrip('=') + '.' + base64.urlsafe_b64encode(signature).decode().rstrip('=') -def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None, batch_no: str | None = None) -> dict[str, Any]: +def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None) -> dict[str, Any]: """验证令牌签名、时效、scope、会话归属及请求对象,拒绝猜测他人编号。""" try: encoded, signed = str(token or '').split('.', 1) @@ -53,6 +53,4 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() if task is None or str(body.get('task') or '').upper() != task.task_no: raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') - if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper(): - raise ForbiddenError('Batch is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') return body diff --git a/backend/app/services/shipping_notice/context_adapter.py b/backend/app/services/shipping_notice/context_adapter.py index fe440674..302960b2 100644 --- a/backend/app/services/shipping_notice/context_adapter.py +++ b/backend/app/services/shipping_notice/context_adapter.py @@ -33,7 +33,7 @@ def build_shipping_notice_context_adapter( Args: agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。 session_id: HXOPS 会话 ID。 - adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id、batch_no。 + adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id。 request_id: 请求追踪 ID。 trigger_source: 触发来源。 locale: 用户语言。 @@ -46,7 +46,6 @@ def build_shipping_notice_context_adapter( return build_dify_chat_inputs( session_id, task_id=shipping_hints.get('task_id'), - batch_no=shipping_hints.get('batch_no'), trigger_source=trigger_source, request_id=request_id, locale=locale, diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index d329b992..62a3abda 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -3,7 +3,7 @@ services/shipping_notice/dify_inputs.py 用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。 依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。 -逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点, +逻辑:由 Context Adapter / api/chat 调用;本模块只使用显式任务锚点, 仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。 发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。 """ @@ -19,14 +19,8 @@ from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPU from app.services.shipping_notice.runtime_context import build_shipping_runtime_context -def _latest_batch_for_conversation(conversation_id: str) -> None: - """shipping_batches 已删除;固定返回 None。""" - del conversation_id - return None - - def _task_by_task_no(task_id: str) -> ShippingNotice | None: - """按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。""" + """按显式 task_id 获取任务;禁止按会话号猜测当前任务。""" normalized = str(task_id or "").strip().upper() if not normalized: return None @@ -66,8 +60,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) - """ 解析当前显式焦点任务行。 - 核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询, - 但不在无焦点时回退到最近任务,避免多票批次串单。 + 核心逻辑:优先复用已查出的显式 task;不在无焦点时回退到最近任务,避免多票串单。 Args: focus_task: 已解析出的焦点任务号。 @@ -88,7 +81,6 @@ def build_dify_chat_inputs( conversation_id: str | None = None, *, task_id: str | None = None, - batch_no: str | None = None, trigger_source: str | None = None, request_id: str | None = None, locale: str | None = None, @@ -108,7 +100,6 @@ def build_dify_chat_inputs( return {} explicit_task = str(task_id or "").strip().upper() - explicit_batch = str(batch_no or "").strip().upper() explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper() resolved_temporary_session = ( explicit_temporary_session @@ -119,28 +110,12 @@ def build_dify_chat_inputs( ) ) - batch = _latest_batch_for_conversation(conv_id) explicit_task_row = _task_by_task_no(explicit_task) - focus_task = explicit_task - if not focus_task and batch and batch.current_focus_task_no: - focus_task = str(batch.current_focus_task_no or "").strip().upper() - - focus_batch = explicit_batch - if not focus_batch and batch and batch.batch_no: - focus_batch = str(batch.batch_no or "").strip().upper() - elif ( - not focus_batch - and explicit_task_row - and getattr(explicit_task_row, "batch", None) is not None - and getattr(explicit_task_row.batch, "batch_no", None) - ): - focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper() runtime_context = build_shipping_runtime_context( session_id=conv_id, task=_focus_task_row(focus_task, explicit_task_row), - batch=batch or getattr(explicit_task_row, "batch", None), trigger_source=trigger_source, request_id=request_id, locale=locale, @@ -161,7 +136,7 @@ def build_dify_chat_inputs( session = ChatSession.query.filter_by(session_id=conv_id).one_or_none() capability_token = issue_chat_capability( user_id=session.user_id, session_id=conv_id, agent_id=session.agent_id, - task_no=focus_task, batch_no=focus_batch, + task_no=focus_task, ) if session is not None else None return { AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context), diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index d38c1d7c..ec9a04c3 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -431,6 +431,62 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]: } +def _serialize_candidate_status_brief( + cand: ShippingOrderCandidate, + *, + documents: dict[int, str | None], +) -> dict[str, Any]: + """序列化 Intake 状态列表所需的 Candidate 最小字段,不读取审核证据详情。""" + from app.services.shipping_notice.duplicate_detection import _allowed_actions_for + + status = str(cand.duplicate_status or 'unchecked') + blocking = status in { + 'exact_file', + 'same_active_task', + 'same_completed_task', + 'possible_duplicate', + 'same_business_content', + 'possible_revision', + } + strength = str(cand.fingerprint_strength or 'unavailable') + if strength == 'unavailable' and status == 'none': + blocking = False + structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {} + business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {} + return { + 'candidate_no': cand.candidate_no, + 'primary_document_id': cand.primary_document_id, + 'primary_document_filename': documents.get(int(cand.primary_document_id)) + if cand.primary_document_id is not None else None, + 'po_number': cand.po_number or business_summary.get('po_number'), + 'validation_status': cand.validation_status, + 'candidate_status': cand.candidate_status, + 'acceptance_mode': cand.acceptance_mode, + 'extraction_source': cand.extraction_source, + 'selected': bool(cand.selected), + 'conflicts': list(cand.conflicts_json or []), + 'missing_fields': list(cand.missing_fields_json or []), + 'business_summary': business_summary, + 'duplicate': { + 'status': status, + 'blocking': blocking, + 'fingerprint_strength': strength, + 'matches': list(cand.duplicate_matches_json or []), + 'allowed_actions': _allowed_actions_for( + status=status, + fingerprint_strength=strength, + matches=list(cand.duplicate_matches_json or []), + ), + }, + 'duplicate_resolution': { + 'action': cand.duplicate_resolution, + 'target_task_no': cand.duplicate_target_task_no, + 'reason': cand.duplicate_resolution_reason, + } if cand.duplicate_resolution else None, + 'consumed_task_id': cand.consumed_task_id, + } + + def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]: """列出 Intake 下 Document 摘要。""" rows = ( @@ -442,15 +498,36 @@ def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list return [_serialize_document_brief(row, include_text=include_text) for row in rows] -def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]: - """列出 Intake 下 Candidate 摘要。""" +def list_intake_candidates( + intake_id: int, + *, + include_details: bool = True, +) -> list[dict[str, Any]]: + """列出 Intake 下 Candidate 摘要;状态列表可省略重型审核证据。""" rows = ( db.session.query(ShippingOrderCandidate) .filter(ShippingOrderCandidate.intake_id == int(intake_id)) .order_by(ShippingOrderCandidate.id.asc()) .all() ) - return [_serialize_candidate_brief(row) for row in rows] + if include_details: + return [_serialize_candidate_brief(row) for row in rows] + + document_ids = { + int(row.primary_document_id) + for row in rows + if row.primary_document_id is not None + } + documents = { + int(row.id): row.filename + for row in ( + db.session.query(ShippingOrderDocument.id, ShippingOrderDocument.filename) + .filter(ShippingOrderDocument.id.in_(document_ids)) + .all() + if document_ids else [] + ) + } + return [_serialize_candidate_status_brief(row, documents=documents) for row in rows] _UNCHECKED_DUP: dict[str, Any] = { diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py index a698ba90..9f70279e 100644 --- a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py +++ b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py @@ -8,7 +8,6 @@ from __future__ import annotations -from copy import deepcopy import math import re from statistics import median @@ -17,6 +16,9 @@ from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, model_validator from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.coordinate_transform import ( + apply_coordinate_transform_to_region, +) from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value @@ -111,7 +113,7 @@ _HEADER_TERMS = frozenset({ 'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev', }) _SUMMARY_PATTERN = re.compile( - r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)', + r'(?:\btotal(?:\s*amount)?\b|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)', re.IGNORECASE, ) @@ -477,65 +479,64 @@ def _project_coordinate_profile_regions( exclusion_regions: list[dict[str, Any]] | None, coordinate_transform: dict[str, Any] | None, ) -> dict[str, Any] | None: - """对当前重建调用复制并投影受 matcher 证明的相对坐标平移。 + """对当前重建调用复制并投影受 matcher 证明的统一坐标变换。 未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied`` 变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review, 不能静默回退到旧绝对坐标。 """ - if coordinate_transform is None: - return { - 'table_region': table_region, - 'line_layouts': line_layouts, - 'termination_rules': termination_rules, - 'exclusion_regions': exclusion_regions, - } - if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied': - return None - try: - translate_x = float(coordinate_transform['translate_x']) - translate_y = float(coordinate_transform['translate_y']) - except (KeyError, TypeError, ValueError): - return None - if not math.isfinite(translate_x) or not math.isfinite(translate_y): - return None - - def translate_region(region: Any) -> bool: + def project_region(region: Any) -> dict[str, float] | None: if not isinstance(region, dict): - return False - try: - x0, y0 = float(region['x0']) + translate_x, float(region['y0']) + translate_y - x1, y1 = float(region['x1']) + translate_x, float(region['y1']) + translate_y - except (KeyError, TypeError, ValueError): - return False - if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1): - return False - region.update({'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}) - return True + return None + return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform) - projected_table = deepcopy(table_region) if table_region is not None else None - projected_layouts = deepcopy(line_layouts) - projected_terminations = deepcopy(termination_rules) if termination_rules is not None else None - projected_exclusions = deepcopy(exclusion_regions) if exclusion_regions is not None else None - if projected_table is not None and not translate_region(projected_table): + projected_table = project_region(table_region) if table_region is not None else None + projected_layouts = [] + projected_terminations: list[dict[str, Any]] | None = [] if termination_rules is not None else None + projected_exclusions: list[dict[str, float]] | None = [] if exclusion_regions is not None else None + if table_region is not None and projected_table is None: return None - for layout in projected_layouts: + for layout in line_layouts: if not isinstance(layout, dict): return None - region = layout.get('region') - if region is not None and not translate_region(region): - return None - for field in layout.get('field_regions') or []: - if not isinstance(field, dict) or not translate_region(field.get('region')): + copied = dict(layout) + region = copied.get('region') + if region is not None: + projected_region = project_region(region) + if projected_region is None: return None - for rule in projected_terminations or []: - anchor = rule.get('anchor') if isinstance(rule, dict) else None + copied['region'] = projected_region + fields = [] + for field in copied.get('field_regions') or []: + if not isinstance(field, dict): + return None + projected_field = dict(field) + projected_region = project_region(field.get('region')) + if projected_region is None: + return None + projected_field['region'] = projected_region + fields.append(projected_field) + copied['field_regions'] = fields + projected_layouts.append(copied) + for rule in termination_rules or []: + if not isinstance(rule, dict): + return None + copied = dict(rule) + anchor = copied.get('anchor') region = anchor.get('region') if isinstance(anchor, dict) else None - if region is not None and not translate_region(region): - return None - for region in projected_exclusions or []: - if not translate_region(region): + if region is not None: + projected_region = project_region(region) + if projected_region is None: + return None + copied['anchor'] = {**anchor, 'region': projected_region} + assert projected_terminations is not None + projected_terminations.append(copied) + for region in exclusion_regions or []: + projected_region = project_region(region) + if projected_region is None: return None + assert projected_exclusions is not None + projected_exclusions.append(projected_region) return { 'table_region': projected_table, 'line_layouts': projected_layouts, @@ -912,6 +913,86 @@ def suggest_multi_subrow_layouts( return suggestions +def derive_incomplete_table_bbox( + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox | dict[str, Any], +) -> dict[str, float] | None: + """从页级字符证据修复只覆盖表头的候选表格框。 + + 该函数只允许沿原候选框的纵向向下扩展:必须先看到可靠的明细起行锚点, + 并在其后遇到明确的合计/终止行;否则返回 ``None``。横向边界始终继承原候选, + 因而不会把页面上的其他表格或普通文本合并进来。 + + Args: + characters: 同页完整 PDF/OCR 字符坐标,而不是已按错误表框截取的字符。 + table_bbox: MinerU 或其他结构引擎产出的原始表格候选框。 + + Returns: + 可验证的派生绝对表格框;证据不唯一或缺失时返回 ``None``。 + """ + bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox) + if bbox.x1 <= bbox.x0 or bbox.y1 <= bbox.y0: + return None + try: + positioned = [ + ( + index, + item if isinstance(item, PositionedCharacter) + else PositionedCharacter.model_validate(item), + ) + for index, item in enumerate(characters) + ] + except Exception: + return None + # 只取原表横向范围内的字符,纵向上限使用页面证据的最大 y 值。 + candidates = [ + item for item in positioned + if bbox.x0 <= (item[1].bbox.x0 + item[1].bbox.x1) / 2 <= bbox.x1 + and (item[1].bbox.y0 + item[1].bbox.y1) / 2 >= bbox.y0 + ] + if not candidates: + return None + bands = _group_visual_rows(candidates) + anchor_bands: list[list[tuple[int, PositionedCharacter]]] = [] + summary_y0: float | None = None + for band in bands: + band_bbox = _band_bbox(band) + text = ''.join( + glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0) + ).strip() + if band_bbox.y1 <= bbox.y1: + continue + if _SUMMARY_PATTERN.search(text): + if anchor_bands: + summary_y0 = band_bbox.y0 + break + continue + if _band_starts_item(band, bbox): + anchor_bands.append(band) + if not anchor_bands: + return None + last_data_y1 = max(glyph.bbox.y1 for band in anchor_bands for _, glyph in band) + # 续行属于同一表格,但不能将其误当成新的表格边界;取终止行前的最后字符。 + for band in bands: + band_bbox = _band_bbox(band) + if band_bbox.y0 < anchor_bands[0][0][1].bbox.y0: + continue + text = ''.join( + glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0) + ).strip() + if _SUMMARY_PATTERN.search(text): + break + last_data_y1 = max(last_data_y1, band_bbox.y1) + end_y = summary_y0 if summary_y0 is not None else last_data_y1 + if end_y <= bbox.y1: + return None + return { + 'x0': float(bbox.x0), 'y0': float(bbox.y0), + 'x1': float(bbox.x1), 'y1': float(end_y), + } + + def suggest_header_regions( *, characters: list[PositionedCharacter | dict[str, Any]], diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_transform.py b/backend/app/services/shipping_notice/document_layout/coordinate_transform.py new file mode 100644 index 00000000..4aae338a --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/coordinate_transform.py @@ -0,0 +1,133 @@ +""" +services/shipping_notice/document_layout/coordinate_transform.py + +用途:对冻结 Profile 的归一化几何区域应用 matcher 已证明的受限坐标变换。 +依赖:标准库数学运算;由 Profile matcher 求解、订单头和订单行解析共同消费。 +逻辑:默认保持 legacy 绝对坐标;仅接受已应用且通过残差/边界门禁的平移或仿射矩阵, + 任何无效、过界或无法由稳定锚点证明的变换都返回 None 以进入 Review。 +""" + +from __future__ import annotations + +import math +from copy import deepcopy +from typing import Any + + +def apply_coordinate_transform_to_region( + region: dict[str, Any], *, coordinate_transform: dict[str, Any] | None, +) -> dict[str, float] | None: + """将 Profile 相对区域投影到当前文档坐标系,非法变换 fail-closed。 + + Args: + region: 含 x0/y0/x1/y1 的冻结归一化矩形。 + coordinate_transform: Matcher 唯一候选附带的 ``status=applied`` 变换;None 表示 legacy。 + + Returns: + 投影后的页内 bbox;矩阵将矩形四角包络,旋转后仍保留完整证据范围。 + """ + try: + corners = [ + (float(region['x0']), float(region['y0'])), + (float(region['x0']), float(region['y1'])), + (float(region['x1']), float(region['y0'])), + (float(region['x1']), float(region['y1'])), + ] + except (KeyError, TypeError, ValueError): + return None + if not all(math.isfinite(value) for pair in corners for value in pair): + return None + if coordinate_transform is None: + return _bounded_bbox(corners) + matrix = coordinate_transform_matrix(coordinate_transform) + if matrix is None: + return None + return _bounded_bbox([_apply_matrix(matrix, x=x, y=y) for x, y in corners]) + + +def coordinate_transform_matrix(value: dict[str, Any]) -> tuple[float, float, float, float, float, float] | None: + """解析并校验 matcher 输出;无 matrix 的历史 applied 结果仅视为平移。""" + if not isinstance(value, dict) or value.get('status') != 'applied': + return None + raw = value.get('matrix') + if isinstance(raw, list) and len(raw) == 6: + try: + matrix = tuple(float(item) for item in raw) + except (TypeError, ValueError): + return None + else: + try: + matrix = (1.0, 0.0, float(value['translate_x']), 0.0, 1.0, float(value['translate_y'])) + except (KeyError, TypeError, ValueError): + return None + if not all(math.isfinite(item) for item in matrix): + return None + a, b, _tx, d, e, _ty = matrix + determinant = a * e - b * d + if determinant <= 0 or determinant < .50 or determinant > 1.50: + return None + return matrix + + +def project_coordinate_profile_payload( + payload: dict[str, Any], *, coordinate_transform: dict[str, Any] | None, +) -> dict[str, Any] | None: + """复制并统一投影 Profile 的订单头、表区、行区、字段和终止区,不回写冻结定义。""" + if coordinate_transform is None: + return deepcopy(payload) + projected = deepcopy(payload) + + def project(region: Any) -> bool: + if not isinstance(region, dict): + return False + next_region = apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform) + if next_region is None: + return False + region.clear() + region.update(next_region) + return True + + for layout in projected.get('order_field_layouts') or []: + if not isinstance(layout, dict): + return None + for key in ('absolute_value_region', 'fallback_value_region'): + region = layout.get(key) + if region is not None and not project(region): + return None + anchor = layout.get('anchor') + if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']): + return None + for table in projected.get('table_regions') or []: + if not isinstance(table, dict) or not project(table.get('region')): + return None + for layout in [*(table.get('header_layouts') or []), *(table.get('line_layouts') or [])]: + if not isinstance(layout, dict) or not project(layout.get('region')): + return None + for field in layout.get('field_regions') or []: + if not isinstance(field, dict) or not project(field.get('region')): + return None + for rule in table.get('termination_rules') or []: + anchor = rule.get('anchor') if isinstance(rule, dict) else None + if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']): + return None + for region in table.get('exclusion_regions') or []: + if not project(region): + return None + return projected + + +def _apply_matrix(matrix: tuple[float, float, float, float, float, float], *, x: float, y: float) -> tuple[float, float]: + """应用二维仿射矩阵,输入输出均为页内归一化坐标。""" + a, b, tx, d, e, ty = matrix + return a * x + b * y + tx, d * x + e * y + ty + + +def _bounded_bbox(corners: list[tuple[float, float]]) -> dict[str, float] | None: + """将投影角点收敛为页内 bbox;旋转后越页的区域必须 Review。""" + if not corners or not all(math.isfinite(value) for pair in corners for value in pair): + return None + x0, x1 = min(x for x, _ in corners), max(x for x, _ in corners) + y0, y1 = min(y for _, y in corners), max(y for _, y in corners) + if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1): + return None + return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1} diff --git a/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py b/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py index 63263976..a285b0f7 100644 --- a/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py +++ b/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py @@ -29,13 +29,32 @@ def ensure_on_demand_coordinate_evidence( for key in legacy_keys if isinstance(layout.get(key), dict) } - # Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。 + # Run 快照可能早于最近一次布局重试;当前 Layout 是最新解析事实,同页坐标必须 + # 优先于 Run 快照,后者只能补齐当前 Layout 尚未保存的页或表。 current_version = getattr(document, 'current_layout_version', None) current_payload = getattr(current_version, 'payload_json', None) if isinstance(current_payload, dict): current_evidence = current_payload.get('coordinate_evidence') if isinstance(current_evidence, dict): - evidence = {**current_evidence, **evidence} + merged_current = dict(evidence) + for key in ('pages', 'page_glyphs', 'tables'): + snapshot_mapping = _coordinate_mapping(evidence.get(key)) + current_mapping = _coordinate_mapping(current_evidence.get(key)) + # 仅合并实际存在的坐标类别。空 tables 不得写入轻量快照,否则会让 + # 顶层业务 tables 列表与坐标表映射的边界在后续调用中变得模糊。 + if snapshot_mapping or current_mapping: + merged_current[key] = {**snapshot_mapping, **current_mapping} + snapshot_sources = _coordinate_mapping(evidence.get('sources')) + current_sources = _coordinate_mapping(current_evidence.get('sources')) + merged_current['sources'] = { + **snapshot_sources, + **current_sources, + 'pages': { + **_coordinate_mapping(snapshot_sources.get('pages')), + **_coordinate_mapping(current_sources.get('pages')), + }, + } + evidence = merged_current for key in ('pages', 'page_glyphs', 'sources', 'tables'): if key not in evidence and isinstance(current_payload.get(key), dict): evidence[key] = current_payload[key] diff --git a/backend/app/services/shipping_notice/document_layout/order_field_extraction.py b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py index 91a4d7cd..c0169327 100644 --- a/backend/app/services/shipping_notice/document_layout/order_field_extraction.py +++ b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py @@ -14,6 +14,9 @@ from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.coordinate_transform import ( + project_coordinate_profile_payload, +) from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row from app.services.shipping_notice.document_layout.order_profile import ( AnchorRelativeRegion, @@ -84,42 +87,20 @@ def extract_order_fields( def _project_coordinate_transform( profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None, ) -> OrderCoordinateProfile | None: - """把 matcher 唯一确认的平移一次性投影到订单头布局,禁止二次估算。""" + """把 matcher 唯一确认的统一变换投影到订单头布局,禁止二次估算。""" if coordinate_transform is None: return profile - if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied': + payload = project_coordinate_profile_payload( + profile.model_dump(mode='python'), coordinate_transform=coordinate_transform, + ) + if payload is None: return None - try: - dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y']) - except (KeyError, TypeError, ValueError): - return None - if not all(value == value and abs(value) != float('inf') for value in (dx, dy)): - return None - payload = profile.model_dump(mode='python') - for layout in payload.get('order_field_layouts') or []: - if not isinstance(layout, dict): - continue - for key in ('absolute_value_region', 'fallback_value_region'): - region = layout.get(key) - if isinstance(region, dict): - _translate_region_dict(region, dx=dx, dy=dy) - anchor = layout.get('anchor') - if isinstance(anchor, dict) and isinstance(anchor.get('region'), dict): - _translate_region_dict(anchor['region'], dx=dx, dy=dy) try: return OrderCoordinateProfile.model_validate(payload) except Exception: return None -def _translate_region_dict(region: dict[str, Any], *, dx: float, dy: float) -> None: - """原地平移归一化区域并拒绝越界;调用方随后重新校验 Profile。""" - region['x0'] = float(region['x0']) + dx - region['x1'] = float(region['x1']) + dx - region['y0'] = float(region['y0']) + dy - region['y1'] = float(region['y1']) + dy - - def _extract_layout( *, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False, diff --git a/backend/app/services/shipping_notice/document_layout/order_profile.py b/backend/app/services/shipping_notice/document_layout/order_profile.py index abb05394..5b443f1b 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -428,12 +428,16 @@ class DocumentMatchProfile(OrderProfileModel): class AnchorFrameCoordinateModel(OrderProfileModel): - """声明以稳定静态文字建立运行时平移坐标框架的 Profile 能力。""" + """声明以稳定静态文字建立运行时受限几何坐标框架的 Profile 能力。""" type: Literal['anchor_frame'] anchors: list[AnchorRule] = Field(min_length=1, max_length=4) max_translate_x: float = Field(default=.03, ge=0, le=.15) max_translate_y: float = Field(default=.06, ge=0, le=.20) + transform_mode: Literal['translate', 'affine'] = 'translate' + max_scale_delta: float = Field(default=.03, ge=0, le=.10) + max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0) + max_residual: float = Field(default=.01, gt=0, le=.05) @model_validator(mode='after') def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel': @@ -443,6 +447,8 @@ class AnchorFrameCoordinateModel(OrderProfileModel): ids = [anchor.anchor_id for anchor in self.anchors] if len(ids) != len(set(ids)): raise ValueError('anchor frame anchor ids must be unique') + if self.transform_mode == 'affine' and len(self.anchors) < 3: + raise ValueError('affine coordinate model requires at least three frame anchors') return self @@ -453,6 +459,10 @@ class CoordinateModel(OrderProfileModel): anchors: list[AnchorRule] = Field(default_factory=list, max_length=4) max_translate_x: float = Field(default=.03, ge=0, le=.15) max_translate_y: float = Field(default=.06, ge=0, le=.20) + transform_mode: Literal['translate', 'affine'] = 'translate' + max_scale_delta: float = Field(default=.03, ge=0, le=.10) + max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0) + max_residual: float = Field(default=.01, gt=0, le=.05) @model_validator(mode='after') def validate_coordinate_model(self) -> 'CoordinateModel': @@ -463,6 +473,8 @@ class CoordinateModel(OrderProfileModel): AnchorFrameCoordinateModel( type='anchor_frame', anchors=self.anchors, max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y, + transform_mode=self.transform_mode, max_scale_delta=self.max_scale_delta, + max_rotation_degrees=self.max_rotation_degrees, max_residual=self.max_residual, ) return self diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index e72034bb..c3654ee2 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -10,6 +10,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py from __future__ import annotations from copy import deepcopy +import math import re from typing import Any, Literal @@ -20,6 +21,9 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text, visual_glyph_rows, ) +from app.services.shipping_notice.document_layout.coordinate_transform import ( + apply_coordinate_transform_to_region, +) from app.services.shipping_notice.document_layout.order_profile import ( AnchorRule, CRITICAL_STRUCTURE_DIMENSION_KEYS, @@ -34,7 +38,9 @@ from app.services.shipping_notice.document_layout.order_profile_signature import ) -LAYOUT_MATCHING_FEATURES_VERSION = 'shipping-layout-matching-features.v2' +# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义, +# 避免无意义的版本兼容分支。 +LAYOUT_MATCHING_FEATURES_VERSION = 'v1' def _anchor_comparable_text(value: Any) -> str: @@ -359,13 +365,9 @@ def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]: glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=bbox, ) - first = candidates[0] if candidates else {} rendered_tables.append({ 'bbox': bbox, 'header_candidates': candidates, - 'header_tokens': first.get('header_tokens', []), - 'column_centers': first.get('column_centers', []), - 'column_width_ratios': first.get('column_width_ratios', []), }) result = { 'version': LAYOUT_MATCHING_FEATURES_VERSION, @@ -520,6 +522,7 @@ def _resolve_coordinate_transform( return None, [] deltas: list[tuple[float, float]] = [] + anchor_points: list[tuple[float, float, float, float]] = [] anchor_ids: list[str] = [] for anchor in model.anchors: found = _find_anchor_rule_matches( @@ -546,8 +549,15 @@ def _resolve_coordinate_transform( expected_x = (anchor.region.x0 + anchor.region.x1) / 2 expected_y = (anchor.region.y0 + anchor.region.y1) / 2 deltas.append((observed_x - expected_x, observed_y - expected_y)) + anchor_points.append((expected_x, expected_y, observed_x, observed_y)) anchor_ids.append(anchor.anchor_id) + if model.transform_mode == 'affine': + transform, reason = _resolve_affine_coordinate_transform( + anchor_points=anchor_points, anchor_ids=anchor_ids, model=model, + ) + return transform, [] if transform is not None else [reason] + first_x, first_y = deltas[0] if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]): return None, ['profile_anchor_frame_anchor_inconsistent'] @@ -562,6 +572,92 @@ def _resolve_coordinate_transform( }, [] +def _resolve_affine_coordinate_transform( + *, anchor_points: list[tuple[float, float, float, float]], anchor_ids: list[str], model: Any, +) -> tuple[dict[str, Any] | None, str]: + """以 Profile 显式声明的三个以上稳定锚点求受限仿射,无法证明即失败关闭。""" + if len(anchor_points) < 3: + return None, 'profile_anchor_frame_affine_anchor_insufficient' + matrix_x = _least_squares_affine_axis(anchor_points, observed_index=2) + matrix_y = _least_squares_affine_axis(anchor_points, observed_index=3) + if matrix_x is None or matrix_y is None: + return None, 'profile_anchor_frame_affine_anchor_degenerate' + a, b, tx = matrix_x + d, e, ty = matrix_y + determinant = a * e - b * d + scale_x, scale_y = math.hypot(a, d), math.hypot(b, e) + rotation_degrees = abs(math.degrees(math.atan2(d, a))) + residual = max( + math.hypot(a * x + b * y + tx - observed_x, d * x + e * y + ty - observed_y) + for x, y, observed_x, observed_y in anchor_points + ) + if not all(math.isfinite(value) for value in (determinant, scale_x, scale_y, rotation_degrees, residual)): + return None, 'profile_anchor_frame_affine_invalid' + if determinant <= 0: + return None, 'profile_anchor_frame_affine_invalid' + if max(abs(scale_x - 1), abs(scale_y - 1)) > model.max_scale_delta: + return None, 'profile_anchor_frame_affine_scale_out_of_range' + if rotation_degrees > model.max_rotation_degrees: + return None, 'profile_anchor_frame_affine_rotation_out_of_range' + if residual > model.max_residual: + return None, 'profile_anchor_frame_affine_residual_out_of_range' + if abs(tx) > model.max_translate_x or abs(ty) > model.max_translate_y: + return None, 'profile_anchor_frame_transform_out_of_range' + return { + 'status': 'applied', + 'matrix': [round(value, 6) for value in (a, b, tx, d, e, ty)], + 'translate_x': round(tx, 6), + 'translate_y': round(ty, 6), + 'anchor_ids': anchor_ids, + 'residual': round(residual, 6), + 'reason_codes': [], + }, '' + + +def _least_squares_affine_axis( + points: list[tuple[float, float, float, float]], *, observed_index: int, +) -> tuple[float, float, float] | None: + """用正规方程拟合单个仿射轴;共线锚点会因奇异矩阵而被拒绝。""" + count = float(len(points)) + sum_x = sum(item[0] for item in points) + sum_y = sum(item[1] for item in points) + sum_xx = sum(item[0] * item[0] for item in points) + sum_xy = sum(item[0] * item[1] for item in points) + sum_yy = sum(item[1] * item[1] for item in points) + sum_z = sum(item[observed_index] for item in points) + sum_xz = sum(item[0] * item[observed_index] for item in points) + sum_yz = sum(item[1] * item[observed_index] for item in points) + determinant = ( + sum_xx * (sum_yy * count - sum_y * sum_y) + - sum_xy * (sum_xy * count - sum_y * sum_x) + + sum_x * (sum_xy * sum_y - sum_yy * sum_x) + ) + if not math.isfinite(determinant) or abs(determinant) < 1e-9: + return None + matrix = ((sum_xx, sum_xy, sum_x), (sum_xy, sum_yy, sum_y), (sum_x, sum_y, count)) + target = (sum_xz, sum_yz, sum_z) + values = [] + for column in range(3): + replaced = tuple( + tuple(target[row] if index == column else matrix[row][index] for index in range(3)) + for row in range(3) + ) + value = _determinant_3x3(replaced) / determinant + if not math.isfinite(value): + return None + values.append(value) + return values[0], values[1], values[2] + + +def _determinant_3x3(matrix: tuple[tuple[float, float, float], ...]) -> float: + """返回 3x3 矩阵行列式,供无额外数值依赖的仿射拟合使用。""" + return ( + matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) + - matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]) + + matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]) + ) + + def _find_anchor_rule_matches( *, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any], max_translate_x: float, max_translate_y: float, @@ -669,24 +765,38 @@ def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> boo def _translate_signature( *, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None, ) -> dict[str, Any] | None: - """将当前 Profile 的签名副本映射到同一运行时框架,绝不回写冻结签名。""" + """将当前 Profile 签名映射到共同坐标框架,非法变换必须使证据失效。""" if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied': return signature - try: - dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y']) - except (KeyError, TypeError, ValueError): - return signature translated = deepcopy(signature) + + def project_bbox(value: Any) -> list[float] | None: + if not isinstance(value, list) or len(value) != 4: + return None + projected = apply_coordinate_transform_to_region( + {'x0': value[0], 'y0': value[1], 'x1': value[2], 'y1': value[3]}, + coordinate_transform=coordinate_transform, + ) + if projected is None: + return None + return [projected['x0'], projected['y0'], projected['x1'], projected['y1']] + for pattern in translated.get('table_patterns') or []: if not isinstance(pattern, dict): continue bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {} median = bbox.get('median') if isinstance(bbox.get('median'), list) else None - if median and len(median) == 4: - bbox['median'] = [median[0] + dx, median[1] + dy, median[2] + dx, median[3] + dy] + if median: + projected = project_bbox(median) + if projected is None: + return None + bbox['median'] = projected header = pattern.get('header_bbox') - if isinstance(header, list) and len(header) == 4: - pattern['header_bbox'] = [header[0] + dx, header[1] + dy, header[2] + dx, header[3] + dy] + if header is not None: + projected = project_bbox(header) + if projected is None: + return None + pattern['header_bbox'] = projected for relation in translated.get('field_relation_graph') or []: if isinstance(relation, dict): # 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。 @@ -1029,7 +1139,7 @@ def _observe_layout_features( ) -> dict[str, Any]: """从冻结 layout 聚合非敏感结构特征供维度比对。""" persisted = layout.get('matching_features') - # 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v2 投影。 + # 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v1 投影。 if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()): persisted = None if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION: @@ -1077,26 +1187,26 @@ def _observe_layout_features( def _observed_features_from_persisted_projection( *, features: dict[str, Any], signature: dict[str, Any] | None, ) -> dict[str, Any] | None: - """将压缩前持久化的轻量特征恢复为 matcher 输入,绝不读取逐字符正文。""" + """将完整的事实投影恢复为 matcher 输入,缺任一关键结构则拒绝匹配。 + + 投影生成时没有 Profile 上下文,因此会保留同一主表的多个视觉行候选。运行期只能 + 根据冻结签名的 token、顺序和列几何联合选择;按列数选最近候选会把数据行误作表头。 + """ page_structure = features.get('page_structure') tables = features.get('tables') if not isinstance(page_structure, dict) or not isinstance(tables, list): return None - candidates = [item for item in tables if isinstance(item, dict) and isinstance(item.get('bbox'), list)] + candidates = [ + item for item in tables + if isinstance(item, dict) + and _is_complete_persisted_table_candidate(item) + ] if not candidates: return None - expected = _signature_column_values(signature or {}, 'column_centers') - primary = candidates[0] - if expected: - def distance(item: dict[str, Any]) -> tuple[float, int]: - options = item.get('header_candidates') if isinstance(item.get('header_candidates'), list) else [item] - best = min((abs(len(option.get('column_centers') or []) - len(expected)) for option in options if isinstance(option, dict)), default=999) - return best, abs(len(item.get('column_centers') or []) - len(expected)) - primary = min(candidates, key=distance) - options = primary.get('header_candidates') if isinstance(primary.get('header_candidates'), list) else [] - if options: - primary = min(options, key=lambda item: abs(len(item.get('column_centers') or []) - len(expected))) | {'bbox': candidates[0].get('bbox')} - bbox = primary.get('bbox') + selected = _select_persisted_header_candidate(candidates=candidates, signature=signature) + if selected is None: + return None + primary, bbox = selected centers = primary.get('column_centers') widths = primary.get('column_width_ratios') tokens = primary.get('header_tokens') @@ -1121,6 +1231,80 @@ def _observed_features_from_persisted_projection( } +def _is_complete_persisted_table_candidate(candidate: dict[str, Any]) -> bool: + """校验 v1 投影的表和表头候选契约,防止不完整旧数据参与高分匹配。""" + bbox = candidate.get('bbox') + headers = candidate.get('header_candidates') + if not isinstance(bbox, list) or len(bbox) != 4 or not isinstance(headers, list): + return False + return any(_is_complete_persisted_header_candidate(item) for item in headers if isinstance(item, dict)) + + +def _is_complete_persisted_header_candidate(candidate: dict[str, Any]) -> bool: + """候选行必须同时保留 token、列中心和列宽,不能用残缺结构猜测。""" + tokens = candidate.get('header_tokens') + centers = candidate.get('column_centers') + widths = candidate.get('column_width_ratios') + return ( + isinstance(tokens, list) + and isinstance(centers, list) + and isinstance(widths, list) + and bool(tokens) + and bool(centers) + and len(centers) == len(widths) + ) + + +def _select_persisted_header_candidate( + *, candidates: list[dict[str, Any]], signature: dict[str, Any] | None, +) -> tuple[dict[str, Any], list[float]] | None: + """按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。""" + expected_tokens = [ + str(token).casefold() + for pattern in (signature or {}).get('table_patterns') or [] + if isinstance(pattern, dict) + for token in pattern.get('header_tokens') or [] + ] + expected_order = [ + str(token).casefold() + for pattern in (signature or {}).get('table_patterns') or [] + if isinstance(pattern, dict) + for token in pattern.get('header_order') or [] + ] + expected_centers = _signature_column_values(signature or {}, 'column_centers') + expected_widths = _signature_column_values(signature or {}, 'column_width_ratios') + if not expected_tokens or not expected_centers: + return None + + scored: list[tuple[float, float, float, int, dict[str, Any], list[float]]] = [] + for table in candidates: + bbox = table['bbox'] + for header in table['header_candidates']: + if not isinstance(header, dict) or not _is_complete_persisted_header_candidate(header): + continue + tokens = [str(token).casefold() for token in header['header_tokens']] + centers = header['column_centers'] + widths = header['column_width_ratios'] + token_ratio = sum(token in tokens for token in expected_tokens) / len(expected_tokens) + shared = [token for token in expected_order if token in tokens] + order_ratio = 1.0 + if len(shared) > 1: + positions = [tokens.index(token) for token in shared] + order_ratio = sum(left < right for left, right in zip(positions, positions[1:])) / (len(positions) - 1) + center_ratio = _sequence_similarity(expected_centers, centers, tolerance=0.08) + width_ratio = _sequence_similarity(expected_widths, widths, tolerance=0.16) if expected_widths else 1.0 + count_ratio = min(len(expected_centers), len(centers)) / max(len(expected_centers), len(centers)) + score = .50 * token_ratio + .15 * order_ratio + .25 * center_ratio + .05 * width_ratio + .05 * count_ratio + # token 语义或几何任一缺失都不足以把压缩投影作为结构事实。 + if token_ratio < .50 or center_ratio < .50: + continue + scored.append((score, token_ratio, center_ratio, len(tokens), header, bbox)) + if not scored: + return None + _, _, _, _, header, bbox = max(scored, key=lambda item: item[:4]) + return header, bbox + + def _select_signature_primary_table_bbox( *, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None, ) -> list[float] | None: diff --git a/backend/app/services/shipping_notice/email_allocation_table_parser.py b/backend/app/services/shipping_notice/email_allocation_table_parser.py index d5198358..aa4f11f2 100644 --- a/backend/app/services/shipping_notice/email_allocation_table_parser.py +++ b/backend/app/services/shipping_notice/email_allocation_table_parser.py @@ -61,19 +61,31 @@ def _normalize_schema_row( def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]: - """将首行映射为 Schema 订单字段或邮件专属字段;重复映射直接标为复核。""" + """将首行映射为 Schema 订单字段;同字段多个别名按 Schema 顺序保留首选列。""" schema_headers = _schema_headers(schema_definition) mapped: dict[int, str] = {} + selected_by_field: dict[str, tuple[int, int]] = {} issues: list[str] = [] for column, slot in enumerate(grid.rows[0]): normalized = normalize_table_header(slot.text if slot is not None else '').casefold() schema_field = schema_headers.get(normalized) hits = [schema_field] if schema_field else [] if len(hits) == 1: - if hits[0] in mapped.values(): - issues.append('email_supplement_duplicate_header') + field_code = str(hits[0]) + priority = _schema_header_priority(schema_definition, field_code, normalized) + previous = selected_by_field.get(field_code) + if previous is None: + mapped[column] = field_code + selected_by_field[field_code] = (priority, column) else: - mapped[column] = hits[0] + previous_priority, previous_column = previous + # 同一业务字段出现两个已配置别名时,按 Schema 中 field_code、 + # display_name、aliases 的声明顺序选择唯一证据列;不把同一行 + # 的 Source / hub code 误判为冲突,也不允许后一个列覆盖首选值。 + if priority < previous_priority: + mapped.pop(previous_column, None) + mapped[column] = field_code + selected_by_field[field_code] = (priority, column) elif len(hits) > 1: issues.append('email_supplement_header_ambiguous') if not ({'customer_po_number', 'po_number'} & set(mapped.values())): @@ -81,6 +93,21 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in return mapped, sorted(set(issues)) +def _schema_header_priority(schema_definition: dict[str, Any], field_code: str, normalized_header: str) -> int: + """返回字段表头的 Schema 声明顺序,供同字段多别名确定性裁决。""" + priorities: list[int] = [] + for raw in schema_definition.get('fields') or []: + if not isinstance(raw, dict) or not raw.get('enabled', True): + continue + if str(raw.get('field_code') or '').strip() != field_code: + continue + candidates = (field_code, raw.get('display_name'), *(raw.get('aliases') or [])) + for priority, value in enumerate(candidates): + if normalize_table_header(value).casefold() == normalized_header: + priorities.append(priority) + return min(priorities) if priorities else 2**31 - 1 + + def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]: """收集邮件补充允许的 Schema 别名;跨字段冲突必须显式保留为不可映射。""" headers: dict[str, str | None] = {} diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index b76f1414..f4e69084 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -202,6 +202,10 @@ def _mapping_value( value = order_values.get('__export_sequence') else: value = key + # 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串; + # 尤其金额字段不得由数量/单价等相邻字段隐式推导或伪装为已提供。 + if kind == 'order_field' and value is None: + return None return _format_value(value, mapping['formatter']) diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py index 4203be3f..81c916a0 100644 --- a/backend/app/services/shipping_notice/export_archive.py +++ b/backend/app/services/shipping_notice/export_archive.py @@ -1,7 +1,7 @@ """ services/shipping_notice/export_archive.py -用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。 +用途:为显式任务集合生成受权限控制的发货 Excel ZIP 下载包。 依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。 逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。 """ @@ -18,36 +18,22 @@ from zipfile import ZIP_DEFLATED, ZipFile from app.core.errors import NotFoundError, ValidationError from app.models import ShippingExportArtifact, ShippingNotice -from app.services.shipping_notice.query_service import ( - get_batch_for_user, - get_task_for_user, - list_sorted_batch_tasks, - resolve_task_export_download, -) +from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download MAX_ARCHIVE_TASKS = 100 -def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]: - """按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。""" - normalized_batch = str(batch_no or '').strip() +def _select_tasks(*, user_id: int, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]: + """按显式任务号选择当前用户任务,禁止部分越权成功。""" normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip())) - if bool(normalized_batch) == bool(normalized_tasks): - raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') - if normalized_batch: - batch = get_batch_for_user(normalized_batch, user_id) - if batch is None: - raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') - tasks = list_sorted_batch_tasks(batch) - archive_key = normalized_batch - else: - tasks = [] - for task_no in normalized_tasks: - task = get_task_for_user(task_no, user_id) - if task is None: - raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') - tasks.append(task) - archive_key = 'selected' + if not normalized_tasks: + raise ValidationError('task_nos is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + tasks = [] + for task_no in normalized_tasks: + task = get_task_for_user(task_no, user_id) + if task is None: + raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') + tasks.append(task) if not tasks: raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY') if len(tasks) > MAX_ARCHIVE_TASKS: @@ -55,7 +41,7 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once', code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS}, ) - return tasks, archive_key + return tasks, 'selected' def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]: @@ -91,16 +77,14 @@ def _archive_name(filename: str, task_no: str, used: set[str]) -> str: return candidate -def build_export_archive( - *, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None, -) -> tuple[BinaryIO, str, dict]: +def build_export_archive(*, user_id: int, task_nos: list[str]) -> tuple[BinaryIO, str, dict]: """ 生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。 Returns: (定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。 """ - tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos) + tasks, archive_key = _select_tasks(user_id=user_id, task_nos=task_nos) artifacts = _ready_artifacts(tasks) # 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。 stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b') @@ -129,7 +113,7 @@ def build_export_archive( included += 1 entries.append(entry) manifest = { - 'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []}, + 'archive_version': 1, 'selection': {'task_nos': task_nos}, 'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks), 'included_count': included, 'excluded_count': len(entries) - included, 'entries': entries, } diff --git a/backend/app/services/shipping_notice/generic_order_gate.py b/backend/app/services/shipping_notice/generic_order_gate.py index a69571fc..fb1f7f32 100644 --- a/backend/app/services/shipping_notice/generic_order_gate.py +++ b/backend/app/services/shipping_notice/generic_order_gate.py @@ -22,6 +22,7 @@ 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.generic_parse_plan import validate_generic_parse_plan @dataclass(frozen=True) @@ -49,6 +50,9 @@ def evaluate_generic_extraction_gate( schema: dict[str, Any], intake: dict[str, Any], unit: Any, + parse_plan: dict[str, Any] | None = None, + layout_snapshot: dict[str, Any] | None = None, + require_parse_plan: bool = False, ) -> GenericGateResult: """ 执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与必填字段缺失。 @@ -68,13 +72,28 @@ def evaluate_generic_extraction_gate( Returns: GenericGateResult;passed 为 True 时 parse_result.orders 非空。 """ - completeness = build_generic_completeness_report(candidates) + # 生产工作流必须传入冻结 Plan;保留无 Plan 参数的纯函数调用,供已有诊断和 + # 单元测试直接评估候选完整性,不把它接入自动建单路径。 + plan_validation = None + effective_candidates = candidates + if parse_plan is not None or require_parse_plan: + plan_validation = validate_generic_parse_plan( + plan=parse_plan, + schema_checksum=str(schema.get('checksum') or ''), + layout_snapshot=layout_snapshot or {}, + runtime_candidates=candidates, + ) + effective_candidates = plan_validation.candidates + completeness = build_generic_completeness_report(effective_candidates) gate_codes: list[str] = [] stable_codes: list[str] = [] + if plan_validation is not None and not plan_validation.passed: + gate_codes.extend(plan_validation.reason_codes) + gate_codes.extend(_completeness_gate_codes(completeness)) parse_result = parse_generic_orders( - candidates=candidates, + candidates=effective_candidates, definition=definition, schema=schema, intake=intake, @@ -83,7 +102,7 @@ def evaluate_generic_extraction_gate( if parse_result.reason_code: stable_codes.append(parse_result.reason_code) - customer_values = collect_customer_field_values(candidates, definition=definition) + customer_values = collect_customer_field_values(effective_candidates, definition=definition) if len(customer_values) > 1: gate_codes.append('multiple_customer') stable_codes.append('generic_gate_blocked') diff --git a/backend/app/services/shipping_notice/generic_parse_plan.py b/backend/app/services/shipping_notice/generic_parse_plan.py new file mode 100644 index 00000000..1f571a5f --- /dev/null +++ b/backend/app/services/shipping_notice/generic_parse_plan.py @@ -0,0 +1,137 @@ +""" +services/shipping_notice/generic_parse_plan.py + +用途:将自动标注的 layout_schema_candidates 编译为 Run 冻结的通用解析计划。 +依赖:冻结 Schema、Layout candidate 与 schema_mapping 的 cell 级证据。 +逻辑:候选映射只可作为 Plan 输入;生产通用解析必须先校验 Plan 的 Schema、Layout、 + 候选和字段证据身份,不能直接把运行时候选当作业务事实。 +""" + +from __future__ import annotations + +import hashlib +import json +from copy import deepcopy +from dataclasses import dataclass +from typing import Any + + +GENERIC_PARSE_PLAN_VERSION = 'generic_parse_plan.v1' + + +def _checksum(payload: Any) -> str: + """生成稳定 JSON checksum;Plan 身份不得依赖字典插入顺序。""" + encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(encoded.encode('utf-8')).hexdigest() + + +def layout_checksum(layout_snapshot: dict[str, Any]) -> str | None: + """提取结构 Layout 身份;按需坐标补全不应改变已冻结的版面身份。""" + candidate = layout_snapshot.get('layout_candidate') if isinstance(layout_snapshot, dict) else None + return _checksum(candidate) if isinstance(candidate, dict) else None + + +def _field_evidence_errors(candidates: list[dict[str, Any]]) -> list[str]: + """校验每个将进入订单的字段都能回溯到冻结 Layout cell 证据。""" + errors: list[str] = [] + for table_index, table in enumerate(candidates): + if not isinstance(table, dict): + errors.append(f'table:{table_index}:invalid') + continue + for row in table.get('rows') or []: + if not isinstance(row, dict) or str(row.get('role') or '') != 'data': + continue + for field in row.get('fields') or []: + if not isinstance(field, dict) or field.get('value') in (None, ''): + continue + if not field.get('field_id'): + errors.append(f'table:{table_index}:field_id_missing') + if not field.get('evidence_ref') or not field.get('cell_id'): + errors.append(f'table:{table_index}:field_evidence_missing') + return sorted(set(errors)) + + +def compile_generic_parse_plan( + *, + candidates: list[dict[str, Any]], + schema_checksum: str, + layout_snapshot: dict[str, Any], +) -> dict[str, Any]: + """ + 将自动标注候选编译为可冻结 Parse Plan。 + + 自动标注本身不具有生产资格。该函数只记录候选的输入身份和字段证据,后续仍由 + generic_order_gate 检查表/行完整性、必填字段和业务冲突。 + """ + # Plan 冻结前仍在同一 Worker 内构建订单;不得借深拷贝把 Decimal/date 等 + # 业务值提前变成字符串,JSON 落库阶段由 Run 的统一冻结器处理。 + copied = deepcopy(candidates if isinstance(candidates, list) else []) + source_statuses = [ + str(item.get('mapping_status') or 'candidate') + for item in copied if isinstance(item, dict) + ] + errors = _field_evidence_errors(copied) + if not str(schema_checksum or '').strip(): + errors.append('schema_checksum_missing') + resolved_layout_checksum = layout_checksum(layout_snapshot) + if not resolved_layout_checksum: + errors.append('layout_checksum_missing') + if any(status not in {'accepted', 'candidate'} for status in source_statuses): + errors.append('mapping_status_unqualified') + payload = { + 'version': GENERIC_PARSE_PLAN_VERSION, + 'schema_checksum': str(schema_checksum or ''), + 'layout_checksum': resolved_layout_checksum, + 'candidates': copied, + 'candidate_checksum': _checksum(copied), + 'mapping_decisions': [{ + 'page_no': item.get('page_no'), 'table_id': item.get('table_id'), + 'source_mapping_status': str(item.get('mapping_status') or 'candidate'), + 'decision': 'auto_qualified' if str(item.get('mapping_status') or 'candidate') in {'accepted', 'candidate'} else 'rejected', + } for item in copied if isinstance(item, dict)], + 'evidence_errors': sorted(set(errors)), + } + payload['status'] = 'qualified' if not payload['evidence_errors'] else 'rejected' + payload['checksum'] = _checksum(payload) + return payload + + +@dataclass(frozen=True) +class GenericParsePlanValidation: + """生产 Gate 使用的 Parse Plan 校验结论。""" + + passed: bool + reason_codes: list[str] + candidates: list[dict[str, Any]] + + +def validate_generic_parse_plan( + *, + plan: Any, + schema_checksum: str, + layout_snapshot: dict[str, Any], + runtime_candidates: list[dict[str, Any]] | None = None, +) -> GenericParsePlanValidation: + """验证冻结 Plan 未被 Schema、Layout 或候选映射漂移污染。""" + if not isinstance(plan, dict): + return GenericParsePlanValidation(False, ['generic_parse_plan_missing'], []) + candidates = plan.get('candidates') if isinstance(plan.get('candidates'), list) else [] + reasons: list[str] = [] + if str(plan.get('version') or '') != GENERIC_PARSE_PLAN_VERSION: + reasons.append('generic_parse_plan_version_invalid') + payload = {key: value for key, value in plan.items() if key != 'checksum'} + if str(plan.get('checksum') or '') != _checksum(payload): + reasons.append('generic_parse_plan_checksum_invalid') + if str(plan.get('status') or '') != 'qualified': + reasons.append('generic_parse_plan_unqualified') + if str(plan.get('schema_checksum') or '') != str(schema_checksum or ''): + reasons.append('generic_parse_plan_schema_changed') + if str(plan.get('layout_checksum') or '') != str(layout_checksum(layout_snapshot) or ''): + reasons.append('generic_parse_plan_layout_changed') + if str(plan.get('candidate_checksum') or '') != _checksum(candidates): + reasons.append('generic_parse_plan_candidate_changed') + if runtime_candidates is not None and _checksum(runtime_candidates) != str(plan.get('candidate_checksum') or ''): + reasons.append('generic_parse_plan_runtime_candidate_changed') + if plan.get('evidence_errors'): + reasons.append('generic_parse_plan_evidence_missing') + return GenericParsePlanValidation(not reasons, sorted(set(reasons)), candidates) diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py index 15e975fc..5e6d5f59 100644 --- a/backend/app/services/shipping_notice/intake_service.py +++ b/backend/app/services/shipping_notice/intake_service.py @@ -172,6 +172,7 @@ def serialize_intake( *, asset: FileAsset | None = None, include_parse_texts: bool = False, + include_candidate_details: bool = True, ) -> dict[str, Any]: """ 对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。 @@ -179,6 +180,8 @@ def serialize_intake( Args: include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口), 并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。 + include_candidate_details: False 时仅返回恢复输入状态所需的 Candidate 字段, + 避免活跃列表传输 evidence / field_adjudication 等重型审核数据。 """ from app.services.shipping_notice.document_candidate_persist import ( list_intake_candidates, @@ -198,7 +201,10 @@ def serialize_intake( } parse_summary = structured if include_parse_texts else _lean_parse_summary(structured) documents = list_intake_documents(int(intake.id), include_text=include_parse_texts) - candidates = list_intake_candidates(int(intake.id)) + candidates = list_intake_candidates( + int(intake.id), + include_details=include_candidate_details, + ) layout_summary = _serialize_intake_layout_summary(int(intake.id)) payload: dict[str, Any] = { 'intake_no': intake.intake_no, @@ -571,7 +577,14 @@ def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | if conv: query = query.filter(ShippingOrderIntake.conversation_id == conv) rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all() - return [serialize_intake(intake, asset=asset) for intake, asset in rows] + return [ + serialize_intake( + intake, + asset=asset, + include_candidate_details=False, + ) + for intake, asset in rows + ] def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]: @@ -588,7 +601,14 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str ) .all() ) - return [serialize_intake(intake, asset=asset) for intake, asset in rows] + return [ + serialize_intake( + intake, + asset=asset, + include_candidate_details=False, + ) + for intake, asset in rows + ] def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]: diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index a3de3664..8e34636c 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -1,7 +1,7 @@ """ services/shipping_notice/inventory_file_store.py -用途:管理货代发货批次级库存快照文件、任务 link 与解析结果投影。 +用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。 依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。 逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。 """ @@ -30,8 +30,6 @@ from app.services.shipping_notice.inventory_source_gate import ( task_inventory_identity, ) from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version -from app.services.shipping_notice.query_service import list_sorted_batch_tasks - def _can_relink_inventory(task: ShippingNotice) -> bool: """判断任务是否允许被新的批次库存快照影响;终态任务不能回退。""" return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \ @@ -228,13 +226,13 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> ) -def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile: +def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile: """ - 保存库存 Excel 并创建批次级库存快照。 + 保存库存 Excel 并创建任务级库存快照。 - 【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。 + 【AI 触发时机】:用户为当前发货任务上传库存快照时调用。 核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析; - 快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。 + 快照须携带任务正式库存源身份,只绑定当前任务。 """ if not is_inventory_source_stable(task): raise AppError( @@ -360,7 +358,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh ) raise AppError( code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", - message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定", + message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定", http_status=409, ) created_links.append(link) diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 65636141..a734c743 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -18,13 +18,10 @@ from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, ) from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response -from app.services.shipping_notice.inventory_file_store import ( - save_batch_inventory_upload, -) +from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload from app.services.shipping_notice.query_service import ( get_task_by_ref, resolve_task_from_payload, - serialize_batch_for_tool, serialize_task_for_tool, ) from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues @@ -176,7 +173,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: detail=t("workflow.inventory.uploading_detail", lang=lang).format(filename=filename), ) db.session.flush() - inv_file = save_batch_inventory_upload(task, upload) + inv_file = save_task_inventory_upload(task, upload) inventory_lines = [ item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict) ] @@ -220,7 +217,6 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: { "inventory_file_no": inv_file.inventory_file_no, "share_mode": inv_file.share_mode, - "batch_no": None, }, ) return inventory_loaded_response( diff --git a/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py b/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py deleted file mode 100644 index a8c5ca75..00000000 --- a/backend/app/services/shipping_notice/legacy_stp_job_admin_service.py +++ /dev/null @@ -1,297 +0,0 @@ -""" -backend/app/services/shipping_notice/legacy_stp_job_admin_service.py - -用途:Phase 5-1 —— 管理员历史 STP Job 面板的只读投影服务(928/929 运维面板专用)。 -依赖:models.job.Job、JobType(若有)、ShippingOrderReviewCase。 -逻辑: - 1. list_admin_legacy_stp_jobs —— 按 domain=shipping_notice + job_type=shipping_stp_auto_create - + status IN {failed,dead} 分页返回;支持筛选 case_no / q / error_code / created_from / created_to。 - 2. get_admin_legacy_stp_job —— 单条 Job 详情 + 关联 Review Case(若可通过 reference_key==case_no 回链)。 -禁止事项(严格 fail-closed): - • 不允许写任何数据(禁 Job.status 修改,禁 db.session.commit/add/flush 等)。 - • 不输出敏感字段(result_json 中若含 token/password 自动脱敏)。 - • 所有接口仅 allow_admin,路由层 require_admin 再守门一道。 -""" - -from __future__ import annotations - -import re -from datetime import datetime -from typing import Any - -from sqlalchemy import and_, or_ - -from app import db - - -# 失败 / 死 Job 白名单:历史 928/929 仅针对 shipping_stp_auto_create -_LEGACY_DOMAIN = 'shipping_notice' -_LEGACY_JOB_TYPES: frozenset[str] = frozenset({ - 'shipping_stp_auto_create', -}) -_LEGACY_STATUSES: frozenset[str] = frozenset({'failed', 'dead'}) - -# 脱敏正则(非常粗:防止 secret/password/token/key 等明文进入管理面板) -_SENSITIVE_KEY_RE = re.compile( - r'(password|passwd|secret|token|api[_-]?key|credential|authorization)', - flags=re.IGNORECASE, -) - - -def _mask_sensitive(obj: Any) -> Any: - """递归递归脱敏 dict/list 中疑似密钥字段的值(fail-safe,不抛错)。""" - if isinstance(obj, dict): - out: dict[str, Any] = {} - for k, v in obj.items(): - if isinstance(k, str) and _SENSITIVE_KEY_RE.search(k): - out[k] = '***MASKED***' - else: - out[k] = _mask_sensitive(v) - return out - if isinstance(obj, list): - return [_mask_sensitive(i) for i in obj] - if isinstance(obj, tuple): - return tuple(_mask_sensitive(i) for i in obj) - return obj - - -def _serialize_job_row(job) -> dict[str, Any]: - """把 Job ORM 行 → 管理员摘要 JSON(只读投影)。""" - result_json = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {} - payload_json = dict(job.payload_json or {}) if isinstance(job.payload_json, dict) else {} - blocking_reason = ( - result_json.get('blocking_reason') - or result_json.get('reason_code') - or result_json.get('error_code') - or None - ) - if isinstance(blocking_reason, dict): - blocking_reason = blocking_reason.get('code') if isinstance(blocking_reason.get('code'), str) else None - return { - 'job_id': int(job.id), - 'domain': str(job.domain or ''), - 'job_type': str(job.job_type or ''), - 'status': str(job.status or ''), - 'business_ref': str(job.business_ref or ''), - 'reference_key': str(getattr(job, 'reference_key', None) or ''), # 兼容旧 Job - 'case_no': ( - str(getattr(job, 'reference_key', None) or '') or - str(payload_json.get('case_no') or '') or None - ), - 'priority': int(job.priority or 0), - 'attempts': int(job.attempts or 0), - 'max_attempts': int(job.max_attempts or 0), - 'message': str(job.message or '') or None, - 'error_message': str(job.error_message or '') or None, - 'error_code': str(result_json.get('error_code') or ''), - 'blocking_reason': (str(blocking_reason) if blocking_reason else None), - 'retryable': bool(result_json.get('retryable')) if result_json.get('retryable') is not None else None, - 'next_action': result_json.get('next_action'), - 'retry_of_job_id': (int(job.retry_of_job_id) if job.retry_of_job_id else None), - 'created_by_id': (int(job.created_by_id) if job.created_by_id else None), - 'result_json_masked': _mask_sensitive(result_json), - 'payload_json_masked': _mask_sensitive(payload_json), - 'created_at': str(job.created_at.isoformat()) if isinstance(job.created_at, datetime) else None, - 'updated_at': str(job.updated_at.isoformat()) if isinstance(job.updated_at, datetime) else None, - 'started_at': str(job.started_at.isoformat()) if isinstance(job.started_at, datetime) else None, - 'finished_at': str(job.finished_at.isoformat()) if isinstance(job.finished_at, datetime) else None, - } - - -def _parse_iso_dt(value: str | None, *, field: str): - """解析可选 ISO 日期时间;抛 ValidationError。""" - from app.core.errors import ValidationError - - if value in (None, ''): - return None - try: - text = str(value).strip() - if text.endswith('Z'): - text = text[:-1] + '+00:00' - return datetime.fromisoformat(text) - except ValueError as exc: - raise ValidationError(f'{field} must be ISO datetime (YYYY-MM-DDTHH:MM:SS)') from exc - - -def list_admin_legacy_stp_jobs( - *, - page: int = 1, - page_size: int = 25, - status: str | None = None, - job_type: str | None = None, - q: str | None = None, - case_no: str | None = None, - error_code: str | None = None, - blocking_reason: str | None = None, - created_from: str | None = None, - created_to: str | None = None, - sort: str = '-created_at', -) -> dict[str, Any]: - """ - 管理员只读列表:domain=shipping_notice + job_type=shipping_stp_auto_create + status IN {failed, dead}。 - 用于运维面板快速定位历史 928/929 这类失败死 Job。 - """ - from app.core.errors import ValidationError - from app.models.job import Job - from app import db # type: ignore - - if not isinstance(page, int) or page < 1: - raise ValidationError('page must be positive integer') - if not isinstance(page_size, int) or not 1 <= page_size <= 100: - raise ValidationError('page_size must be between 1 and 100') - if status and str(status) not in _LEGACY_STATUSES: - raise ValidationError(f'status must be one of: {sorted(_LEGACY_STATUSES)}') - if job_type and str(job_type) not in _LEGACY_JOB_TYPES: - raise ValidationError(f'job_type must be one of: {sorted(_LEGACY_JOB_TYPES)}') - - created_from_dt = _parse_iso_dt(created_from, field='created_from') - created_to_dt = _parse_iso_dt(created_to, field='created_to') - - # 只拿失败/死 STP Job - where = [ - Job.domain == _LEGACY_DOMAIN, - Job.job_type.in_(list(_LEGACY_JOB_TYPES)), - Job.status.in_(list(_LEGACY_STATUSES)), - ] - if status: - where.append(Job.status == str(status)) - if job_type: - where.append(Job.job_type == str(job_type)) - if case_no: - case_no_s = str(case_no).strip() - where.append(or_( - getattr(Job, 'reference_key', None) == case_no_s - if hasattr(Job, 'reference_key') - else False, - # 兼容旧模型:从 payload_json->case_no 查(JSON 跨库差异大,仅包含匹配) - Job.payload_json.contains({'case_no': case_no_s}), - )) - if error_code: - where.append(Job.result_json.contains({'error_code': str(error_code).strip()})) - if blocking_reason: - br = str(blocking_reason).strip() - where.append(or_( - Job.result_json.contains({'blocking_reason': br}), - Job.result_json.contains({'reason_code': br}), - )) - if created_from_dt is not None: - where.append(Job.created_at >= created_from_dt) - if created_to_dt is not None: - where.append(Job.created_at <= created_to_dt) - if q and str(q).strip(): - qs = f'%{str(q).strip()}%' - where.append(or_( - Job.business_ref.ilike(qs), - Job.message.ilike(qs), - Job.error_message.ilike(qs), - )) - - # 排序 - sort_exprs = [] - for raw in str(sort or '-created_at').split(','): - s = raw.strip() - if not s: - continue - descending = s.startswith('-') - key = s[1:] if descending else s - if key == 'created_at': - expr = Job.created_at.desc() if descending else Job.created_at.asc() - elif key == 'updated_at': - expr = Job.updated_at.desc() if descending else Job.updated_at.asc() - elif key == 'id': - expr = Job.id.desc() if descending else Job.id.asc() - elif key == 'attempts': - expr = Job.attempts.desc() if descending else Job.attempts.asc() - else: - continue - sort_exprs.append(expr) - if not sort_exprs: - sort_exprs = [Job.created_at.desc()] - - stmt = db.select(Job).where(and_(*where)).order_by(*sort_exprs) - total = len(db.session.scalars(db.select(Job.id).where(and_(*where))).all()) - items = db.session.scalars( - stmt.offset((int(page) - 1) * int(page_size)).limit(int(page_size)), - ).all() - return { - 'items': [_serialize_job_row(j) for j in items], - 'pagination': { - 'page': int(page), - 'page_size': int(page_size), - 'total': int(total), - 'total_pages': ((int(total) + int(page_size) - 1) // int(page_size)) if total > 0 else 0, - }, - 'filters': { - 'domain': _LEGACY_DOMAIN, - 'job_types': sorted(_LEGACY_JOB_TYPES), - 'statuses': sorted(_LEGACY_STATUSES), - }, - } - - -def get_admin_legacy_stp_job(job_id: int) -> dict[str, Any]: - """ - 管理员单条历史 STP Job 详情:返回 Job 投影 + 回链 Review Case(若 reference_key==case_no 存在)。 - 仅允许失败/死 Job:若 Job 是 queued/running → 抛 ValidationError(避免管理员误对活跃 Job 做 replay)。 - """ - from app.core.errors import NotFoundError, ValidationError - from app.models.job import Job - from app.models.shipping.shipping_order_review_case import ShippingOrderReviewCase - - job = db.session.get(Job, int(job_id)) - if job is None: - raise NotFoundError(f'legacy job not found: {job_id}', code='SHIPPING.REVIEW_CASE_NOT_FOUND') - if str(job.domain or '') != _LEGACY_DOMAIN: - raise ValidationError(f'legacy job must be domain={_LEGACY_DOMAIN}') - if str(job.job_type or '') not in _LEGACY_JOB_TYPES: - raise ValidationError(f'legacy job must be job_type in {sorted(_LEGACY_JOB_TYPES)}') - if str(job.status or '') not in _LEGACY_STATUSES: - raise ValidationError( - f'legacy job must be status in {sorted(_LEGACY_STATUSES)} (current={job.status})', - code='SHIPPING.RECONCILE_INVALID_USER_ACTION', - ) - job_row = _serialize_job_row(job) - - # 回链 Review Case(只读:若能通过 reference_key==case_no 找得到) - case_no = ( - str(getattr(job, 'reference_key', None) or '') - or str((job.payload_json or {}).get('case_no') or '') - or None - ) - case_row: dict[str, Any] | None = None - if case_no: - case_obj = ( - ShippingOrderReviewCase.query - .filter_by(case_no=str(case_no).strip()) - .order_by(ShippingOrderReviewCase.id.desc()) - .first() - ) - if case_obj is not None: - case_row = { - 'case_id': int(case_obj.id), - 'case_no': str(case_obj.case_no or ''), - 'status': str(case_obj.status or ''), - 'candidate_id': int(case_obj.candidate_id) if case_obj.candidate_id else None, - 'confirmed_task_id': int(case_obj.confirmed_task_id) if case_obj.confirmed_task_id else None, - 'document_id': int(case_obj.document_id) if case_obj.document_id else None, - 'owner_user_id': int(case_obj.owner_user_id) if case_obj.owner_user_id else None, - 'created_at': str(case_obj.created_at.isoformat()) if getattr(case_obj, 'created_at', None) else None, - 'updated_at': str(case_obj.updated_at.isoformat()) if getattr(case_obj, 'updated_at', None) else None, - } - return { - 'job': job_row, - 'case': case_row, - 'replay_plan': { - 'supported': True, - 'recommended_user_action': ( - 'force_create' - if case_row and str(case_row.get('status') or '') in {'draft', 'ready', 'unreviewed'} - else 'create_revision' - ), - 'needs_replay_mode': bool(case_row and job_row.get('case_no') != case_row.get('case_no')), - 'reconcile_and_progress_endpoint': ( - f'/workspace/shipping-notice/order-review-cases/{case_no}/reconcile-and-progress' - if case_no else None - ), - }, - } diff --git a/backend/app/services/shipping_notice/legacy_supplement_conflict_reassessment_service.py b/backend/app/services/shipping_notice/legacy_supplement_conflict_reassessment_service.py new file mode 100644 index 00000000..f800a0eb --- /dev/null +++ b/backend/app/services/shipping_notice/legacy_supplement_conflict_reassessment_service.py @@ -0,0 +1,296 @@ +""" +services/shipping_notice/legacy_supplement_conflict_reassessment_service.py + +用途:将历史邮件正文补充冲突升级为可展示、可追溯的统一 Finding,并重算 Candidate 资格。 +依赖:ShippingOrderCandidate/Run、candidate_qualification_service、fulfillment_audit。 +逻辑:历史 `{field, reason}` 没有双方值或证据,不能猜测为已解决;本服务仅将其转为 + `supplement_conflict_evidence_insufficient`,保留 blocking 门禁并给出重新识别恢复入口。 + 已含 conflict_key 的新 Finding 不改写;真实值比较仍由冻结输入的新解析链负责。 +""" + +from __future__ import annotations + +from typing import Any + +from app.extensions import db +from app.models import ( + ShippingOrderCandidate, + ShippingOrderProcessingPlan, + ShippingOrderProcessingRun, + ShippingOrderProcessingUnit, +) +from app.services.shipping_notice.candidate_qualification_service import ( + recalculate_candidate_qualification, +) +from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit +from app.services.shipping_notice.order_supplement_merge import merge_email_supplements + + +_LEGACY_REASON = 'supplement_field_conflict' +_EVIDENCE_GAP_REASON = 'supplement_conflict_evidence_insufficient' + + +def _legacy_finding_key(item: dict[str, Any]) -> str: + """为无法复原证据的旧 Finding 生成稳定键,避免继续以无键记录阻断。""" + field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field' + try: + line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1 + except (TypeError, ValueError): + line_index = -1 + return f'{line_index}:{field}' + + +def is_legacy_supplement_conflict(item: Any) -> bool: + """判断记录是否是没有稳定裁决身份与双方证据的历史正文补充冲突。""" + return ( + isinstance(item, dict) + and str(item.get('reason') or '').strip() == _LEGACY_REASON + and not str(item.get('conflict_key') or '').strip() + ) + + +def upgrade_legacy_supplement_conflicts(conflicts: Any) -> tuple[list[Any], int]: + """ + 将旧简略冲突升级为统一证据缺失 Finding。 + + 核心逻辑:旧记录仅有字段与原因,缺失 PDF/EML 原值、document_id、evidence_ref, + 无法安全裁决或判定为格式等价;因此保持 fail-closed,但使 Case 显示明确恢复动作。 + + Returns: + (升级后的冲突列表, 本次升级数量)。 + """ + source = list(conflicts or []) if isinstance(conflicts, list) else [] + upgraded: list[Any] = [] + changed = 0 + seen_keys: set[str] = set() + for item in source: + if not is_legacy_supplement_conflict(item): + upgraded.append(item) + if isinstance(item, dict): + key = str(item.get('conflict_key') or '').strip() + if key: + seen_keys.add(key) + continue + key = _legacy_finding_key(item) + if key in seen_keys: + changed += 1 + continue + seen_keys.add(key) + field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field' + try: + line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1 + except (TypeError, ValueError): + line_index = -1 + upgraded.append({ + 'conflict_key': key, + 'severity': 'blocking', + 'reason': _EVIDENCE_GAP_REASON, + 'resolution_status': 'unresolved', + 'field': field, + 'scope': str(item.get('scope') or 'unscoped'), + 'line_index': line_index if line_index >= 0 else None, + 'values': [], + 'sources': [], + 'rule_version': 'legacy-supplement-conflict.v1', + 'legacy_reason': _LEGACY_REASON, + 'recovery_action': 'reparse_current_pdf', + }) + changed += 1 + return upgraded, changed + + +def _without_legacy_supplement_conflicts(conflicts: Any) -> list[Any]: + """去除待重建的旧 Finding,保留其他解析/业务门禁。""" + return [ + item for item in (conflicts or []) + if not is_legacy_supplement_conflict(item) + ] if isinstance(conflicts, list) else [] + + +def _supplement_findings(conflicts: Any) -> list[dict[str, Any]]: + """从重算订单结果读取当前正文补充 Finding,不借用其他门禁事实。""" + return [ + item for item in (conflicts or []) + if isinstance(item, dict) + and str(item.get('reason') or '').strip() == _LEGACY_REASON + ] if isinstance(conflicts, list) else [] + + +def reassess_legacy_supplement_conflicts_from_frozen_order( + *, + candidate_conflicts: Any, + frozen_order: Any, + supplements_by_intake: Any, + schema_definition: Any, +) -> tuple[list[Any], str, int]: + """ + 使用冻结订单和邮件补充事实按当前合并规则重算旧冲突。 + + Returns: + (新冲突, rebuilt|evidence_insufficient|not_applicable, 处理的旧记录数)。 + """ + legacy_count = sum(1 for item in (candidate_conflicts or []) if is_legacy_supplement_conflict(item)) \ + if isinstance(candidate_conflicts, list) else 0 + if not legacy_count: + return list(candidate_conflicts or []) if isinstance(candidate_conflicts, list) else [], 'not_applicable', 0 + if not ( + isinstance(frozen_order, dict) + and isinstance(supplements_by_intake, dict) + and isinstance(schema_definition, dict) + and isinstance(schema_definition.get('fields'), list) + ): + upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts) + return upgraded, 'evidence_insufficient', legacy_count + replay_order = dict(frozen_order) + replay_order['conflicts'] = _without_legacy_supplement_conflicts(replay_order.get('conflicts')) + try: + rebuilt_order = merge_email_supplements( + orders=[replay_order], + supplements_by_intake=supplements_by_intake, + schema_definition=schema_definition, + )[0] + except (TypeError, ValueError): + upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts) + return upgraded, 'evidence_insufficient', legacy_count + # Candidate 的非补充门禁由其自身持有;只用重算结果替换旧正文补充项。 + preserved = _without_legacy_supplement_conflicts(candidate_conflicts) + rebuilt = _supplement_findings(rebuilt_order.get('conflicts')) + return [*preserved, *rebuilt], 'rebuilt', legacy_count + + +def _frozen_reassessment_inputs( + *, candidate: ShippingOrderCandidate, run: ShippingOrderProcessingRun | None, +) -> tuple[dict[str, Any] | None, dict[int, dict[str, Any]] | None, dict[str, Any] | None]: + """按 Candidate 所属 Unit 定位冻结订单、邮件补充与 Schema;歧义时拒绝猜测。""" + if run is None: + return None, None, None + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else None + supplements = { + int(intake.get('intake_id') or 0): supplement + for intake in snapshot.get('intakes') or [] if isinstance(intake, dict) + for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict) + if int(intake.get('intake_id') or 0) > 0 + } + units = ( + ShippingOrderProcessingUnit.query + .join(ShippingOrderProcessingPlan, ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id) + .filter( + ShippingOrderProcessingPlan.run_id == int(run.id), + ShippingOrderProcessingUnit.document_id == int(candidate.primary_document_id), + ) + .order_by(ShippingOrderProcessingUnit.id.asc()) + .all() + ) + if len(units) != 1: + return None, supplements, definition + orders = (units[0].result_json or {}).get('orders') if isinstance(units[0].result_json, dict) else None + if not isinstance(orders, list): + return None, supplements, definition + index = candidate.source_order_index + if isinstance(index, int) and 0 <= index < len(orders) and isinstance(orders[index], dict): + return dict(orders[index]), supplements, definition + exact = [ + item for item in orders + if isinstance(item, dict) + and int(item.get('primary_document_id') or 0) == int(candidate.primary_document_id) + ] + return (dict(exact[0]) if len(exact) == 1 else None), supplements, definition + + +def reassess_legacy_supplement_conflicts( + *, + actor_id: int, + request_id: str | None = None, + candidate_no: str | None = None, + run_no: str | None = None, + include_all: bool = False, +) -> dict[str, Any]: + """ + 对指定范围的旧正文补充冲突执行一次可审计重评估。 + + AI 触发时机:仅管理员确认历史数据修复时调用;普通用户保存草稿或读取 Case 不调用。 + 范围必须指定 Candidate、Run,或显式 include_all,避免误触发全量写操作。 + """ + normalized_candidate_no = str(candidate_no or '').strip().upper() or None + normalized_run_no = str(run_no or '').strip().upper() or None + if not (normalized_candidate_no or normalized_run_no or include_all): + raise ValueError('candidate_no, run_no, or include_all is required') + + query = ShippingOrderCandidate.query.filter(ShippingOrderCandidate.is_current_version.is_(True)) + if normalized_candidate_no: + query = query.filter(ShippingOrderCandidate.candidate_no == normalized_candidate_no) + if normalized_run_no: + query = query.join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderCandidate.order_extraction_run_id, + ).filter(ShippingOrderProcessingRun.run_no == normalized_run_no) + + report = { + 'scanned_count': 0, + 'legacy_conflict_candidate_count': 0, + 'upgraded_finding_count': 0, + 'qualification_recalculated_count': 0, + 'candidate_nos': [], + 'scope': { + 'candidate_no': normalized_candidate_no, + 'run_no': normalized_run_no, + 'include_all': bool(include_all), + }, + } + for candidate in query.with_for_update().all(): + report['scanned_count'] += 1 + legacy_count = sum( + 1 for item in (candidate.conflicts_json or []) if is_legacy_supplement_conflict(item) + ) if isinstance(candidate.conflicts_json, list) else 0 + if not legacy_count: + continue + run = ( + db.session.get(ShippingOrderProcessingRun, int(candidate.order_extraction_run_id)) + if candidate.order_extraction_run_id else None + ) + frozen_order, supplements, definition = _frozen_reassessment_inputs(candidate=candidate, run=run) + after_conflicts, reassessment_status, changed = reassess_legacy_supplement_conflicts_from_frozen_order( + candidate_conflicts=candidate.conflicts_json, + frozen_order=frozen_order, + supplements_by_intake=supplements, + schema_definition=definition, + ) + before = {'legacy_supplement_conflict_count': legacy_count} + candidate.conflicts_json = after_conflicts + report['legacy_conflict_candidate_count'] += 1 + if reassessment_status == 'evidence_insufficient': + report['upgraded_finding_count'] += changed + else: + report.setdefault('rebuilt_candidate_count', 0) + report['rebuilt_candidate_count'] += 1 + report['candidate_nos'].append(str(candidate.candidate_no)) + recalculate_candidate_qualification( + candidate=candidate, + run=run, + evaluated_by_id=actor_id, + request_id=request_id, + ) + report['qualification_recalculated_count'] += 1 + record_fulfillment_audit( + event_type='legacy_supplement_conflict_reassessed', + aggregate_type='shipping_notice_candidate', + aggregate_id=str(candidate.candidate_no), + action='reassess_legacy_supplement_conflict', + actor_type='admin', + actor_id=actor_id, + run_no=str(run.run_no) if run is not None else None, + reason_code=_EVIDENCE_GAP_REASON, + before=before, + after={ + 'reassessment_status': reassessment_status, + 'replaced_legacy_finding_count': changed, + 'remaining_supplement_finding_count': len(_supplement_findings(after_conflicts)), + 'recovery_action': 'reparse_current_pdf' if reassessment_status == 'evidence_insufficient' else None, + }, + metadata={'request_id': request_id, 'migration_version': 'legacy-supplement-conflict.v1'}, + source='legacy_supplement_conflict_reassessment', + ) + report['candidate_nos'].sort() + return report diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 5cc5d6f9..7b702675 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -2,8 +2,8 @@ services/shipping_notice/lifecycle_projection.py 用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。 -依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。 -逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。 +依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。 +逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 """ @@ -48,24 +48,29 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { 'manual_upload_handoff': 'freight_upload', } -# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。 -LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = ( - ('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}), - ('order_review', { - 'customer_resolving', 'duplicate_checking', 'order_creating', 'review_required', - 'waiting_review', 'waiting_human_review', 'waiting_human', 'pre_ot_stp', 'order_review', - }), - ('fulfillment_prep', { - 'inventory_source_resolving', 'inventory_fetching', 'inventory_fetch', 'inventory_preparation', - 'inventory_candidates_calculated', 'inventory_candidates_frozen', 'inventory_snapshots_ready', - 'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating', - 'excel_generate', 'excel_generated', - }), - ('freight_upload', { - 'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'upload_complete', 'completed', - }), -) - +# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于 +# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在 +# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。 +LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { + 'upload_received': 'intake_parse', + 'email_parsing': 'intake_parse', + 'document_parsing': 'intake_parse', + 'email_adjudicating': 'intake_parse', + 'candidate_creating': 'intake_parse', + 'waiting_review': 'order_review', + 'customer_resolving': 'order_review', + 'duplicate_checking': 'order_review', + 'inventory_source_resolving': 'order_review', + 'order_creating': 'fulfillment_prep', + 'inventory_fetching': 'fulfillment_prep', + 'inventory_preparation': 'fulfillment_prep', + 'inventory_matching': 'fulfillment_prep', + 'inventory_sufficiency': 'fulfillment_prep', + 'excel_generating': 'fulfillment_prep', + 'freight_uploading': 'freight_upload', + 'manual_upload_handoff': 'freight_upload', + 'completed': 'upload_complete', +} def lifecycle_entries( *, @@ -104,14 +109,16 @@ def project_lifecycle( *, current_gate: dict[str, Any] | None, blocking_reason: dict[str, Any] | None, - legacy_stage: str | None, has_candidate_context: bool, has_intake_parse_context: bool = False, verified_upload_success: bool = False, + processing_stage: str | None = None, ) -> dict[str, Any]: - """按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。 + """按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。 - ``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。 + ``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能 + 授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算 + 阶段或放开按钮。 """ gate = current_gate if isinstance(current_gate, dict) else {} gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() @@ -123,6 +130,11 @@ def project_lifecycle( elif gate_code in LIFECYCLE_STAGE_BY_GATE: lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code] authority = 'process_gate' + elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE: + lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[ + str(processing_stage or '').strip().lower() + ] + authority = 'processing_stage' else: reason = blocking_reason if isinstance(blocking_reason, dict) else {} reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip() @@ -131,12 +143,8 @@ def project_lifecycle( lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[owning_gate] authority = 'blocking_reason' else: - normalized_legacy = str(legacy_stage or '').strip().lower() - lifecycle_stage = next( - (code for code, aliases in LIFECYCLE_STAGE_RANGES if normalized_legacy in aliases), - normalized_legacy if normalized_legacy in LIFECYCLE_STAGE_CODES else None, - ) - authority = 'legacy_fallback' if lifecycle_stage else 'unclassified' + lifecycle_stage = None + authority = 'unclassified' return { 'lifecycle_stage': lifecycle_stage, 'lifecycle_entries': lifecycle_entries( diff --git a/backend/app/services/shipping_notice/open_existing_reservation_backfill.py b/backend/app/services/shipping_notice/open_existing_reservation_backfill.py index df24e08c..63da9d40 100644 --- a/backend/app/services/shipping_notice/open_existing_reservation_backfill.py +++ b/backend/app/services/shipping_notice/open_existing_reservation_backfill.py @@ -1,9 +1,9 @@ """ backend/app/services/shipping_notice/open_existing_reservation_backfill.py -用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到旧任务(兼容入口)。 +用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到既有任务。 依赖:task_candidate_reconciliation、tool_common。 -逻辑:batch_from_intakes 仍调用本模块;内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。 +逻辑:内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/order_auto_freeze_execution.py b/backend/app/services/shipping_notice/order_auto_freeze_execution.py deleted file mode 100644 index 7634bd94..00000000 --- a/backend/app/services/shipping_notice/order_auto_freeze_execution.py +++ /dev/null @@ -1,353 +0,0 @@ -""" -services/shipping_notice/order_auto_freeze_execution.py - -用途:消费 Run 级自动冻结门禁摘要,把当前 Run 已接受的候选订单落成 Task 并冻结为 Snapshot。 -依赖:Run/Candidate/Task 模型、候选建批编排与订单冻结服务。 -逻辑:只有当 run.auto_freeze_policy_json 已明确放行时才执行;执行范围严格限定在当前 Run, - 建单与冻结均只处理本轮 eligible 的 accepted + selected 候选集合,禁止扩大到 Run 内其它已消费候选; - 单任务冻结使用 savepoint,失败回滚该任务半成品,禁止外层误提交已冻结状态。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any - -from app import db -from app.models import ( - ShippingOrderCandidate, - ShippingOrderCustomerMatch, - ShippingOrderExtraction, - ShippingOrderProcessingRun, - ShippingNotice, -) -from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates -from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot - - -def maybe_execute_run_auto_freeze( - *, - run: ShippingOrderProcessingRun, - submission_result: dict[str, Any], -) -> dict[str, Any]: - """在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。""" - result = dict(submission_result or {}) - policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {} - if not bool(policy.get('enabled')): - return result - - # [STEP 1] 冻结候选集合在建单前冻结;后续冻结不得重新扩大范围。 - candidate_nos = _eligible_candidate_nos(run) - create_result: dict[str, Any] | None = None - if candidate_nos: - create_result = create_shipping_batch_from_candidates( - user_id=int(run.user_id), - conversation_id=run.conversation_id, - intake_nos=_snapshot_intake_nos(run), - candidate_nos=candidate_nos, - create_idempotency_key=f"extract:{str(run.input_snapshot_hash or '')[:48]}", - ) - - frozen_task_nos, blocked_tasks = _freeze_created_tasks( - run=run, - policy=policy, - candidate_nos=candidate_nos, - ) - refreshed = _refresh_submission_result( - run=run, - previous_result=result, - create_result=create_result, - ) - refreshed['auto_freeze'] = { - 'enabled': True, - 'frozen_task_nos': frozen_task_nos, - 'blocked_tasks': blocked_tasks, - 'eligible_candidate_nos': list(candidate_nos), - } - return refreshed - - -def _eligible_candidate_nos(run: ShippingOrderProcessingRun) -> list[str]: - """只返回当前 Run 中可以自动建单的 accepted + selected 候选。""" - rows = ( - ShippingOrderCandidate.query - .filter_by( - order_extraction_run_id=int(run.id), - is_current_version=True, - candidate_status='accepted', - selected=True, - ) - .filter(ShippingOrderCandidate.consumed_task_id.is_(None)) - .order_by(ShippingOrderCandidate.id.asc()) - .all() - ) - return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()] - - -def _snapshot_intake_nos(run: ShippingOrderProcessingRun) -> list[str]: - """从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。""" - snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} - intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else [] - return [ - str(item.get('intake_no') or '').strip().upper() - for item in intakes - if isinstance(item, dict) and str(item.get('intake_no') or '').strip() - ] - - -def _freeze_created_tasks( - *, - run: ShippingOrderProcessingRun, - policy: dict[str, Any], - candidate_nos: list[str], -) -> tuple[list[str], list[dict[str, Any]]]: - """ - 冻结本轮 eligible 且已消费的任务。 - - 核心逻辑:候选集合必须与建单前 `_eligible_candidate_nos` 完全一致; - 禁止扫描 Run 下全部 consumed 候选(避免误冻人工/其它路径任务)。 - """ - eligible = { - str(item).strip() - for item in (candidate_nos or []) - if str(item).strip() - } - if not eligible: - return [], [] - - candidates = ( - ShippingOrderCandidate.query - .filter_by( - order_extraction_run_id=int(run.id), - is_current_version=True, - candidate_status='accepted', - selected=True, - ) - .filter(ShippingOrderCandidate.consumed_task_id.isnot(None)) - .filter(ShippingOrderCandidate.candidate_no.in_(tuple(eligible))) - .order_by(ShippingOrderCandidate.id.asc()) - .all() - ) - frozen_task_nos: list[str] = [] - blocked_tasks: list[dict[str, Any]] = [] - for candidate in candidates: - if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing': - continue - task = db.session.get(ShippingNotice, int(candidate.consumed_task_id or 0)) - if task is None: - continue - # [STEP] 单任务 savepoint:冻结失败必须回滚本任务已 flush 的快照/指针/客户继承, - # 禁止外层事务提交“返回阻断但库内已冻结”的半成品。 - try: - with db.session.begin_nested(): - _inherit_confirmed_ordering_customer(run=run, task=task, policy=policy) - snapshot = freeze_order_snapshot( - task, - actor_id=None, - expected_order_data_version=int(task.order_data_version or 1), - freeze_mode='auto', - auto_freeze_policy=policy, - ) - # [STEP] 与冻结同 savepoint:进度事件失败则回滚本任务冻结半成品。 - from app.services.shipping_notice.order_extraction_progress import record_run_progress - - record_run_progress( - run=run, - event_code='order_auto_frozen', - summary={ - 'task_no': str(task.task_no or ''), - 'candidate_no': str(candidate.candidate_no or ''), - 'snapshot_id': int(getattr(snapshot, 'id', 0) or 0) or None, - 'freeze_source': str((policy or {}).get('freeze_source') or '') or None, - }, - commit=False, - ) - frozen_task_nos.append(str(task.task_no or f"snapshot-{snapshot.id}")) - except Exception as exc: # pragma: no cover - 阻断明细由调用侧测试断言 - blocked_tasks.append({ - 'candidate_no': str(candidate.candidate_no or ''), - 'task_no': str(task.task_no or ''), - 'code': str(getattr(exc, 'code', '') or ''), - 'message': str(exc), - 'details': getattr(exc, 'details', None), - }) - return frozen_task_nos, blocked_tasks - - -def _inherit_confirmed_ordering_customer( - *, - run: ShippingOrderProcessingRun, - task: ShippingNotice, - policy: dict[str, Any], -) -> None: - """把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。""" - confirmed_ids = sorted({ - int(item) - for item in (policy.get('confirmed_customer_ids') or []) - if str(item).strip().isdigit() - }) - if len(confirmed_ids) != 1 or not task.current_order_extraction_id: - return - extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id)) - if extraction is None: - return - target = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(extraction.id), - role='bill_to', - ).one_or_none() - if ( - target is not None - and target.status == 'confirmed' - and int(target.customer_id or 0) == confirmed_ids[0] - and bool(target.customer_short_code_snapshot) - and bool(target.identity_fingerprint) - and bool(target.identity_rule_version) - ): - return - if target is not None and target.status == 'confirmed' and target.customer_id not in {None, confirmed_ids[0]}: - return - source = ( - ShippingOrderCustomerMatch.query - .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) - .filter( - ShippingOrderExtraction.run_id == int(run.id), - ShippingOrderCustomerMatch.role == 'bill_to', - ShippingOrderCustomerMatch.status == 'confirmed', - ShippingOrderCustomerMatch.customer_id == confirmed_ids[0], - ) - .order_by(ShippingOrderCustomerMatch.confirmed_at.desc(), ShippingOrderCustomerMatch.id.desc()) - .first() - ) - if source is None: - return - if target is None: - target = ShippingOrderCustomerMatch( - extraction_id=int(extraction.id), - role='bill_to', - identity_components_json={}, - candidates_json=[], - ) - db.session.add(target) - target.raw_name = source.raw_name - target.normalized_name = source.normalized_name - target.source_system = source.source_system - target.external_code = source.external_code - target.identity_fingerprint = source.identity_fingerprint - target.identity_rule_version = source.identity_rule_version - target.identity_components_json = dict(source.identity_components_json or {}) - target.status = 'confirmed' - target.customer_id = source.customer_id - target.site_id = source.site_id - target.customer_name_snapshot = source.customer_name_snapshot - target.customer_short_code_snapshot = source.customer_short_code_snapshot - target.candidates_json = list(source.candidates_json or []) - target.resolution_method = source.resolution_method or 'run_auto_freeze_inherited' - target.confirmation_reason = source.confirmation_reason or 'run_auto_freeze_inherited' - target.confirmed_by_id = source.confirmed_by_id - target.confirmed_at = source.confirmed_at or datetime.utcnow() - target.updated_at = datetime.utcnow() - db.session.flush() - - -def _refresh_submission_result( - *, - run: ShippingOrderProcessingRun, - previous_result: dict[str, Any], - create_result: dict[str, Any] | None, -) -> dict[str, Any]: - """按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。""" - candidates = ( - ShippingOrderCandidate.query - .filter_by(order_extraction_run_id=int(run.id), is_current_version=True) - .order_by(ShippingOrderCandidate.id.asc()) - .all() - ) - pending_by_candidate_no = { - str(item.get('candidate_no') or ''): item - for item in previous_result.get('pending_orders') or [] - if isinstance(item, dict) and str(item.get('candidate_no') or '').strip() - } - created: list[dict[str, Any]] = [] - opened_existing: list[dict[str, Any]] = [] - pending_orders: list[dict[str, Any]] = [] - created_with_missing_fields_count = 0 - for candidate in candidates: - if candidate.consumed_task_id is None: - pending_item = pending_by_candidate_no.get(str(candidate.candidate_no or '')) - if pending_item is not None: - pending_orders.append(pending_item) - continue - task = db.session.get(ShippingNotice, int(candidate.consumed_task_id)) - if task is None: - continue - if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing': - opened_existing.append({ - 'candidate_no': candidate.candidate_no, - 'task_no': task.task_no, - 'batch_no': None, - }) - continue - created.append({'task_no': task.task_no}) - if candidate.missing_fields_json: - created_with_missing_fields_count += 1 - created_with_missing_fields_count = min(created_with_missing_fields_count, len(created)) - non_shipping_orders = list(previous_result.get('non_shipping_orders') or []) - refreshed = { - 'status': 'ok', - 'request_id': str(run.run_no), - 'batch_no': ( - create_result.get('batch_no') - if isinstance(create_result, dict) and create_result.get('batch_no') - else previous_result.get('batch_no') - ), - 'created': created, - 'opened_existing': opened_existing, - 'pending_orders': pending_orders, - 'non_shipping_orders': non_shipping_orders, - 'created_count': len(created), - 'opened_existing_count': len(opened_existing), - 'pending_count': len(pending_orders), - 'non_shipping_count': len(non_shipping_orders), - 'created_with_missing_fields_count': created_with_missing_fields_count, - } - refreshed['message'] = _build_submission_message( - created_count=refreshed['created_count'], - opened_existing_count=refreshed['opened_existing_count'], - pending_count=refreshed['pending_count'], - non_shipping_count=refreshed['non_shipping_count'], - created_with_missing_fields_count=created_with_missing_fields_count, - ) - return refreshed - - -def _build_submission_message( - *, - created_count: int, - opened_existing_count: int, - pending_count: int, - non_shipping_count: int, - created_with_missing_fields_count: int, -) -> str: - """生成自动冻结执行后的统一结果摘要,保持与订单抽取主链路文案一致。""" - if not created_count and not opened_existing_count and not pending_count: - if non_shipping_count: - return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。' - return '未识别到发货订单,本次未创建任务。' - - parts: list[str] = [] - if created_count: - parts.append(f'已创建 {created_count} 个发货任务') - if opened_existing_count: - parts.append(f'已打开 {opened_existing_count} 个已有任务') - if pending_count: - prefix = '另有' if parts else '有' - parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突') - if non_shipping_count: - parts.append(f'已忽略 {non_shipping_count} 项非发货内容') - message = ';'.join(parts) + '。' - if created_with_missing_fields_count: - message += ( - f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,' - '可通过自然对话补充。' - ) - return message diff --git a/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py b/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py index 17f15d17..5ccec735 100644 --- a/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_pdf_automark_service.py @@ -941,24 +941,15 @@ def enqueue_pdf_automark( ).order_by(ShippingOrderDocumentProfileSample.id.asc()).first() if annotation is None or annotation.table_id != resolved_table_id: raise ValidationError('Automark requires the frozen annotation sample table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') - if not annotation.layout_version_id or not annotation.layout_payload_checksum: - raise ValidationError('Annotation sample layout evidence is not frozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') + from app.services.shipping_notice.order_document_profile_service import require_profile_sample_automark_ready + readiness = require_profile_sample_automark_ready(profile=profile, sample=annotation, actor_id=actor_id) document = db.session.get(ShippingOrderDocument, int(document_id)) - current_checksum = str( - getattr(getattr(document, 'current_layout_version', None), 'payload_checksum', '') or '', - ) - if ( - document is None - or int(document.current_layout_version_id or 0) != int(annotation.layout_version_id) - or current_checksum != str(annotation.layout_payload_checksum) - ): - raise ValidationError('Annotation sample layout is stale and must be refrozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') payload = { 'profile_id': int(profile_id), 'document_id': int(document_id), 'table_id': resolved_table_id, 'schema_version_id': int(schema_version_id) if schema_version_id else None, 'page_no': int(page_no) if page_no else 1, 'actor_id': int(actor_id), - 'layout_version_id': int(annotation.layout_version_id), - 'layout_payload_checksum': str(annotation.layout_payload_checksum), + 'layout_version_id': int(readiness['layout_version_id']), + 'layout_payload_checksum': str(readiness['layout_payload_checksum']), } ref = f'pdf-automark:{int(profile_id)}:{int(document_id)}:{payload["table_id"] or "page"}:{payload["page_no"]}' job_id = enqueue( diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py index 6b8fdbbc..13db780c 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -39,6 +39,7 @@ from app.models import ( ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + derive_incomplete_table_bbox, reconstruct_coordinate_profile_rows, suggest_header_layouts, suggest_header_regions, @@ -1406,6 +1407,166 @@ def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDo return version +def refresh_profile_sample_readiness( + *, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample, + actor_id: int | None = None, commit: bool = False, +) -> dict[str, Any]: + """刷新模板样本的 Layout/主表/证据状态,并在条件满足时幂等冻结现有证据字段。 + + [STEP 1] 上传物化、Layout ready、主表绑定和证据冻结是四个独立状态; + 本函数只在 ready Layout 且内容身份一致时写回既有样本字段,绝不创建新实体, + 也不会在 Layout 尚未完成时把样本伪装成可自动标注。 + + Args: + profile: 必须是当前模板 Profile。 + sample: Profile 的 annotation/training 样本绑定。 + actor_id: 产生冻结审计时的管理员身份,可为空(后台布局收口)。 + commit: 是否提交当前事务;保存草稿时由外层事务统一提交。 + + Returns: + 包含 layout_status、main_table_status、evidence_status 和 automark_ready 的安全状态。 + """ + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is None: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(sample.document_id), 'layout_status': 'missing', + 'main_table_status': 'missing', 'evidence_status': 'unavailable', + 'automark_ready': False, 'reason_code': 'document_missing', + } + from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + + layout = current_layout_snapshot(document) or {} + version = ( + db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id)) + if document.current_layout_version_id else None + ) + if ( + version is None or str(version.status or '') != 'ready' + or not isinstance(version.payload_json, dict) + ): + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': str(getattr(version, 'status', None) or 'pending'), + 'main_table_status': 'pending', 'evidence_status': 'pending', + 'automark_ready': False, 'reason_code': 'layout_not_ready', + } + tables = [ + item for item in (layout.get('tables') or []) + if isinstance(item, dict) and str(item.get('table_id') or '').strip() + ] + table_id = str(sample.table_id or '').strip() + if not table_id: + definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + configured = str(definition.get('main_table_id') or '').strip() + if configured: + table_id = configured + elif len(tables) == 1: + table_id = str(tables[0]['table_id']).strip() + else: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'ambiguous' if tables else 'missing', + 'evidence_status': 'pending', 'automark_ready': False, + 'reason_code': 'main_table_ambiguous' if tables else 'main_table_missing', + } + if not any(str(item.get('table_id') or '') == table_id for item in tables): + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'missing', 'evidence_status': 'stale', + 'automark_ready': False, 'reason_code': 'main_table_missing', + } + content_hash = str(document.content_hash or '').strip().lower() + source_hash = str(version.source_content_hash or '').strip().lower() + if len(content_hash) != 64 or len(source_hash) != 64 or content_hash != source_hash: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'bound', 'evidence_status': 'stale', + 'automark_ready': False, 'reason_code': 'layout_content_hash_mismatch', + } + from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload + payload_checksum, _ = canonical_layout_payload(version.payload_json or {}) + stored_checksum = str(version.payload_checksum or '').strip().lower() + if len(stored_checksum) != 64 or payload_checksum != stored_checksum: + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'layout_status': 'ready', + 'main_table_status': 'bound', 'evidence_status': 'stale', + 'automark_ready': False, 'reason_code': 'layout_checksum_mismatch', + } + changed = ( + sample.table_id != table_id + or sample.layout_version_id != int(version.id) + or str(sample.layout_payload_checksum or '').lower() != stored_checksum + or str(sample.source_content_hash or '').lower() != content_hash + or str(sample.layout_contract_version or '') != str(version.contract_version or '').strip() + or str(sample.parser_key or '') != str(version.parser_key or '').strip() + or str(sample.parser_name or '') != str(version.parser_name or '').strip() + or str(sample.parser_version or '') != str(version.parser_version or '').strip() + ) + sample.table_id = table_id + sample.layout_version_id = int(version.id) + sample.layout_payload_checksum = stored_checksum + sample.source_content_hash = content_hash + sample.layout_contract_version = str(version.contract_version or '').strip() or None + sample.parser_key = str(version.parser_key or '').strip() or None + sample.parser_name = str(version.parser_name or '').strip() or None + sample.parser_version = str(version.parser_version or '').strip() or None + # Layout identity or parser provenance changed means this is a new evidence freeze, + # not merely a repeated read of the same frozen sample. + sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at + sample.source_filename_snapshot = str(document.filename or '').strip() or None + sample.page_count_snapshot = _layout_page_count(version.payload_json or {}) + sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id) + if changed: + _audit( + profile_id=profile.id, document_id=document.id, + event_type='profile_sample_evidence_frozen', actor_id=actor_id, + detail={ + 'sample_id': int(sample.id), 'sample_role': sample.sample_role, + 'layout_version_id': int(version.id), 'table_id': table_id, + 'layout_payload_checksum': stored_checksum, + }, + ) + if commit: + db.session.commit() + return { + 'profile_id': int(profile.id), 'sample_id': int(sample.id), + 'document_id': int(document.id), 'table_id': table_id, + 'layout_status': 'ready', 'main_table_status': 'bound', + 'evidence_status': 'frozen', 'automark_ready': True, + 'layout_version_id': int(version.id), 'layout_payload_checksum': stored_checksum, + 'reason_code': None, + } + + +def require_profile_sample_automark_ready( + *, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample, + actor_id: int | None = None, +) -> dict[str, Any]: + """自动标注入队前唯一强门禁;未满足证据条件时返回稳定、可操作的错误码。""" + state = refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False) + if state.get('automark_ready'): + return state + reason = str(state.get('reason_code') or 'profile_sample_not_ready') + code_by_reason = { + 'layout_not_ready': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY', + 'main_table_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED', + 'main_table_ambiguous': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS', + 'layout_content_hash_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE', + 'layout_checksum_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE', + 'document_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + } + raise ValidationError( + 'Profile sample is not ready for PDF automark', + code=code_by_reason.get(reason, 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'), + details=state, + ) + + def _layout_page_count(payload: dict[str, Any]) -> int | None: """????????????? payload ?? pages?????????????""" pages = payload.get('pages') @@ -2510,6 +2671,36 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st if intake is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') documents = ShippingOrderDocument.query.filter_by(intake_id=intake.id).all() + readiness: list[dict[str, Any]] = [] + document_layout_states: list[str] = [] + for document in documents: + # 测试/后台轮询都可能只载入 current_layout_version_id;显式按 ID 读取, + # 不能因 ORM relationship 尚未加载把实际 failed/ready 误报为 pending。 + version = ( + db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id)) + if document.current_layout_version_id else None + ) + if version is None: + # failed Layout 不会成为 current_layout_version;上传状态仍须如实展示最近一次 + # 解析结论,不能因为没有 current 指针把失败伪装成仍在等待。 + version = ( + ShippingDocumentLayoutVersion.query + .filter_by(document_id=document.id) + .order_by(ShippingDocumentLayoutVersion.version.desc()) + .first() + ) + document_layout_states.append(str(getattr(version, 'status', None) or 'pending')) + bindings = ShippingOrderDocumentProfileSample.query.filter_by(document_id=document.id).all() + for sample in bindings: + profile = db.session.get(ShippingOrderDocumentProfile, int(sample.profile_id)) + if profile is None or profile.status != 'draft': + continue + state = refresh_profile_sample_readiness( + profile=profile, sample=sample, actor_id=actor_id, commit=False, + ) + readiness.append(state) + if readiness: + db.session.commit() if intake.parse_status in {'parse_failed', 'failed', 'error'}: status = 'failed' error_code = intake.error_code @@ -2520,12 +2711,29 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st # ???? PDF Document??????? EML / Layout? status = 'parsing' error_code = None + ready_values = [bool(item.get('automark_ready')) for item in readiness] return { 'intake_no': intake.intake_no, 'parse_status': status, 'document_count': len(documents), 'document_ids': [int(document.id) for document in documents], 'error_code': error_code, + 'layout_status': ( + 'ready' if readiness and all(item.get('layout_status') == 'ready' for item in readiness) + else ( + readiness[0].get('layout_status') + if readiness + else ('ready' if document_layout_states and all(item == 'ready' for item in document_layout_states) + else (document_layout_states[0] if document_layout_states else 'pending')) + ) + ), + 'evidence_status': ( + 'frozen' if readiness and all(item.get('evidence_status') == 'frozen' for item in readiness) + else (readiness[0].get('evidence_status') if readiness else 'pending') + ), + 'automark_ready': bool(readiness) and all(ready_values), + 'automark_reason_code': next((item.get('reason_code') for item in readiness if item.get('reason_code')), None), + 'sample_readiness': readiness, } @@ -2683,11 +2891,33 @@ def suggest_coordinate_reconstruction( if field.get('auto_annotation_enabled', True) and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'} ] + effective_characters = characters + effective_table_bbox = dict(raw_table['bbox']) + table_bbox_source = 'layout_table' suggestions = suggest_multi_subrow_layouts( - characters=characters, table_bbox=raw_table['bbox'], + characters=effective_characters, table_bbox=effective_table_bbox, ) if not suggestions: - raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') + # MinerU can return a header-only table bbox. Use complete page evidence + # to derive a candidate boundary, while retaining the original fact. + page_characters, page_source = _page_coordinate_characters( + layout, page_no=int(raw_table.get('page_no') or 1), + ) + if page_characters and page_source in {'pdf_coordinate', 'ocr_coordinate'}: + derived_bbox = derive_incomplete_table_bbox( + characters=page_characters, table_bbox=effective_table_bbox, + ) + if derived_bbox is not None: + derived_suggestions = suggest_multi_subrow_layouts( + characters=page_characters, table_bbox=derived_bbox, + ) + if derived_suggestions: + effective_characters = page_characters + effective_table_bbox = derived_bbox + suggestions = derived_suggestions + table_bbox_source = 'page_coordinate_derived' + if not suggestions: + raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID') raw_row_offset = data.get('row_offset') if raw_row_offset is not None: try: @@ -2709,14 +2939,16 @@ def suggest_coordinate_reconstruction( page = (layout.get('coordinate_evidence') or {}).get('pages', {}).get(str(raw_table.get('page_no') or 1), {}) try: page_width, page_height = float(page['width']), float(page['height']) - table_bbox = raw_table['bbox'] + table_bbox = effective_table_bbox table_region = { 'x0': float(table_bbox['x0']) / page_width, 'y0': float(table_bbox['y0']) / page_height, 'x1': float(table_bbox['x1']) / page_width, 'y1': float(table_bbox['y1']) / page_height, } except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc: raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc - header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox']) + header_suggestions = suggest_header_regions( + characters=effective_characters, table_bbox=effective_table_bbox, + ) # Only exact, unique aliases can bind a column. Position is considered only after # the label itself is proven, preventing shifted documents from remapping fields. aliases: dict[str, str | None] = {} @@ -2791,6 +3023,8 @@ def suggest_coordinate_reconstruction( 'table_region': table_region, 'header_regions': serialized_headers, 'subrow_layouts': serialized, + 'table_bbox_source': table_bbox_source, + 'original_table_bbox': dict(raw_table['bbox']), 'status': 'needs_review', } @@ -3114,6 +3348,9 @@ def save_draft( created_by_id=actor_id, ) db.session.add(sample) + # readiness audit records sample_id; assign it within this outer save transaction + # before the shared evidence-freeze service is invoked. + db.session.flush() layout = _document_layout(annotation_document) if not any( isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id @@ -3124,6 +3361,8 @@ def save_draft( code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', ) sample.table_id = visual_main_table_id + # Layout ready 后立即尝试冻结样本证据;尚未 ready 时保留草稿并由状态接口/自动标注入口继续门禁。 + refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False) _refresh_training_sample_count(profile) audit_summary = _definition_audit_summary(definition) if previous_definition is None: diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 45fc5d8a..b64338ad 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -52,7 +52,6 @@ from app.models import ( ShippingNotice, ShippingOrderExtraction, ) -from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates from app.services.shipping_notice.business_fingerprint import ( build_business_fingerprint, build_content_fingerprint, @@ -71,6 +70,47 @@ from app.services.shipping_notice.context_fields.runtime import canonical_mail_c from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_parser +def _discard_resolved_worker_field_conflicts( + conflicts: list[dict[str, Any]], + *, + decisions: list[dict[str, Any]], + blocked_fields: list[str], +) -> list[dict[str, Any]]: + """移除已由最终动态裁决解决的 Worker 早期字段证据缺失阻断。 + + Worker 可能在派生前先报告 ``evidence_missing``;Candidate 必须以 + persist_dynamic_order 的最终 Decision/blocked_fields 为准。仅移除字段级、 + 字段完整性归属的早期缺证冲突:真实跨来源冲突、非字段完整性冲突,以及最终 + 仍处于 blocked_fields 的必填或建单关键字段,一律保留。 + + Args: + conflicts: Worker 原始阻断冲突。 + decisions: 动态 Schema 最终字段裁决。 + blocked_fields: 派生后最终仍阻断流程的字段编码。 + + Returns: + 仍应投影到 Candidate 的阻断冲突。 + """ + unresolved = {str(code).strip() for code in blocked_fields if str(code or '').strip()} + resolved_fields = { + str(item.get('field_code') or '').strip() + for item in decisions + if isinstance(item, dict) + and item.get('status') in {'accepted', 'corroborated', 'derived'} + and str(item.get('field_code') or '').strip() not in unresolved + } + return [ + item for item in conflicts + if not ( + str(item.get('field') or '').strip() in resolved_fields + and str(item.get('reason') or '') == 'evidence_missing' + and str(item.get('owning_gate_code') or '') in { + 'field_completeness', 'order_field_extraction', + } + ) + ] + + def _runtime_session_for_run(run: Any) -> ChatSession | SimpleNamespace: """读取 Run 的 UI 会话;历史会话已清理时使用冻结身份继续持久化业务结果。 @@ -437,6 +477,11 @@ def persist_order_extraction_result( }, frozen_evidence_text_by_document=frozen_evidence_text_by_document, ) + blocking_conflicts = _discard_resolved_worker_field_conflicts( + blocking_conflicts, + decisions=list(dynamic.get('decisions') or []), + blocked_fields=list(dynamic.get('blocked_fields') or []), + ) if run_id is not None: dynamic['extraction'].run_id = int(run_id) layout_evidence_issues = [ @@ -874,67 +919,103 @@ def persist_order_extraction_result( ), ) - auto_candidate_nos = [row.candidate_no for row in auto_candidates] - create_result: dict[str, Any] | None = None - if auto_candidate_nos: - idem = f"extract:{current_snapshot[:48]}" - create_result = create_shipping_batch_from_candidates( - user_id=int(session.user_id), - conversation_id=session.session_id, - intake_nos=intake_nos, - candidate_nos=auto_candidate_nos, - create_idempotency_key=idem, - ) - # 建批事务已在启动编排器前绑定 Task 与已接受 Extraction;此处只完成本轮提交收口。 - db.session.commit() - else: - # [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。 - if not pending: - now = datetime.utcnow() - for intake in intakes: - intake.parse_status = 'consumed' - intake.consumed_at = now - intake.order_extraction_status = 'completed' - intake.updated_at = now - db.session.commit() - - create_data = (create_result or {}).get('data') - create_data = create_data if isinstance(create_data, dict) else {} - created = list(create_data.get('tasks') or []) - opened_existing = list( - (create_result or {}).get('opened_existing') - or create_data.get('opened_existing') - or [] - ) - for item in (create_result or {}).get('reconciliation_pending') or []: - if not isinstance(item, dict): + # [STEP 4] open_existing 是既有任务的安全跳转/字段对账,不是新建单路径。 + # 它必须在此单独收口,禁止借已删除批次编排器实现,也不得触发新单或自动推进。 + opened_existing: list[dict[str, Any]] = [] + for candidate in auto_candidates: + if ( + candidate.duplicate_resolution != 'open_existing' + or candidate.consumed_task_id is not None + or candidate.validation_status != 'ready' + ): continue - reconciliation = ( - item.get('reconciliation') - if isinstance(item.get('reconciliation'), dict) - else {} + target_no = str(candidate.duplicate_target_task_no or '').strip().upper() + if not target_no: + continue + target = ( + db.session.query(ShippingNotice) + .filter_by(task_no=target_no, user_id=int(session.user_id)) + .with_for_update() + .first() ) - pending.append({ - 'candidate_no': item.get('candidate_no'), - 'task_no': item.get('task_no'), - 'reasons': [ - str(reconciliation.get('reason') or 'open_existing_reconciliation_required') - ], - 'reconciliation': reconciliation, + if target is None: + continue + reconciliation: dict[str, Any] | None = None + duplicate_status = str(candidate.duplicate_status or '').strip() + if duplicate_status == 'exact_file': + from app.services.shipping_notice.open_existing_reservation_backfill import ( + backfill_exact_file_open_existing_reservations, + ) + + structured = ( + candidate.structured_result_json + if isinstance(candidate.structured_result_json, dict) + else {} + ) + extraction = ( + structured.get('extraction') + if isinstance(structured.get('extraction'), dict) + else {} + ) + reconciliation = backfill_exact_file_open_existing_reservations( + task=target, + candidate=candidate, + candidate_summary=( + structured.get('business_summary') + if isinstance(structured.get('business_summary'), dict) + else {} + ), + duplicate_status=duplicate_status, + duplicate_matches=[{'task_no': target.task_no}], + verified_reservation_evidence=list( + extraction.get('verified_reservation_evidence') or [] + ), + ) + # 对账服务仍以既有任务的动态字段及旧安全态为唯一依据;其内会在字段 + # 已安全补齐后推进到 parse_review,不能在这里二次推导或覆盖阶段。 + if ( + reconciliation.get('status') != 'applied' + and reconciliation.get('reason') not in { + 'duplicate_status_not_exact_file', + 'target_already_complete', + 'target_task_not_safe', + } + ): + candidate.selected = False + pending_item = { + 'candidate_no': candidate.candidate_no, + 'task_no': target.task_no, + 'reasons': [str(reconciliation.get('reason') or 'open_existing_reconciliation_required')], + 'reconciliation': reconciliation, + } + pending.append(pending_item) + pending_by_intake[int(candidate.intake_id)].append(pending_item) + continue + candidate.consumed_task_id = int(target.id) + candidate.updated_at = datetime.utcnow() + opened_existing.append({ + 'candidate_no': candidate.candidate_no, + 'task_no': target.task_no, + **({'reconciliation': reconciliation} if reconciliation is not None else {}), }) - created_count = len(created) + + # Candidate 只进入 Review Case/STP;禁止旧抽取链绕过确认直接创建批次或 Task。 + if not pending: + now = datetime.utcnow() + for intake in intakes: + intake.parse_status = 'consumed' + intake.consumed_at = now + intake.order_extraction_status = 'completed' + intake.updated_at = now + db.session.commit() + + created: list[dict[str, Any]] = [] + created_count = 0 opened_existing_count = len(opened_existing) - created_with_missing_fields_count = sum( - 1 - for candidate in auto_candidates - if candidate.duplicate_resolution != 'open_existing' and candidate.missing_fields_json - ) - # 下层响应缺失任务明细属于契约异常;摘要只能陈述已持久化并返回的 Task,不能回退到 Candidate 数。 - created_with_missing_fields_count = min(created_with_missing_fields_count, created_count) + created_with_missing_fields_count = 0 result = { 'status': 'ok', 'request_id': request_id, - 'batch_no': create_result.get('batch_no') if create_result else None, 'created': created, 'opened_existing': opened_existing, 'pending_orders': pending, @@ -1032,7 +1113,6 @@ def submit_order_extraction_run_result( result = { 'status': 'ok', 'request_id': str(run.run_no), - 'batch_no': None, 'created': [{'task_no': task_no} for task_no in task_nos], 'opened_existing': [], 'pending_orders': [{'candidate_no': item.candidate_no} for item in pending], @@ -1078,7 +1158,6 @@ def submit_order_extraction_run_result( result = { 'status': 'ok', 'request_id': str(run.run_no), - 'batch_no': None, 'created': [], 'opened_existing': [], 'pending_orders': [], @@ -1276,7 +1355,6 @@ def submit_order_extraction_unit_result( result = { 'status': 'ok', 'request_id': str(run.run_no), - 'batch_no': None, 'created': [{'task_no': task_no} for task_no in task_nos], 'opened_existing': [], 'pending_orders': [], 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 a0ff4891..83421f27 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/order_extraction_run_service.py 用途:创建、查询和序列化建单前订单抽取领域 Run;Unit 完成后独立触发 Candidate/STP 下游。 依赖:Agent/ChatSession、ShippingOrderIntake/Document、已发布订单 Schema、SQLAlchemy 事务、 - order_extraction.submit_order_extraction_unit_result、progress_workflow.auto_progress、 + order_extraction.submit_order_extraction_unit_result、 workflow_ledger_service(物化后幂等建 WorkflowItem)、process_gate_bridge(Execution 创建)、 error_explainability_contract(Run 失败可解释性投影)、 conversation_processing_projection(会话多任务投影)、audit_service。 @@ -34,7 +34,7 @@ from typing import Any from flask import current_app from sqlalchemy.exc import IntegrityError -from sqlalchemy import and_, or_ +from sqlalchemy import and_, func, or_, select from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError @@ -852,6 +852,7 @@ def _build_snapshot( parse_email_allocation_text, ) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan table_contract = compile_table_header_contract(dict(schema_version.definition_json or {})) generic_config = ( @@ -918,7 +919,7 @@ def _build_snapshot( ) if isinstance(email_supplement, dict): email_supplement['document_id'] = int(document.id) - documents_by_intake[document.intake_id].append({ + document_snapshot = { 'document_id': document.id, 'document_type': document.document_type, 'attachment_key': document.attachment_key, @@ -933,7 +934,15 @@ def _build_snapshot( 'layout_snapshot': layout_snapshot, 'layout_schema_candidates': layout_schema_candidates, 'email_supplement': email_supplement, - }) + } + # 自动标注候选只在冻结 Schema/Layout 身份下编译为 Parse Plan;Worker 不得 + # 直接消费 layout_schema_candidates。 + document_snapshot['generic_parse_plan'] = compile_generic_parse_plan( + candidates=layout_schema_candidates, + schema_checksum=str(schema_version.checksum or ''), + layout_snapshot=layout_snapshot if isinstance(layout_snapshot, dict) else {}, + ) + documents_by_intake[document.intake_id].append(document_snapshot) incomplete = [ intake.intake_no for intake in intakes @@ -1366,6 +1375,7 @@ def materialize_order_extraction_run_inputs( from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan table_contract = compile_table_header_contract(dict(contract)) document_ids = _run_snapshot_document_ids(run) if document_ids: @@ -1411,6 +1421,11 @@ def materialize_order_extraction_run_inputs( candidates = [{'mapping_status': 'failed', 'issues': ['layout_schema_mapping_invalid']}] item['layout_snapshot'] = layout_snapshot item['layout_schema_candidates'] = candidates + item['generic_parse_plan'] = compile_generic_parse_plan( + candidates=candidates, + schema_checksum=str(schema.get('checksum') or ''), + layout_snapshot=layout_snapshot if isinstance(layout_snapshot, dict) else {}, + ) changed = True if changed: from sqlalchemy.orm.attributes import flag_modified @@ -2442,7 +2457,7 @@ def submit_order_extraction( """ from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) normalized_submission = str(submission_id or '').strip() @@ -2466,17 +2481,11 @@ def submit_order_extraction( ) can_append, block_reason = evaluate_can_append(existing) existing_task_no = str(getattr(existing, 'user_task_no', None) or '').strip() or None - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user.id, conversation_id=existing.conversation_id, focused_task_no=existing_task_no, recent_task_no=existing_task_no, - recent_decision=decision, - recent_append_count=( - int(existing_row.appended_intake_count) - if existing_row is not None and decision == 'appended' - else None - ), ) return { 'decision': decision, @@ -2497,7 +2506,6 @@ def submit_order_extraction( existing.input_frozen_at.isoformat() + 'Z' if existing.input_frozen_at else None ), 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } # [STEP 2] 解析可追加目标。 @@ -2776,16 +2784,14 @@ def submit_order_extraction( persisted_task_no = str(getattr(run, 'user_task_no', None) or '').strip() or None from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user.id, conversation_id=run.conversation_id, focused_task_no=persisted_task_no, recent_task_no=persisted_task_no, - recent_decision=decision, - recent_append_count=appended_count if decision == 'appended' else None, ) return { 'decision': decision, @@ -2803,7 +2809,6 @@ def submit_order_extraction( run.input_frozen_at.isoformat() + 'Z' if run.input_frozen_at else None ), 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } @@ -2826,7 +2831,7 @@ def focus_conversation_task( _latest_focused_task_no, ) from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) normalized_task = str(task_no or '').strip() @@ -2863,7 +2868,7 @@ def focus_conversation_task( after={'focused_task_no': normalized_task, 'run_no': run.run_no}, metadata={'user_task_no': normalized_task}, ) - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user_id, conversation_id=run.conversation_id, focused_task_no=normalized_task, @@ -2871,7 +2876,6 @@ def focus_conversation_task( return { 'focused_task_no': normalized_task, 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } @@ -2891,7 +2895,7 @@ def mark_conversation_task_viewed( """ from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.shipping_processing_projection import ( - project_conversation_processing_items, + project_conversation_processing_summary, ) normalized_task = str(task_no or '').strip() @@ -2927,7 +2931,7 @@ def mark_conversation_task_viewed( after={'seen_at': run.seen_at.isoformat() + 'Z', 'user_task_no': normalized_task}, metadata={'user_task_no': normalized_task}, ) - unified = project_conversation_processing_items( + unified = project_conversation_processing_summary( user_id=user_id, conversation_id=run.conversation_id, focused_task_no=normalized_task, @@ -2935,7 +2939,6 @@ def mark_conversation_task_viewed( return { 'user_task_no': normalized_task, 'processing': unified.get('conversation_processing'), - 'work_items': unified.get('work_items') or [], } @@ -3289,6 +3292,75 @@ def list_order_extraction_runs( } +def list_order_extraction_run_summaries( + *, + user_id: int, + conversation_id: str | None = None, + limit: int = 50, + status: str | None = None, + page: int | None = None, + page_size: int | None = None, +) -> list[dict[str, Any]] | dict[str, Any]: + """ + 为会话恢复和任务中心读取固定成本 Run 摘要,禁止加载冻结输入快照。 + + 核心逻辑:列表端只需定位最新 Run 与展示摘要,故用标量列投影直接绕过 ORM 实体; + `input_snapshot_json` / `request_snapshot_json` 只能由单 Run 详情路径按需读取。 + + Args: + user_id: 当前用户主键。 + conversation_id: 可选会话过滤。 + limit: 非分页模式的条数上限。 + status: 可选业务状态过滤。 + page: 可选分页页码。 + page_size: 可选分页大小。 + + Returns: + 非分页:摘要字典列表;分页:{items, total, page, page_size}。 + """ + normalized_status = str(status or '').strip() or None + if normalized_status and normalized_status not in { + 'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled', + }: + raise ValidationError('status is invalid') + + filters = [ShippingOrderProcessingRun.user_id == user_id] + if conversation_id: + filters.append(ShippingOrderProcessingRun.conversation_id == conversation_id) + if normalized_status: + filters.append(ShippingOrderProcessingRun.status == normalized_status) + columns = ( + ShippingOrderProcessingRun.run_no, + ShippingOrderProcessingRun.user_task_no, + ShippingOrderProcessingRun.owner_agent_id, + ShippingOrderProcessingRun.conversation_id, + ShippingOrderProcessingRun.status, + ShippingOrderProcessingRun.phase, + ShippingOrderProcessingRun.progress_summary_json, + ShippingOrderProcessingRun.progress_version, + ShippingOrderProcessingRun.last_activity_at, + ShippingOrderProcessingRun.created_at, + ShippingOrderProcessingRun.updated_at, + ) + statement = select(*columns).where(*filters).order_by(ShippingOrderProcessingRun.created_at.desc()) + if page is None and page_size is None: + return list(db.session.execute( + statement.limit(min(max(int(limit or 50), 1), 100)), + ).mappings()) + safe_page = max(1, int(page or 1)) + safe_page_size = min(100, max(1, int(page_size or 20))) + total = db.session.scalar(select(func.count()).select_from(ShippingOrderProcessingRun).where(*filters)) or 0 + rows = list(db.session.execute( + statement.offset((safe_page - 1) * safe_page_size).limit(safe_page_size), + ).mappings()) + return { + 'items': rows, + 'total': int(total), + 'page': safe_page, + 'page_size': safe_page_size, + } + + def _reparse_difference_summary(run: ShippingOrderProcessingRun) -> dict[str, Any] | None: """返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。""" source = run.reparse_source @@ -3561,6 +3633,35 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str, } +def serialize_order_extraction_run_list_item(run: Any) -> dict[str, Any]: + """序列化标量 Run 列表行;不得访问 ORM 冻结快照或工作台投影。""" + row = run if hasattr(run, 'get') else run._mapping + progress_summary = row.get('progress_summary_json') if isinstance(row.get('progress_summary_json'), dict) else {} + return { + 'run_no': row['run_no'], + 'user_task_no': row['user_task_no'], + 'agent_id': row['owner_agent_id'], + 'conversation_id': row['conversation_id'], + 'status': str(row['status'] or 'queued'), + 'phase': str(row['phase'] or row['status'] or 'queued'), + 'summary': { + 'total_documents': int(progress_summary.get('total_documents') or 0), + 'pending_documents': int(progress_summary.get('pending_documents') or 0), + 'processing_documents': int(progress_summary.get('processing_documents') or 0), + 'completed_documents': int(progress_summary.get('completed_documents') or 0), + 'review_required_documents': int(progress_summary.get('review_required_documents') or 0), + 'failed_documents': int(progress_summary.get('failed_documents') or 0), + 'cancelled_documents': int(progress_summary.get('cancelled_documents') or 0), + 'candidate_count': int(progress_summary.get('candidate_count') or 0), + 'opened_existing_documents': int(progress_summary.get('opened_existing_documents') or 0), + }, + 'progress_version': int(row['progress_version'] or 0), + 'last_activity_at': row['last_activity_at'].isoformat() + 'Z' if row['last_activity_at'] else None, + 'created_at': row['created_at'].isoformat() + 'Z' if row['created_at'] else None, + 'updated_at': row['updated_at'].isoformat() + 'Z' if row['updated_at'] else None, + } + + def serialize_order_extraction_message_state(run: ShippingOrderProcessingRun) -> dict[str, Any]: """把服务端 Run 事实投影为聊天状态卡;历史恢复和实时持久化必须共用同一映射。""" from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state @@ -4359,10 +4460,11 @@ def progress_ready_extraction_unit( orders: list[dict[str, Any]], ) -> dict[str, Any]: """ - 单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 STP 触发下游 auto_progress。 + 单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 Review Case/STP 正式链触发下游。 - 核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit;建批路径由编排器 - 调用 progress_workflow.auto_progress;若仅打开既有任务则不重复推进。 + 核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit。自动建单与自动推进 + 由 submit 内的 Review Case/STP 正式链异步协调,禁止此处再以已删除的 batch_no 或 + 结果数组推断并直接调用旧 auto_progress,避免重复推进。 Args: run: 所属抽取 Run。 @@ -4376,21 +4478,6 @@ def progress_ready_extraction_unit( mark_order_extraction_persistence_started(run) result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders) - # 建批编排器会异步调用同一 auto_progress;此处仅为无编排器的已创建任务兜底同步推进。 - created = list(result.get('created') or []) - if created and not result.get('batch_no') and not result.get('idempotent_replay'): - from app.services.shipping_notice.progress_workflow import auto_progress - for item in created: - task_no = str(item.get('task_no') or '').strip() - if not task_no: - continue - try: - auto_progress({'task_id': task_no, 'source': 'system'}) - except Exception: - current_app.logger.exception( - 'STP auto_progress failed after unit persist run=%s unit=%s task=%s', - run.run_no, getattr(unit, 'id', None), task_no, - ) return result diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index fec158b1..a0caa566 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -26,6 +26,9 @@ from app.services.shipping_notice.document_layout.html_table import parse_html_g from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows +from app.services.shipping_notice.document_layout.coordinate_transform import ( + apply_coordinate_transform_to_region, +) from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.document_layout.order_profile_matcher import ( ProfileMatchResult, @@ -479,29 +482,8 @@ def _selected_coordinate_transform( def _translate_coordinate_region( region: dict[str, float], *, coordinate_transform: dict[str, Any] | None, ) -> dict[str, float] | None: - """在裁剪页级 glyph 前使用 matcher 已确认的受限平移;非法声明 fail-closed。""" - if coordinate_transform is None: - return region - if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied': - return None - try: - translate_x, translate_y = ( - float(coordinate_transform['translate_x']), - float(coordinate_transform['translate_y']), - ) - translated = { - 'x0': float(region['x0']) + translate_x, - 'y0': float(region['y0']) + translate_y, - 'x1': float(region['x1']) + translate_x, - 'y1': float(region['y1']) + translate_y, - } - except (KeyError, TypeError, ValueError): - return None - if not all(value == value and abs(value) != float('inf') for value in translated.values()): - return None - if not (0 <= translated['x0'] < translated['x1'] <= 1 and 0 <= translated['y0'] < translated['y1'] <= 1): - return None - return translated + """在裁剪页级 glyph 前应用 matcher 已确认的统一坐标变换,非法声明 fail-closed。""" + return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform) def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: @@ -1466,8 +1448,12 @@ def _extract_generic_evidence_result( from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate candidates = document.get('layout_schema_candidates') if isinstance(document.get('layout_schema_candidates'), list) else [] + parse_plan = document.get('generic_parse_plan') if isinstance(document.get('generic_parse_plan'), dict) else None gate = evaluate_generic_extraction_gate( candidates=candidates, + parse_plan=parse_plan, + layout_snapshot=document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}, + require_parse_plan=True, definition=definition, schema=schema, intake=intake, @@ -1557,6 +1543,14 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult if adapter_result.attach_formal_evidence: order['_hxops_formal_evidence'] = (adapter_result.evidence or {}).get('formal_evidence_summary') order['_hxops_value_source_identity'] = (adapter_result.evidence or {}).get('value_source_identity') + _normalize_profile_order_observations( + orders, + default_value_source=adapter_name, + coordinate_transform=_selected_coordinate_transform( + profile_match=match, + raw_profile=selected_profile, + ) if adapter_name == 'coordinate_ocr' and isinstance(selected_profile, dict) else None, + ) decision['parsed_table_count'] = 1 decision['route_type'] = 'profile_deterministic' if decision.get('fallback_reason_codes'): @@ -1823,6 +1817,67 @@ def _build_approved_profile_order( return orders[0] if orders and len(orders) == 1 else None +def _normalize_profile_order_observations( + orders: list[dict[str, Any]], + *, + default_value_source: str, + coordinate_transform: dict[str, Any] | None, +) -> None: + """将 Profile adapter 的字段产物统一为可追溯 Observation 合同。 + + 坐标模板、XFA datasets 的内部字段形态不同,但进入 Candidate Gate 前必须具有相同 + 的来源、证据引用和几何变换声明。这里不补造缺失的坐标或值;仅为已有字段级 + layout/datasets evidence 投影稳定顶层引用,缺证据仍由后续资格门禁拦截。 + """ + source_aliases = { + 'pdf_coordinate': 'native_pdf', + 'native_glyph': 'native_pdf', + 'ocr_coordinate': 'ocr', + 'ocr_glyph': 'ocr', + 'acroform_widget': 'acroform_widget', + 'xfa_dataset': 'xfa_dataset', + 'coordinate_ocr': 'native_pdf', + } + default_source = source_aliases.get(default_value_source, default_value_source or 'unknown') + transform_ref: dict[str, Any] | None = None + if default_source in {'native_pdf', 'ocr', 'acroform_widget'}: + transform_ref = ( + {'kind': 'legacy_absolute'} + if coordinate_transform is None + else { + 'kind': 'coordinate_transform', + 'status': coordinate_transform.get('status'), + 'matrix': list(coordinate_transform.get('matrix') or []), + 'anchor_count': coordinate_transform.get('anchor_count'), + 'residual': coordinate_transform.get('residual'), + } + ) + for order in orders: + if not isinstance(order, dict): + continue + groups = [order.get('header_fields') or []] + groups.extend( + line.get('fields') or [] + for line in order.get('lines') or [] + if isinstance(line, dict) + ) + for fields in groups: + for field in fields if isinstance(fields, list) else []: + if not isinstance(field, dict): + continue + for observation in field.get('observations') or []: + if not isinstance(observation, dict): + continue + evidence = observation.get('layout_evidence') + evidence = evidence if isinstance(evidence, dict) else {} + raw_source = observation.get('value_source') or evidence.get('source') or default_value_source + observation['value_source'] = source_aliases.get(str(raw_source or ''), default_source) + if 'evidence_ref' not in observation and evidence.get('evidence_ref') is not None: + observation['evidence_ref'] = evidence.get('evidence_ref') + if transform_ref is not None: + observation['transform_ref'] = transform_ref + + def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]: """读取唯一匹配坐标模板的 confirmed 订单字段;无页级证据或歧义时返回空锁集。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 13e2a498..ec0175c3 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -1108,9 +1108,11 @@ def _run_available_actions( if ( str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} ): - from app.services.shipping_notice.order_review_disposition_service import has_reparseable_batch_documents + from app.services.shipping_notice.order_review_disposition_service import ( + has_reparseable_batch_documents_readonly, + ) - if has_reparseable_batch_documents(user_id=int(run.user_id), run=run): + if has_reparseable_batch_documents_readonly(user_id=int(run.user_id), run=run): actions.append('reparse_batch') if run.status == 'failed' or any(unit.status == 'failed' for unit in units) or 'technical_failure' in categories: if 'retry_failed_attachments' not in actions: @@ -1390,7 +1392,9 @@ def _email_supplement_projection( 1 for order in orders if isinstance(order, dict) for conflict in order.get('conflicts') or [] if isinstance(conflict, dict) - if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous' + if str(conflict.get('reason') or '').strip() in { + 'supplement_relation_ambiguous', 'supplement_field_conflict', + } ) status = 'conflict' if conflict_count > 0 else 'merged' if relation_codes else '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 e86d24c8..26ff330a 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -1595,13 +1595,19 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: return False if not getattr(task, 'current_order_extraction_id', None): return False - return not bool( - getattr(task, 'inventory_snapshot_id', None) - or getattr(task, 'inventory_lines_json', None) - or getattr(task, 'match_status', None) - or getattr(task, 'export_file_path', None) - or getattr(task, 'upload_status', None) - ) + inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None) + inventory_lines = getattr(task, 'inventory_lines_json', None) + match_status = getattr(task, 'match_status', None) + export_file_path = getattr(task, 'export_file_path', None) + upload_status = getattr(task, 'upload_status', None) + # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 + # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 + has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool) + has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) + has_match = isinstance(match_status, str) and bool(match_status.strip()) + has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) + has_upload = isinstance(upload_status, str) and bool(upload_status.strip()) + return not (has_inventory or has_match or has_export or has_upload) def resolve_confirm_outcome(progress: dict[str, Any] | None) -> str: diff --git a/backend/app/services/shipping_notice/order_review_disposition_service.py b/backend/app/services/shipping_notice/order_review_disposition_service.py index af92d24e..7c1fbab2 100644 --- a/backend/app/services/shipping_notice/order_review_disposition_service.py +++ b/backend/app/services/shipping_notice/order_review_disposition_service.py @@ -92,8 +92,8 @@ def _case_document_identity(*, case: ShippingOrderReviewCase, documents_by_id: d return f'document:{document_id}' -def select_current_batch_reparse_cases( - *, user_id: int, run: ShippingOrderProcessingRun, +def _select_current_batch_reparse_cases( + *, user_id: int, run: ShippingOrderProcessingRun, for_update: bool, ) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]: """ 从批次 Run 谱系为每个原 PDF 选择最新 Review Case。 @@ -112,24 +112,26 @@ def select_current_batch_reparse_cases( ShippingOrderReviewStream.owner_user_id == int(user_id), ShippingOrderProcessingRun.conversation_id == str(run.conversation_id), ) - .with_for_update() - .all() ) + if for_update: + stream_cases = stream_cases.with_for_update() + stream_cases = stream_cases.all() if stream_cases: root = _run_lineage_root(run=run) return root, sorted(stream_cases, key=lambda item: int(item.document_id)) root = _run_lineage_root(run=run) runs = _lineage_runs(root=root, user_id=user_id) run_ids = [int(item.id) for item in runs] - cases = ( + cases_query = ( ShippingOrderReviewCase.query .filter( ShippingOrderReviewCase.owner_user_id == int(user_id), ShippingOrderReviewCase.run_id.in_(run_ids), ) - .with_for_update() - .all() ) + if for_update: + cases_query = cases_query.with_for_update() + cases = cases_query.all() document_ids = {int(case.document_id) for case in cases if int(case.document_id or 0) > 0} documents_by_id = { int(document.id): document @@ -145,6 +147,13 @@ def select_current_batch_reparse_cases( return root, [selected[key] for key in sorted(selected)] +def select_current_batch_reparse_cases( + *, user_id: int, run: ShippingOrderProcessingRun, +) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]: + """为批次重解析写命令选择当前 Case,并锁定参与决策的行。""" + return _select_current_batch_reparse_cases(user_id=user_id, run=run, for_update=True) + + def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessingRun) -> bool: """供投影判断批次操作可见性;确认/履约与非订单文件不作为可重解析目标。""" _root, cases = select_current_batch_reparse_cases(user_id=user_id, run=run) @@ -155,6 +164,21 @@ def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessin ) +def has_reparseable_batch_documents_readonly( + *, user_id: int, run: ShippingOrderProcessingRun, +) -> bool: + """为 GET 投影无锁判断批次重解析资格,禁止复用写命令的锁定选择器。""" + _root, cases = _select_current_batch_reparse_cases( + user_id=user_id, run=run, for_update=False, + ) + return any( + str(case.status or '').strip().lower() + in {'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending'} + and case.confirmed_task_id is None + for case in cases + ) + + def reparse_batch_documents( *, user_id: int, run_no: str, reason: str, comment: str | None = None, ) -> dict[str, Any]: diff --git a/backend/app/services/shipping_notice/order_review_field_conflict_service.py b/backend/app/services/shipping_notice/order_review_field_conflict_service.py index 6620b177..3a87cdd8 100644 --- a/backend/app/services/shipping_notice/order_review_field_conflict_service.py +++ b/backend/app/services/shipping_notice/order_review_field_conflict_service.py @@ -17,6 +17,7 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ShippingOrderCandidate, ShippingOrderReviewCase from app.services.shipping_notice.candidate_qualification_service import ( + field_evidence_gap_is_non_blocking, recalculate_candidate_qualification, resolve_review_case_customer_resolved, ) @@ -39,7 +40,12 @@ from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts ) _VC_CONFLICT_PREFIX = 'vc:' -_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) +_EVIDENCE_GAP_REASONS = frozenset({ + 'evidence_missing', + 'pdf_evidence_missing', + # 历史正文补充冲突缺失双方值和证据,必须显示重新识别入口,不能成为空面板阻断。 + 'supplement_conflict_evidence_insufficient', +}) def _conflict_key(*, field: str, line_index: Any) -> str: @@ -51,6 +57,12 @@ def _conflict_key(*, field: str, line_index: Any) -> str: return f'{idx}:{str(field or "").strip()}' +def _stored_conflict_key(item: dict[str, Any]) -> str: + """读取新旧 Candidate 冲突的稳定键,新 Finding 优先使用其冻结 conflict_key。""" + explicit = str(item.get('conflict_key') or '').strip() + return explicit or _conflict_key(field=item.get('field'), line_index=item.get('line_index')) + + def _candidate_for_case(case: ShippingOrderReviewCase) -> ShippingOrderCandidate | None: if not case.candidate_id: return None @@ -156,6 +168,36 @@ def _option_display( } +def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]: + """将统一 Finding 的 source 快照投影为复核选项,避免依赖已丢失的 Observation 索引。""" + options: list[dict[str, Any]] = [] + seen: set[str] = set() + for source in item.get('sources') or []: + if not isinstance(source, dict): + continue + raw_value = source.get('raw_value') + if raw_value in (None, ''): + continue + key = str(raw_value) + if key in seen: + continue + seen.add(key) + source_type = str(source.get('source_type') or '').strip() + evidence_role = 'primary_pdf' if source_type == 'pdf' else _evidence_role_for_source_type(source_type) + options.append({ + 'value_key': key, + 'display_value': raw_value, + 'sources': [source_type] if source_type else [], + 'source_type': source_type or None, + 'source_types': [source_type] if source_type else [], + 'evidence_role': evidence_role, + 'evidence_rank': None, + 'evidence_ref': source.get('evidence_ref'), + 'document_id': source.get('document_id'), + }) + return options + + def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: """按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。""" draft = case.current_draft @@ -341,11 +383,13 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')] reason = str(item.get('reason') or 'field_conflict') is_evidence_gap = reason in _EVIDENCE_GAP_REASONS + if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item): + continue # 只有多个候选值不一致才属于「字段冲突待裁决」。 if len(value_keys) < 2 and not is_evidence_gap: continue observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid] - options = [ + options = _finding_source_options(item) or [ _option_display( field=field, value_key=key, @@ -356,15 +400,16 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu ] line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None finding = { - 'conflict_key': _conflict_key(field=field, line_index=line_index), + 'conflict_key': _stored_conflict_key(item), 'field_code': field, 'line_index': line_index if line_index >= 0 else None, 'line_key': line_key, - 'scope': _finding_scope(case, field_code=field, line_index=line_index), + 'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)), 'severity': str(item.get('severity') or 'blocking'), 'reason': reason, 'options': options, 'observation_ids': observation_ids, + 'recovery_action': str(item.get('recovery_action') or '').strip() or None, } # 同一 scope/field/reason 只能有一个开放 Finding;重复来源合并为一张卡。 finding_identity = (finding['conflict_key'], reason) @@ -565,7 +610,7 @@ def resolve_review_case_field_conflict( for idx, item in enumerate(conflicts): if not isinstance(item, dict): continue - key = _conflict_key(field=item.get('field'), line_index=item.get('line_index')) + key = _stored_conflict_key(item) if key == raw_key: target_idx = idx target = item @@ -588,13 +633,17 @@ def resolve_review_case_field_conflict( 'option_index is required for adopt_option', code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID', ) - observations = _observations_index(_adjudication_blob(candidate)) - option = _option_display( - field=field_code, - value_key=value_keys[int(option_index)], - observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid], - observations=observations, - ) + options = _finding_source_options(target) + if options: + option = options[int(option_index)] + else: + observations = _observations_index(_adjudication_blob(candidate)) + option = _option_display( + field=field_code, + value_key=value_keys[int(option_index)], + observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid], + observations=observations, + ) chosen_display = option.get('display_value') elif mode == 'custom': if custom_value in (None, ''): @@ -614,7 +663,7 @@ def resolve_review_case_field_conflict( item for item in conflicts if not ( isinstance(item, dict) - and _conflict_key(field=item.get('field'), line_index=item.get('line_index')) == raw_key + and _stored_conflict_key(item) == raw_key ) ] candidate.conflicts_json = conflicts diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index c4275b88..06a9e8b2 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -7,8 +7,8 @@ services/shipping_notice/order_review_fulfillment_decision_service.py line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、 order_review_resume_service。 逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions; - 订单级聚合计数供侧栏主卡;旧 create_fulfillment_wave 仍走 confirm(BE-8 兼容); - OT 后自动 wave 另服务;履约「料号」= Schema part_number(内部料号),禁止 reservation 回填。 + 订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」= + Schema part_number(内部料号),禁止 reservation 回填。 """ from __future__ import annotations @@ -1252,156 +1252,6 @@ def decide_review_line_fulfillment( return attach_resume_outcome(payload, resume) -def create_fulfillment_wave( - *, - user_id: int, - case_no: str, - line_keys: list[str], - expected_draft_version: Any, - idempotency_key: str | None, - reason: str | None = None, -) -> dict[str, Any]: - """ - 为选中的完整明细行创建履约波次 Task。 - - 核心逻辑:仅接受已标记 fulfill_complete_line_now 且未入 Task 的行; - 建波次前强制 validate_draft 刷新库存事实并再次校验充足/Reservation; - 数量必须等于草稿整行;调用确认服务并传入 line_keys 过滤。 - - Args: - user_id: 操作人。 - case_no: Case 编号。 - line_keys: 本波次完整行键列表。 - expected_draft_version: 草稿版本。 - idempotency_key: 建单幂等键。 - reason: 可选备注。 - - Returns: - 确认结果 + line_fulfillment 投影。 - """ - keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] - if not keys: - raise ValidationError( - 'line_keys required', - code='SHIPPING.REVIEW_LINE_WAVE_EMPTY', - ) - if len(keys) != len(set(keys)): - raise ValidationError( - 'Duplicate line_keys', - code='SHIPPING.REVIEW_LINE_WAVE_DUPLICATE', - ) - - case = _load_writable_case(user_id=user_id, case_no=case_no) - # [STEP 1] 建波次前重跑草稿校验,消费最新库存/预留/路由投影。 - from app.services.shipping_notice.order_review_draft_service import validate_draft - - validate_draft( - user_id=int(user_id), - case_no=str(case_no), - expected_draft_version=expected_draft_version, - ) - case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no or '')) - if case is None: - raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') - - from app.services.shipping_notice.order_review_workbench_projection import ( - schema_fields_from_case, - ) - - draft_lines = _draft_line_map(case) - projections = _line_projection_map(case) - schema_fields = schema_fields_from_case(case) - for key in keys: - if key not in draft_lines: - raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND') - decision = _active_decision(case, key) - if decision is None or decision.decision_code != DECISION_FULFILL: - raise ConflictError( - 'Line must be marked fulfill_complete_line_now', - code='SHIPPING.REVIEW_LINE_NOT_READY_FOR_WAVE', - details={'line_key': key}, - ) - if decision.line_status in {'task_created', 'fulfilled'}: - raise ConflictError( - 'Line already in a task wave', - code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_key': key}, - ) - req, _avail = _assert_line_can_fulfill_complete( - line_key=key, - draft_line=draft_lines[key], - proj=projections.get(key) or {}, - schema_fields=schema_fields, - ) - # 禁止拆分:决定中的 required_qty 必须等于草稿整行数量 - if decision.required_qty and _parse_qty(decision.required_qty) != req: - raise ValidationError( - 'Quantity split is not allowed', - code='SHIPPING.REVIEW_LINE_QTY_SPLIT_FORBIDDEN', - details={'line_key': key}, - ) - - from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case - - # validate_draft 可能抬升草稿版本;以当前草稿版本确认。 - current_version = int(case.current_draft.draft_version) if case.current_draft else expected_draft_version - result = confirm_review_case( - user_id=int(user_id), - case_no=str(case_no), - expected_draft_version=current_version, - idempotency_key=idempotency_key, - confirm_note=reason, - line_keys=keys, - ) - - # [STEP 2] 标记决定为 task_created - from sqlalchemy import func - - case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no)) - # [STEP] 以本波次返回的 task_no 为准,避免多波次时 case.confirmed_task_id 竞态误绑。 - task_id = None - task_no = str((result or {}).get('task_no') or '').strip() - if task_no: - task_row = ShippingNotice.query.filter_by(task_no=task_no).first() - if task_row is not None: - task_id = int(task_row.id) - if task_id is None and isinstance(result, dict) and result.get('case'): - raw_task_id = result['case'].get('confirmed_task_id') - if raw_task_id is not None: - task_id = int(raw_task_id) - # 确认服务已写入 wave_lines;复用其波次号,避免二次递增。 - wave_no = ( - db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no)) - .filter(ShippingOrderReviewWaveLine.review_case_id == int(case.id)) - .scalar() - ) - next_wave = int(wave_no or 0) - if next_wave <= 0: - prior = ( - db.session.query(func.max(ShippingOrderReviewLineDecision.wave_no)) - .filter(ShippingOrderReviewLineDecision.review_case_id == int(case.id)) - .scalar() - ) - next_wave = int(prior or 0) + 1 - for key in keys: - decision = _active_decision(case, key) - if decision is None: - continue - decision.line_status = 'task_created' - decision.task_id = int(task_id) if task_id else decision.task_id - decision.wave_no = next_wave - decision.updated_at = datetime.utcnow() - db.session.flush() - - from app.services.shipping_notice.order_review_projection import serialize_review_case - - result = dict(result or {}) - result['line_fulfillment'] = project_review_case_line_decisions(case) - result['case'] = serialize_review_case(case) - result['wave_no'] = next_wave - return result - - def close_remaining_fulfillment( *, user_id: int, diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index cdd992ae..fb6877c2 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -40,14 +40,22 @@ from __future__ import annotations from typing import Any +from sqlalchemy.orm import Load + from app import db from app.models import ( + Job, ShippingOrderCandidate, ShippingOrderExtraction, ShippingOrderProcessingRun, ShippingOrderReviewCase, + ShippingOrderReviewDraft, ShippingOrderReviewStream, ShippingOrderIntake, + ShippingNotice, + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, ) @@ -539,6 +547,8 @@ def _document_filename(run: ShippingOrderProcessingRun, document_id: int) -> str def _document_intake_for_retry( run: ShippingOrderProcessingRun, document_id: int, + *, + intakes_by_no: dict[str, ShippingOrderIntake] | None = None, ) -> ShippingOrderIntake | None: """按冻结文档归属定位当前 Intake,避免工作台按文件名或会话猜测 SNI。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} @@ -550,6 +560,8 @@ def _document_intake_for_retry( continue intake_no = str(intake_snapshot.get('intake_no') or '').strip().upper() if intake_no: + if intakes_by_no is not None: + return intakes_by_no.get(intake_no) return ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() return None @@ -558,9 +570,17 @@ def _intake_retry_projection( case: ShippingOrderReviewCase, run: ShippingOrderProcessingRun, candidate: ShippingOrderCandidate | None, + *, + intake: ShippingOrderIntake | None = None, + intakes_by_no: dict[str, ShippingOrderIntake] | None = None, ) -> tuple[str | None, bool]: """返回当前 Case 唯一的 Intake 重试目标与服务端授权结果。""" - intake = _document_intake_for_retry(run, int(case.document_id)) + if intake is None: + intake = _document_intake_for_retry( + run, + int(case.document_id), + intakes_by_no=intakes_by_no, + ) retry_authorized = bool( intake is not None and str(intake.parse_status or '').strip().lower() == 'parse_failed' @@ -1052,11 +1072,33 @@ def _serialize_review_case_summary( case: ShippingOrderReviewCase, *, run: ShippingOrderProcessingRun, + candidates_by_id: dict[int, ShippingOrderCandidate] | None = None, + intakes_by_no: dict[str, ShippingOrderIntake] | None = None, + drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None, ) -> dict[str, Any]: """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。""" - candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None - intake = _document_intake_for_retry(run, int(case.document_id)) - intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate) + draft = ( + drafts_by_id.get(int(case.current_draft_id)) + if drafts_by_id is not None and case.current_draft_id + else case.current_draft + ) + candidate = ( + candidates_by_id.get(int(case.candidate_id)) + if candidates_by_id is not None and case.candidate_id + else (db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None) + ) + intake = _document_intake_for_retry( + run, + int(case.document_id), + intakes_by_no=intakes_by_no, + ) + intake_no, intake_retry_authorized = _intake_retry_projection( + case, + run, + candidate, + intake=intake, + intakes_by_no=intakes_by_no, + ) # 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。 # 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。 lifecycle_stage = 'intake_parse' @@ -1097,8 +1139,8 @@ def _serialize_review_case_summary( 'document_id': int(case.document_id), 'file_name': _document_filename(run, int(case.document_id)), 'status': case.status, - 'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None, - 'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0, + 'draft_version': int(draft.draft_version) if draft is not None else None, + 'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0, # Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。 # 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。 'available_actions': ( @@ -1170,16 +1212,162 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, .join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id) .filter(ShippingOrderProcessingRun.conversation_id == conversation_id) .filter(ShippingOrderReviewCase.status != 'superseded') + .options( + Load(ShippingOrderReviewCase).load_only( + ShippingOrderReviewCase.id, + ShippingOrderReviewCase.stream_id, + ShippingOrderReviewCase.revision_no, + ShippingOrderReviewCase.case_no, + ShippingOrderReviewCase.run_id, + ShippingOrderReviewCase.document_id, + ShippingOrderReviewCase.candidate_id, + ShippingOrderReviewCase.current_draft_id, + ShippingOrderReviewCase.confirmed_task_id, + ShippingOrderReviewCase.status, + ShippingOrderReviewCase.disposition, + ), + Load(ShippingOrderProcessingRun).load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.run_no, + ShippingOrderProcessingRun.conversation_id, + ShippingOrderProcessingRun.user_id, + ShippingOrderProcessingRun.schema_version_id, + ShippingOrderProcessingRun.input_snapshot_json, + ), + ) ) if owner_ids: query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids)) rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all() - items = [{ - **_serialize_review_case_summary(case, run=run), - 'stream_id': int(stream.id), - 'stream_state': stream.state, - 'source_run_no': run.run_no, - } for stream, case, run in rows] + case_ids = [int(case.id) for _, case, _ in rows] + candidate_ids = [int(case.candidate_id) for _, case, _ in rows if case.candidate_id] + draft_ids = [int(case.current_draft_id) for _, case, _ in rows if case.current_draft_id] + task_ids = [int(case.confirmed_task_id) for _, case, _ in rows if case.confirmed_task_id] + candidates_by_id = { + int(candidate.id): candidate + for candidate in ShippingOrderCandidate.query.filter(ShippingOrderCandidate.id.in_(candidate_ids)).all() + } if candidate_ids else {} + drafts_by_id = { + int(draft.id): draft + for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all() + } if draft_ids else {} + _tasks_by_id = { + int(task.id): task + for task in ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all() + } if task_ids else {} + intake_nos = { + str(intake_snapshot.get('intake_no') or '').strip().upper() + for _, case, run in rows + for intake_snapshot in (run.input_snapshot_json or {}).get('intakes', []) + if isinstance(intake_snapshot, dict) + for document in intake_snapshot.get('documents') or [] + if isinstance(document, dict) and int(document.get('document_id') or 0) == int(case.document_id) + } + intakes_by_no = { + str(intake.intake_no).strip().upper(): intake + for intake in ShippingOrderIntake.query.filter(ShippingOrderIntake.intake_no.in_(intake_nos)).all() + } if intake_nos else {} + + # 队列是会话级聚合:将逐 Case 的 STP 读取收敛为一次批量查询,并复用既有投影缓存契约。 + from app.services.shipping_notice.order_stp_auto_create_service import build_stp_idempotency_key + + stp_prefixes = { + f"stp-auto:{run.run_no}:doc-{int(case.document_id)}:" + for _, case, run in rows + if case.document_id is not None + } + stp_refs = { + build_stp_idempotency_key( + run_no=run.run_no, + document_id=int(case.document_id), + draft_version=int(drafts_by_id[int(case.current_draft_id)].draft_version), + ) + for _, case, run in rows + if case.current_draft_id and int(case.current_draft_id) in drafts_by_id + } + jobs_by_ref: dict[str, list[Job]] = {ref: [] for ref in stp_refs} + jobs_by_prefix: dict[str, list[Job]] = {prefix: [] for prefix in stp_prefixes} + if stp_prefixes: + from sqlalchemy import or_ + from app.services.shipping_notice.order_stp_auto_create_service import SHIPPING_STP_JOB_DOMAIN + from app.jobs.types import JobType + + jobs = ( + Job.query.filter( + Job.domain == SHIPPING_STP_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + or_(*(Job.business_ref.like(f'{prefix}%') for prefix in stp_prefixes)), + ).order_by(Job.id.desc()).all() + ) + for job in jobs: + ref = str(job.business_ref or '').strip() + jobs_by_ref.setdefault(ref, []).append(job) + prefix = next((item for item in stp_prefixes if ref.startswith(item)), None) + if prefix: + jobs_by_prefix[prefix].append(job) + + executions_by_case_id: dict[int, ShippingProcessExecution] = {} + gates_by_execution_id: dict[int, list[ShippingProcessGate]] = {} + latest_attempt_by_id: dict[int, ShippingProcessGateAttempt] = {} + if case_ids: + executions = ( + ShippingProcessExecution.query.filter( + ShippingProcessExecution.review_case_id.in_(case_ids), + ShippingProcessExecution.status != 'superseded', + ).order_by(ShippingProcessExecution.id.desc()).all() + ) + execution_ids = [int(execution.id) for execution in executions] + for execution in executions: + if execution.review_case_id is not None: + executions_by_case_id.setdefault(int(execution.review_case_id), execution) + if execution_ids: + gates = ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id.in_(execution_ids), + ).order_by( + ShippingProcessGate.execution_id.asc(), + ShippingProcessGate.sequence_no.asc(), + ).all() + for gate in gates: + gates_by_execution_id.setdefault(int(gate.execution_id), []).append(gate) + latest_attempt_ids = [ + int(gate.latest_attempt_id) + for gate in gates + if gate.latest_attempt_id is not None + ] + if latest_attempt_ids: + latest_attempt_by_id = { + int(attempt.id): attempt + for attempt in ShippingProcessGateAttempt.query.filter( + ShippingProcessGateAttempt.id.in_(latest_attempt_ids), + ).all() + } + + previous_cache = db.session.info.get('shipping_conversation_projection_read_cache') + cache = dict(previous_cache) if isinstance(previous_cache, dict) else {} + cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **jobs_by_ref} + cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **jobs_by_prefix} + cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **executions_by_case_id} + cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **gates_by_execution_id} + cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **latest_attempt_by_id} + db.session.info['shipping_conversation_projection_read_cache'] = cache + try: + items = [{ + **_serialize_review_case_summary( + case, + run=run, + candidates_by_id=candidates_by_id, + intakes_by_no=intakes_by_no, + drafts_by_id=drafts_by_id, + ), + 'stream_id': int(stream.id), + 'stream_state': stream.state, + 'source_run_no': run.run_no, + } for stream, case, run in rows] + finally: + if previous_cache is None: + db.session.info.pop('shipping_conversation_projection_read_cache', None) + else: + db.session.info['shipping_conversation_projection_read_cache'] = previous_cache counts = { 'total': len(items), 'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')), diff --git a/backend/app/services/shipping_notice/order_review_service.py b/backend/app/services/shipping_notice/order_review_service.py index 9e56a087..dda4cfa4 100644 --- a/backend/app/services/shipping_notice/order_review_service.py +++ b/backend/app/services/shipping_notice/order_review_service.py @@ -17,6 +17,7 @@ from __future__ import annotations import uuid from typing import Any +from sqlalchemy.orm import load_only from sqlalchemy.orm.attributes import flag_modified from app import db @@ -429,13 +430,32 @@ def get_review_queue_visible_to_user( is_admin: bool = False, ) -> list[ShippingOrderProcessingRun]: """按当前 Run 定位会话;Stream 当前版本决定队列,Run 替代标记不再过滤文件。""" - anchor = get_review_run_visible_to_user(run_no, user_id, is_admin=is_admin) + # 队列仅需要会话与 owner 范围;不要为授权读取解码 Run 的审计/执行大 JSON。 + anchor = ( + ShippingOrderProcessingRun.query.options( + load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.user_id, + ShippingOrderProcessingRun.conversation_id, + ), + ) + .filter_by(run_no=run_no) + .first() + ) + if anchor is None or (not is_admin and int(anchor.user_id) != int(user_id)): + raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND') query = ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.conversation_id == anchor.conversation_id, ) if not is_admin: query = query.filter(ShippingOrderProcessingRun.user_id == int(user_id)) - return query.order_by( + return query.options( + load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.user_id, + ShippingOrderProcessingRun.conversation_id, + ), + ).order_by( ShippingOrderProcessingRun.created_at.asc(), ShippingOrderProcessingRun.id.asc(), ).all() diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index 11b16712..f287239c 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -444,12 +444,19 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success verified_upload_success = has_verified_upload_success(task) - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() + upload_status = getattr(task, 'upload_status', None) + upload_status = upload_status.strip().lower() if isinstance(upload_status, str) else '' + export_file_path = getattr(task, 'export_file_path', None) + match_status = getattr(task, 'match_status', None) + inventory_lines = getattr(task, 'inventory_lines_json', None) + has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) + has_match = isinstance(match_status, str) and bool(match_status.strip()) + has_inventory = isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) progress_state = ( 'uploaded' if verified_upload_success - else 'export_ready' if getattr(task, 'export_file_path', None) - else 'matched' if getattr(task, 'match_status', None) - else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) + else 'export_ready' if has_export + else 'matched' if has_match + else 'inventory_ready' if has_inventory else 'not_started' ) active = find_active_shipping_notice_run_job(task_no=task_no or '') diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 40c8836c..3ff40227 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -1187,19 +1187,6 @@ def persist_dynamic_order( documents, schema_definition=version.definition_json or {}, layout_candidates_by_document=layout_candidates_by_document, ) - for issue in table_issues: - blocked.extend(str(code) for code in issue['field_codes']) - for code in issue.get('field_codes') or []: - findings.append({ - 'finding_code': 'layout_table_evidence_blocked', - 'owning_gate_code': 'layout_parsing', - 'severity': 'blocking', - 'field_code': str(code), - 'decision_id': None, - 'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'), - 'user_visible': True, - 'blocks_current_action': True, - }) groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [ (None, None, 'header', raw_order.get('header_fields') or [], header) ] @@ -1383,6 +1370,41 @@ def persist_dynamic_order( owning_gate_code='field_completeness', )) + # 表格候选未被整表接受只代表结构化坐标质量不足。若当前字段已有已接受的 + # 可验证证据,不能用表格诊断覆盖该字段事实;否则关键字段仍须保守阻断。 + accepted_field_codes = { + str(decision.get('field_code') or '') + for decision in decisions + if str(decision.get('status') or '') in {'accepted', 'corroborated', 'derived'} + } + for issue in table_issues: + blocking_codes = [ + str(code) + for code in issue['field_codes'] + if str(code) not in accepted_field_codes + and field_may_block_process( + next( + ( + config for config in all_configs.values() + if str(config.get('field_code') or '') == str(code) + ), + None, + ) + ) + ] + blocked.extend(blocking_codes) + for code in issue.get('field_codes') or []: + findings.append({ + 'finding_code': 'layout_table_evidence_blocked', + 'owning_gate_code': 'layout_parsing', + 'severity': 'blocking' if str(code) in blocking_codes else 'diagnostic', + 'field_code': str(code), + 'decision_id': None, + 'reason_code': str(issue.get('reason') or 'layout_evidence_unavailable'), + 'user_visible': str(code) in blocking_codes, + 'blocks_current_action': str(code) in blocking_codes, + }) + # 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。 system_line_projections: list[dict[str, Any]] = [] for line, projection in zip(extraction.lines, line_projections): diff --git a/backend/app/services/shipping_notice/order_stp_auto_create_service.py b/backend/app/services/shipping_notice/order_stp_auto_create_service.py index af98c29f..5659d274 100644 --- a/backend/app/services/shipping_notice/order_stp_auto_create_service.py +++ b/backend/app/services/shipping_notice/order_stp_auto_create_service.py @@ -322,6 +322,13 @@ def find_active_stp_job(*, business_ref: str) -> Job | None: key = str(business_ref or '').strip() if not key: return None + cache = db.session.info.get('shipping_conversation_projection_read_cache') + if isinstance(cache, dict): + jobs = cache.get('stp_jobs_by_ref', {}).get(key, []) + return next( + (job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}), + None, + ) return ( Job.query .filter( @@ -348,6 +355,10 @@ def find_latest_stp_job(*, business_ref: str) -> Job | None: key = str(business_ref or '').strip() if not key: return None + cache = db.session.info.get('shipping_conversation_projection_read_cache') + if isinstance(cache, dict): + jobs = cache.get('stp_jobs_by_ref', {}).get(key, []) + return jobs[0] if jobs else None return ( Job.query .filter( diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index 1c23a346..ddc5d92c 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -9,6 +9,7 @@ from __future__ import annotations import copy from typing import Any +from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.po_number import normalize_atomic_po_number @@ -50,6 +51,135 @@ def _schema_field_values(row: dict[str, Any], field_codes: set[str]) -> set[str] } +def _canonical_field_value(value: Any, config: dict[str, Any]) -> Any: + """返回冻结 Schema 下用于跨来源比较的字段规范值,保留调用方持有的原始证据值。 + + 核心逻辑:正文补充合并不能把金额、小数位、日期等显示格式差异误判为业务冲突; + 统一复用订单 Schema 的标准化器,遇到非法值仍向上抛出既有校验异常而非放行。 + + Args: + value: PDF Observation 或邮件正文行中的原始值。 + config: 该 field_code 对应的冻结 Schema 配置。 + + Returns: + 可进行语义相等比较的规范值。 + """ + return normalize_order_field_value(value, config) + + +def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]: + """收集字段 Observation 的规范值集合,禁止以显示文本代替业务等价判断。""" + if not isinstance(fields, list): + return set() + return { + _canonical_field_value(observation.get('value'), config) + for field in fields if isinstance(field, dict) + if codes.get(str(field.get('field_id') or '')) == code + for observation in field.get('observations') or [] if isinstance(observation, dict) + if observation.get('value') not in (None, '') + } + + +def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]: + """返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。""" + if not isinstance(fields, list): + return [] + return [ + observation + for field in fields if isinstance(field, dict) + if codes.get(str(field.get('field_id') or '')) == code + for observation in field.get('observations') or [] if isinstance(observation, dict) + if observation.get('value') not in (None, '') + ] + + +def _supplement_field_conflict( + *, + field_code: str, + config: dict[str, Any], + line_index: int, + pdf_observations: list[dict[str, Any]], + email_value: Any, + email_evidence: dict[str, Any], + email_document_id: int, + schema_version: str, +) -> dict[str, Any]: + """构造可展示、可裁决的正文补充字段冲突 Finding。 + + 核心逻辑:Candidate Gate、复核面板和进度统计必须消费同一事实;因此不能只保存 + field/reason,而要冻结双方原值、Schema 规范值、文档和 evidence_ref。 + """ + pdf = pdf_observations[0] if pdf_observations else {} + pdf_raw = pdf.get('value') + email_raw = email_value + return { + 'conflict_key': f'{line_index}:{field_code}', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'field': field_code, + 'scope': 'header' if line_index < 0 else 'line', + 'line_index': line_index if line_index >= 0 else None, + 'values': [str(pdf_raw), str(email_raw)], + 'sources': [ + { + 'source_type': 'pdf', + 'raw_value': str(pdf_raw), + 'canonical_value': str(_canonical_field_value(pdf_raw, config)), + 'document_id': pdf.get('document_id'), + 'evidence_ref': dict(pdf.get('evidence_ref') or {}), + }, + { + 'source_type': 'email_body', + 'raw_value': str(email_raw), + 'canonical_value': str(_canonical_field_value(email_raw, config)), + 'document_id': email_document_id or None, + 'evidence_ref': dict(email_evidence or {}), + }, + ], + 'rule_version': schema_version or 'shipping-order-schema.unknown', + } + + +def _supplement_multi_value_conflict( + *, + field_code: str, + config: dict[str, Any], + values: set[str], + selected_rows: list[dict[str, Any]], + line_index: int, + email_document_id: int, + schema_version: str, +) -> dict[str, Any]: + """构造邮件正文内部多值的完整 Finding,禁止保留不可展示的旧简略冲突。""" + ordered_values = sorted(values) + sources: list[dict[str, Any]] = [] + for row in selected_rows: + raw_value = str(row.get(field_code) or '').strip() + if not raw_value: + continue + evidence = row.get('evidence', {}).get(field_code, {}) if isinstance(row.get('evidence'), dict) else {} + sources.append({ + 'source_type': 'email_body', + 'raw_value': raw_value, + 'canonical_value': str(_canonical_field_value(raw_value, config)), + 'document_id': email_document_id or None, + 'evidence_ref': dict(evidence or {}), + }) + return { + 'conflict_key': f'{line_index}:{field_code}', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'field': field_code, + 'scope': 'header' if line_index < 0 else 'line', + 'line_index': line_index if line_index >= 0 else None, + 'values': ordered_values, + 'sources': sources, + 'rule_version': schema_version or 'shipping-order-schema.unknown', + } + + def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]: """按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。""" configs = { @@ -59,6 +189,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta } ids = {code: str(item.get('field_id') or '') for code, item in configs.items() if item.get('field_id')} part_codes = {'part_number', 'customer_part_number'} & set(configs) + schema_version = str(schema_definition.get('version') or '') merged: list[dict[str, Any]] = [] for raw in orders: order = copy.deepcopy(raw) @@ -107,52 +238,81 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta continue for source_row in selected: row_part_values = _schema_field_values(source_row, part_codes) - target_lines = [line for line in order.get('lines') or [] if isinstance(line, dict)] + indexed_target_lines = [ + (index, line) + for index, line in enumerate(order.get('lines') or []) + if isinstance(line, dict) + ] if relation != 'po_fallback': # 精确料号命中(含 PN/AMPN × 内部/客户料号四种组合)只写入交集行。 - target_lines = [ - line for line in target_lines + indexed_target_lines = [ + (index, line) for index, line in indexed_target_lines if row_part_values & ( _values(line.get('fields'), 'part_number', {v: k for k, v in ids.items()}) | _values(line.get('fields'), 'customer_part_number', {v: k for k, v in ids.items()}) ) ] - if not target_lines: + if not indexed_target_lines: order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'}) continue + target_lines = [line for _, line in indexed_target_lines] for target_code, config in configs.items(): - values = { - str(item.get(target_code) or '').strip() - for item in selected - if str(item.get(target_code) or '').strip() - } - if len(values) > 1: - order.setdefault('conflicts', []).append({ - 'severity': 'blocking', 'reason': 'supplement_field_conflict', - 'field': target_code, - }) - continue - value = next(iter(values), '') - field_id = ids.get(target_code) - if not value or not field_id: - continue - target_groups = order.get('header_fields') if config.get('scope') == 'header' else [line.setdefault('fields', []) for line in target_lines] - for fields in ([target_groups] if config.get('scope') == 'header' else target_groups): + target_groups = ( + [(-1, order.get('header_fields'))] + if config.get('scope') == 'header' + else [(index, line.setdefault('fields', [])) for index, line in indexed_target_lines] + ) + for line_index, fields in target_groups: if not isinstance(fields, list): continue - existing_values = _values(fields, target_code, {v: k for k, v in ids.items()}) + value_by_canonical: dict[Any, tuple[str, dict[str, Any]]] = {} + comparable_rows = selected if line_index < 0 or relation == 'po_fallback' else [source_row] + for item in comparable_rows: + raw_value = str(item.get(target_code) or '').strip() + if raw_value: + value_by_canonical.setdefault( + _canonical_field_value(raw_value, config), + (raw_value, item), + ) + values = {raw_value for raw_value, _ in value_by_canonical.values()} + if len(value_by_canonical) > 1: + conflict = _supplement_multi_value_conflict( + field_code=target_code, + config=config, + values=values, + selected_rows=comparable_rows, + line_index=line_index, + email_document_id=int(supplement.get('document_id') or 0), + schema_version=schema_version, + ) + if conflict not in order.setdefault('conflicts', []): + order['conflicts'].append(conflict) + continue + value, value_source_row = next(iter(value_by_canonical.values()), ('', {})) + field_id = ids.get(target_code) + if not value or not field_id: + continue + existing_values = _canonical_values( + fields, target_code, {v: k for k, v in ids.items()}, config, + ) if existing_values: # PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略: # 保留 PDF 值,强制进入 Review 由人工裁决。 - if existing_values != {value.strip().upper()}: - conflict = { - 'severity': 'blocking', 'reason': 'supplement_field_conflict', - 'field': target_code, - } + if existing_values != {_canonical_field_value(value, config)}: + conflict = _supplement_field_conflict( + field_code=target_code, + config=config, + line_index=line_index, + pdf_observations=_field_observations(fields, target_code, {v: k for k, v in ids.items()}), + email_value=value, + email_evidence=value_source_row.get('evidence', {}).get(target_code, {}), + email_document_id=int(supplement.get('document_id') or 0), + schema_version=schema_version, + ) if conflict not in order.setdefault('conflicts', []): order['conflicts'].append(conflict) continue - _inject(fields, field_id, value, source_row.get('evidence', {}).get(target_code, {}), int(supplement.get('document_id') or 0)) + _inject(fields, field_id, value, value_source_row.get('evidence', {}).get(target_code, {}), int(supplement.get('document_id') or 0)) # 来源方和分配实体是证据字段;没有对应 Schema 字段时仍写入内部订单元数据。 order.setdefault('_hxops_email_supplement_evidence', []).append({ 'source_from_party': source_row.get('source_from_party'), diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 1762d599..f550e9d7 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -234,26 +234,30 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo gate: 门禁行。 include_diagnostics: False 时仅保留用户可见 blocking Finding。 """ - legacy_readonly = str(gate.gate_code or '').strip() not in PROCESS_GATE_CODE_SET - definition = ( - {'label': '历史 AutoProgress 记录', 'responsible_party': 'system', 'recoverable': False} - if legacy_readonly else _projection_gate_definition(gate.gate_code) - ) + definition = _projection_gate_definition(gate.gate_code) latest = None if gate.latest_attempt_id: - latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id)) + from app import db + + cache = db.session.info.get('shipping_conversation_projection_read_cache') + latest = ( + cache.get('latest_attempt_by_id', {}).get(int(gate.latest_attempt_id)) + if isinstance(cache, dict) else None + ) + if latest is None: + 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) ] - allowed_actions = [str(gate.next_action_code)] if not legacy_readonly and ( + allowed_actions = [str(gate.next_action_code)] if ( gate.next_action_code and is_business_user_action(str(gate.next_action_code)) ) else [] # 将 RecoveryPlan 目标绑定到当前 Gate 对象,避免 Case/UI 包装层只透传主动作时丢失恢复按钮。 from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS - recovery_targets = [] if legacy_readonly else [ + recovery_targets = [ { 'action_code': action_code, 'target_gate': plan.get('target_gate'), @@ -266,7 +270,6 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo ] return { 'gate_code': gate.gate_code, - 'legacy_readonly': legacy_readonly, 'sequence_no': int(gate.sequence_no), 'label': definition.get('label'), 'implementation_status': definition.get('implementation_status'), @@ -316,23 +319,31 @@ def serialize_process_execution( Returns: 含当前门禁、主动作与全部门禁轨道的字典。 """ + from app import db + + cache = db.session.info.get('shipping_conversation_projection_read_cache') gates = ( - ShippingProcessGate.query - .filter_by(execution_id=int(execution.id)) - .order_by(ShippingProcessGate.sequence_no.asc()) - .all() + cache.get('gates_by_execution_id', {}).get(int(execution.id), []) + if isinstance(cache, dict) else [] ) + if not gates: + 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 + if str(gate.gate_code or '').strip() in PROCESS_GATE_CODE_SET ] current = next( (item for item in serialized if item.get('gate_code') == execution.current_gate_code), None, ) - legacy_readonly = any(item.get('legacy_readonly') for item in serialized) recovery_targets: list[dict[str, Any]] = [] - if execution.current_gate_code and not legacy_readonly: + if execution.current_gate_code in PROCESS_GATE_CODE_SET: # RecoveryPlan 合同是服务端唯一动作来源;Projection 只读输出,客户端不能改写 target Gate。 from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS @@ -345,14 +356,18 @@ def serialize_process_execution( 'invalidates': list(definition.get('invalidates') or ()), 'permission': definition.get('permission'), }) - active_recovery_plans = ShippingProcessRecoveryPlan.query.filter( - ShippingProcessRecoveryPlan.execution_id == int(execution.id), - ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}), - ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() + active_recovery_plans = ( + cache.get('active_recovery_plans_by_execution_id', {}).get(int(execution.id), []) + if isinstance(cache, dict) else None + ) + if active_recovery_plans is None: + active_recovery_plans = ShippingProcessRecoveryPlan.query.filter( + ShippingProcessRecoveryPlan.execution_id == int(execution.id), + ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}), + ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() return { 'execution_no': execution.execution_no, - 'status': 'legacy_readonly' if legacy_readonly else execution.status, - 'legacy_readonly': legacy_readonly, + '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, @@ -497,45 +512,6 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。 """ full = serialize_process_execution(execution, include_diagnostics=False) - # 完成态的正式 Execution 会清空 current_gate_code;空值表示没有待处理 Gate, - # 不能被误判为已下线的 APX 历史执行。只有存在实际 Gate 编号且不在正式契约内时, - # 才进入 legacy_readonly 兼容投影。 - current_gate_code = str(getattr(execution, 'current_gate_code', '') or '').strip() - legacy_readonly = bool(full.get('legacy_readonly')) or ( - bool(current_gate_code) and current_gate_code not in PROCESS_GATE_CODE_SET - ) - if legacy_readonly: - refs = _execution_navigation_refs(execution) - return { - 'execution_no': full.get('execution_no'), - 'status': 'legacy_readonly', - 'legacy_readonly': True, - 'execution_status': None, - 'current_gate': full.get('current_gate'), - 'current_blocking_gate': None, - 'recovery_targets': [], - 'active_recovery_plans': [], - 'blocking_reason_code': 'shipping_apx_runtime_disabled', - 'blocking_message': '历史自动推进记录仅供审计查看', - 'failure_detail': None, - 'explainability': None, - 'next_action_code': None, - 'primary_action': None, - 'allowed_actions': [], - 'action_presentation': [], - 'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}], - 'technical_auto_only': True, - 'owner_type': 'system', - 'responsible_party': 'system', - 'diagnostic_hint': None, - **refs, - 'navigation': None, - '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 []) - ], - } current = full.get('current_gate') blocking = None if ( diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index 13c33896..a593bf99 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -305,15 +305,13 @@ def ensure_execution_for_workflow_version( .order_by(ShippingProcessExecution.id.desc()) .first() ) - # APX 六 Gate 与正式 20-Gate 不能共用同一 Execution。历史数据可能仍按 - # task_id 被查到;此时必须新建正式链,禁止把 20-Gate 行写进 APX sequence。 if existing is not None: existing_codes = { str(row.gate_code or '').strip() for row in ShippingProcessGate.query.filter_by(execution_id=int(existing.id)).all() } if existing_codes and not existing_codes.issubset(PROCESS_GATE_CODE_SET): - existing = None + raise RuntimeError('shipping_process_execution_contract_invalid') if existing is not None: if review_case_id and existing.review_case_id is None: existing.review_case_id = int(review_case_id) diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index e1561315..735be71a 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -45,7 +45,6 @@ _WRITE_ACTION_CODES = frozenset({ 'open_shortage_review', 'upload_inventory_file', 'retry_inventory_preparation', - 'retry', 'retry_parse', 'retry_failed_documents', 'regenerate_excel', @@ -79,8 +78,10 @@ _POST_CREATE_STAGES = frozenset({ _ACTION_CODE_ALIASES: dict[str, str] = { 'open_review': 'open_order_review', 'open_order_processing': 'open_order_review', - 'retry_parse': 'retry', - 'retry_failed_documents': 'retry', + # 解析恢复保留其对象边界;不得再塌缩成泛化 retry,否则前端无法判定 + # 应重投 Intake、重跑 Run,还是提交当前 Gate。 + 'retry_parse': 'retry_parse', + 'retry_failed_documents': 'retry_failed_documents', 'open_fulfillment': 'view_result', 'view_details': 'view_result', 'wait_manual_upload': 'open_manual_upload', @@ -90,6 +91,7 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'rematch': 'open_inventory_match_review', 'match_inventory': 'open_inventory_match_review', 'generate_excel': 'regenerate_excel', + 'confirm_inventory_source': 'open_inventory_source_review', # 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由 # Gate API 使用原始 action_code 校验,legacy projection 只负责展示语义。 'regenerate_excel_artifact': 'regenerate_excel', @@ -97,13 +99,27 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'reparse_batch': 'reparse_batch', } +# 具有独立对象边界的动作。它们不是泛化 retry,必须保留原始码,避免丢失 +# 重解析、草稿裁决等业务能力。 +_OBJECT_EXECUTABLE_ACTION_CODES = frozenset({ + 'retry_parse', + 'retry_failed_documents', + 'retry_failed_attachments', + 'reparse', + 'reparse_batch', + 'create_draft', + 'edit_draft', + 'reconcile_and_progress', +}) +# Retry Decision 是旧任务恢复协调器的内部语义。投影只把可确定的决策翻译成 +# 已注册的精确 Gate 动作;绝不再下发字面量 retry。 def normalize_action_code(code: str | None) -> str | None: """ - 将原始动作码规范为 SHIPPING_PROCESSING_ACTION_INTENTS 可识别的契约码。 + 将原始动作码规范为正式 Gate 或具备独立对象边界的业务动作码。 Args: - code: Gate / legacy available_actions 原始码。 + code: Gate 或独立业务动作原始码。 Returns: 契约动作码;无法映射时返回 None(禁止泄漏未知码)。 @@ -112,6 +128,16 @@ def normalize_action_code(code: str | None) -> str | None: if not raw: return None mapped = _ACTION_CODE_ALIASES.get(raw, raw) + # 字面量 retry 没有对象/阶段边界,禁止从历史 payload 重新授权为 UI 动作。 + if mapped == 'retry': + return None + if mapped in _OBJECT_EXECUTABLE_ACTION_CODES: + return mapped + # Gate 合同是正式动作码全集;这里仅作契约校验,不改变原始动作码。 + from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_ACTION_CODES + + if mapped in PROCESS_GATE_ACTION_CODES: + return mapped if mapped in SHIPPING_PROCESSING_ACTION_INTENTS and mapped != 'none': return mapped return None @@ -365,23 +391,24 @@ def derive_available_actions( status: str, stage: str, gate: dict[str, Any] | None, - legacy_actions: list[str] | None = None, + authorized_actions: list[str] | None = None, excel_ready: bool = False, shipping_notice_no: str | None = None, ) -> list[str]: """ - 由 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage 猜测可下载。 + 由持久化 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage + 或未落库的 Gate 片段猜测可操作入口。 核心逻辑:Gate next_action 优先;download_excel 仅当 excel_ready; regenerate_excel 仅当处于 excel_generating 且非 automating 且 Excel 未就绪; - open_manual_upload 仅当 Gate 或 legacy 明确给出;completed → view_result; + open_manual_upload 仅当 Gate 或已授权动作明确给出;completed → view_result; 建单前剔除匹配/Excel/上传等履约动作(fail-closed)。 Args: status: 统一 status。 stage: 统一 stage。 - gate: current_gate 摘要。 - legacy_actions: 可选旧会话卡动作,仅保留可映射项。 + gate: current_gate 摘要;仅正式 Process Gate code 可授权动作。 + authorized_actions: 调用方已裁决的精确对象动作,不能由状态推断。 excel_ready: 是否存在 ready 的发货 Excel Artifact。 shipping_notice_no: 正式 Notice 任务号;空表示建单前。 @@ -393,7 +420,14 @@ def derive_available_actions( post_create = _is_post_create(stage=stage_norm, shipping_notice_no=shipping_notice_no) actions: list[str] = [] seen: set[str] = set() - gate_action = _gate_next_action(gate) + # current_gate 可能来自旧 Case/任务快照。只有 process_gate_contract 注册的 + # 正式 Gate 才能授权动作;历史码即使携带 next_action_code 也必须 fail-closed。 + gate_code = str( + (gate or {}).get('gate_code') or (gate or {}).get('gateCode') or '' + ).strip().lower() if isinstance(gate, dict) else '' + from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET + gate_declared = gate_code in PROCESS_GATE_CODE_SET + gate_action = _gate_next_action(gate) if gate_declared else None def _push(raw: str | None) -> None: code = normalize_action_code(raw) @@ -412,13 +446,8 @@ def derive_available_actions( _push(gate_action) - # [BE-04] 仅技术失败允许默认 retry;业务 blocked 只保留 Gate next_action。 - if status_norm == 'failed' and 'retry' not in seen: - _push('retry') - elif status_norm == 'blocked' and gate_action in { - 'retry', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', - }: - _push('retry') + # 技术失败只能由当前 Gate 或 Retry Decision 下发精确恢复动作。禁止在 + # available_actions 注入字面量 retry,避免跨阶段错误重跑抽取。 if status_norm == 'completed': _push('view_result') elif ( @@ -434,13 +463,14 @@ def derive_available_actions( if excel_ready: _push('download_excel') - for item in legacy_actions or []: - mapped = normalize_action_code(item) - # [BE-07] legacy 只补充只读类动作,禁止用旧卡覆盖 Gate 写意图。 - if mapped in {'view_result', 'view_record', 'refresh', 'download_excel'}: - _push(mapped) - elif mapped == 'open_manual_upload': - _push(mapped) + for item in authorized_actions or []: + code = normalize_action_code(item) + # Gate 片段已声明当前节点时,它是唯一写动作裁决者。调用方携带的对象级 + # 授权只可补足完全无 Gate 的解析处置;即使 Gate 尚未证明已持久化,也不得 + # 用历史动作绕过它并把 match_inventory 等带入 Excel/上传节点。 + if gate_declared and code not in {'view_result', 'view_record', 'refresh', 'download_excel'}: + continue + _push(code) if not actions: actions = ['view_result'] if status_norm in {'completed', 'failed', 'cancelled'} else [] @@ -450,7 +480,7 @@ def derive_available_actions( def reconcile_processing_projection_facts( payload: dict[str, Any], *, - legacy_actions: list[str] | None = None, + authorized_actions: list[str] | None = None, invalidated_from_stage: str | None = None, excel_ready: bool = False, verified_upload_success: bool | None = None, @@ -467,7 +497,7 @@ def reconcile_processing_projection_facts( Args: payload: 即将返回的 ShippingProcessingProjection dict(snake_case)。 - legacy_actions: 可选旧动作列表。 + authorized_actions: 调用方已裁决的精确对象动作。 invalidated_from_stage: 可选失效起点 stage。 excel_ready: 是否存在 ready Excel Artifact。 @@ -591,7 +621,7 @@ def reconcile_processing_projection_facts( status=status, stage=stage, gate=gate, - legacy_actions=legacy_actions if legacy_actions is not None else list( + authorized_actions=authorized_actions if authorized_actions is not None else list( payload.get('available_actions') or [] ), excel_ready=excel_ready, @@ -649,10 +679,10 @@ def apply_user_projection_fields( 【AI 触发时机】:任何需要向前端返回 OrderTask/Conversation 投影的末端出口, 在 reconcile_processing_projection_facts 之后、record_projection_inconsistency 之后调用。 - 核心逻辑(决策 F3:新增字段不替换旧枚举,Retry Decision 优先 + legacy 兜底): - [STEP 1] 保存旧枚举到 legacy_status / legacy_stage / legacy_current_gate,避免旧前端 break。 + 核心逻辑:以正式 Process Gate 与领域事实生成唯一用户态 DTO。 + [STEP 1] 读取当前投影 status / stage / current_gate 作为计算输入,不输出兼容镜像。 [STEP 2] 读取 pending_reason / review_status / inventory_source_status 原始字段。 - [STEP 3] 计算 Retry Decision(仅 notice 存在时,失败/不存在则 legacy 兜底)。 + [STEP 3] 按正式 Gate 与领域终态裁决用户状态。 [STEP 4] 按冻结优先级计算 user_status(completed/cancelled/failed → retryable → waiting_human → running)。 [STEP 5] 仅在投影内部计算可重试语义,用于生成唯一 primary_action;不再输出旧 retryable 布尔字段。 [STEP 6] 计算 blocking_reason:{code, i18n_key, details} 或 None。 @@ -665,7 +695,7 @@ def apply_user_projection_fields( order_task: 可选 ShippingOrderTask 实体(用于 facts 与 legacy pending_reason)。 Returns: - 就地修改后的 payload(含新增 6 字段与 3 个 legacy_* 备份)。 + 就地修改后的 payload(含用户态字段;不保留旧字段备份)。 """ from app.services.shipping_notice.constants import ( RS_SHORTAGE_REVIEW as REVIEW_STATUS_SHORTAGE_REVIEW, @@ -677,10 +707,7 @@ def apply_user_projection_fields( _INVENTORY_SOURCE_STATUS_RESOLVED = 'resolved' _PROCESS_HUMAN_PENDING_MATCH = 'match_review_pending' - # ===== [STEP 1] 旧枚举备份(保持不变) ===== - payload['legacy_status'] = payload.get('status') - payload['legacy_stage'] = payload.get('stage') - payload['legacy_current_gate'] = payload.get('current_gate') + # ===== [STEP 1] 读取当前投影输入 ===== old_status = str(payload.get('status') or '').strip().lower() old_stage = str(payload.get('stage') or '').strip().lower() source_type = str(payload.get('source_type') or '').strip().lower() or None @@ -720,38 +747,7 @@ def apply_user_projection_fields( if order_task is not None and not pending_reason: pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None - # ===== [STEP 3] 计算 Retry Decision(仅 notice 真实存在时) ===== - retry_decision: dict | None = None - rd_action: str | None = None - rd_status: str | None = None - rd_retryable: bool = False - rd_reason_code: str | None = None - _RD_NEEDS_HUMAN: str | None = None - _RD_NOOP: str | None = None - _RD_STATUS_RUNNING: str | None = None - _RD_STATUS_NEEDS_HUMAN: str | None = None - _RD_STATUS_COMPLETED: str | None = None - _RD_STATUS_FAILED: str | None = None - if notice is not None: - try: - from app.services.shipping_notice.task_retry_decision_service import ( - decide_retry_action_only, - ACTION_NEEDS_HUMAN as _RD_NEEDS_HUMAN, - ACTION_NOOP as _RD_NOOP, - STATUS_RUNNING as _RD_STATUS_RUNNING, - STATUS_NEEDS_HUMAN as _RD_STATUS_NEEDS_HUMAN, - STATUS_COMPLETED as _RD_STATUS_COMPLETED, - STATUS_FAILED as _RD_STATUS_FAILED, - ) - retry_decision = decide_retry_action_only(notice, scope='task') - except Exception: # noqa: BLE001 - retry_decision = None - rd_action = str((retry_decision or {}).get('action') or '').strip() or None - rd_status = str((retry_decision or {}).get('status') or '').strip() or None - rd_retryable = bool((retry_decision or {}).get('retryable')) - rd_reason_code = str((retry_decision or {}).get('reason_code') or '').strip() or None - - # ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) ===== + # ===== [STEP 3] 按正式 Gate 与领域终态计算 user_status ===== notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else '' from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success @@ -767,11 +763,8 @@ def apply_user_projection_fields( or notice_upload_status in {'uploaded', 'succeeded', 'success'} ) ) - _rd_has_completed_process = verified_upload_success - def _compute_user_status() -> str: - # [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision - # 只描述任务调度,不能覆盖正式 Gate 已到达的 Excel/上传阻断。 + # 当前 Gate 是唯一可执行状态源,不能由旧 Retry Decision 覆盖。 gate_status = str((old_gate or {}).get('status') or '').strip().lower() if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}: return 'retryable' @@ -786,20 +779,7 @@ def apply_user_projection_fields( return 'cancelled' if old_status == 'failed': return 'failed' - # Retry Decision 可得时:优先用决策器 - if retry_decision is not None: - # 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed - if rd_status == _RD_STATUS_COMPLETED and verified_upload_success: - return 'completed' - if rd_action == _RD_NOOP and _rd_has_completed_process: - return 'completed' - # 5) rd_retryable=True → 'retryable'(新增!) - if rd_retryable is True: - return 'retryable' - # 6) rd_status=needs_human 或 rd_action=needs_human → waiting_human - if rd_status == _RD_STATUS_NEEDS_HUMAN or rd_action == _RD_NEEDS_HUMAN: - return 'waiting_human' - # 7) legacy waiting_human 兜底(保留旧逻辑) + # 领域事实仅补充展示状态,不得生成恢复权限。 if old_status in {'waiting_review', 'waiting_inventory_source_review', 'waiting_shortage_review'}: return 'waiting_human' if pending_reason in { @@ -808,12 +788,9 @@ def apply_user_projection_fields( _PROCESS_HUMAN_PENDING_MATCH, } or review_status_raw in {REVIEW_STATUS_SHORTAGE_REVIEW}: return 'waiting_human' - # 8) rd_status=running 或旧 running 族 → running - if retry_decision is not None and rd_status == _RD_STATUS_RUNNING: - return 'running' if old_status in {'processing', 'queued', 'running'}: return 'running' - # 9) 兜底 + # 无法判定时保守显示处理中,不下发动作。 return 'running' user_status = _compute_user_status() @@ -851,8 +828,6 @@ def apply_user_projection_fields( return False if user_status == 'retryable': return True - if user_status == 'failed' and rd_retryable: - return True return False retryable = _compute_retryable() @@ -928,12 +903,6 @@ def apply_user_projection_fields( return None # 2) waiting_human if user_status == 'waiting_human': - if retry_decision is not None and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY: - return { - 'code': rd_reason_code, - 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], - 'details': {}, - } gate_reason = str((old_gate or {}).get('blocking_reason_code') or '').strip() if gate_reason and gate_reason in _REASON_TO_I18N_KEY: return { @@ -948,12 +917,6 @@ def apply_user_projection_fields( return _legacy_waiting_human_blocking_reason() # 3) retryable if user_status == 'retryable': - if rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY: - return { - 'code': rd_reason_code, - 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], - 'details': {}, - } return { 'code': 'technical_failure_present', 'i18n_key': _REASON_TO_I18N_KEY['technical_failure_present'], @@ -961,16 +924,10 @@ def apply_user_projection_fields( } # 4) failed if user_status == 'failed': - if rd_retryable and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY: - return { - 'code': rd_reason_code, - 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], - 'details': {}, - } return { 'code': 'process_failed_terminal', 'i18n_key': _PROCESS_FAILED_I18N, - 'details': {'legacy_status': old_status, 'legacy_stage': old_stage}, + 'details': {'status': old_status, 'stage': old_stage}, } return None @@ -978,7 +935,6 @@ def apply_user_projection_fields( # ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None ===== _ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = { - 'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules', 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', 'retry_inventory_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', @@ -990,7 +946,6 @@ def apply_user_projection_fields( 'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review', } _ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = { - 'retry': 'chat.shippingProcessing.action.retry', 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', 'open_order_review': 'chat.shippingProcessing.action.open_order_review', @@ -1010,15 +965,6 @@ def apply_user_projection_fields( fallback = _ACTION_CODE_TO_CHAT_I18N_FALLBACK.get(action_code) return fallback or f'chat.shippingProcessing.action.{action_code}' - def _legacy_waiting_human_primary_action(bcode: str) -> dict[str, Any] | None: - if bcode in {'inventory_shortage', 'inventory_multi_file_conflict'}: - code = 'open_inventory_match_review' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - if bcode == 'order_review_required': - code = 'open_order_review' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - return None - def _compute_primary_action() -> dict[str, Any] | None: # [BE-10] Gate action 是当前阶段唯一主动作来源;旧 stage 的 # match_inventory/regenerate_excel 仅作兼容回退。 @@ -1026,7 +972,7 @@ def apply_user_projection_fields( gate_action_alias = { 'regenerate_excel_artifact': 'regenerate_excel', }.get(gate_action, gate_action) - if gate_action_alias in SHIPPING_PROCESSING_ACTION_INTENTS and user_status in { + if gate_action_alias and user_status in { 'retryable', 'waiting_human', 'running', }: return { @@ -1037,11 +983,7 @@ def apply_user_projection_fields( # 1) blocking_reason 非 None if blocking_reason is not None: bcode = str(blocking_reason.get('code') or '').strip() - # 1a. retryable 或 failed+retryable → 统一 retry 动作 - if user_status == 'retryable' or (user_status == 'failed' and retryable is True): - code = 'retry' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - # 1b ~ 1h: waiting_human 按 code 分派 + # waiting_human 仅按 Gate/领域阻断映射精确业务入口。 if user_status == 'waiting_human': if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}: code = 'open_inventory_match_review' @@ -1071,27 +1013,7 @@ def apply_user_projection_fields( }: code = 'open_order_review' return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - # 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底 - available_actions = payload.get('available_actions') - if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions: - code = 'reconcile_and_progress' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - # 1i. 其它 unknown:legacy 兜底 - legacy_pa = _legacy_waiting_human_primary_action(bcode) - if legacy_pa is not None: - return legacy_pa - # 2) completed → download_excel(保持 legacy) - if user_status == 'completed': - code = 'download_excel' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - # 3) running 且 stage 匹配 → match_inventory / regenerate_excel(保持 legacy) - if user_status == 'running' and user_stage == 'inventory_match': - code = 'match_inventory' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - if user_status == 'running' and user_stage == 'excel_generate': - code = 'regenerate_excel' - return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} - # 4) 兜底 None + # Gate 未明确授权时不由阶段、状态或旧 actions 补造 CTA。 return None primary_action = _compute_primary_action() diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index 6d23d569..93abf8c2 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -281,12 +281,16 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = ( 'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate', + 'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review', 'upload_inventory_file', 'retry_inventory_preparation', 'retry_inventory_matching', - 'retry', + 'retry_parse', + 'retry_failed_documents', + 'retry_failed_attachments', + 'reparse', 'reparse_batch', 'refresh', 'regenerate_excel', diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index f4115b59..b3e78008 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -1,14 +1,13 @@ """ services/shipping_notice/query_service.py -用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 +用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、 ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、 order_review_projection(任务中心 STP retry 动作投影)。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; - co8 起 shipping_batches 已删除,批次 list API 返回空、按 batch_no 查询返回 None; - tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉; + tools.py 通过 TaskProjection 委托序列化与任务解析,写路径逐步下沉; SUMMARY 经 _enrich_task_center_fields 附带 todo_category / can_handle / ui_state / recent_event, 以及统一 shipping_processing_status / progress_version / order_task_no(BE-02), 并注入 review_run_no 供任务中心深链订单处理工作台(UI-04); @@ -54,7 +53,6 @@ from app.models import ( ShippingTaskEvent, ShippingUploadAttempt, ) -from app.services.shipping_notice.batch_legacy_removed import SHIPPING_BATCHES_REMOVED_MESSAGE from app.services.shipping_notice.constants import ( CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_PARSE_REVIEW, @@ -162,13 +160,6 @@ class TaskProjection(str, Enum): DETAIL = "detail" -class BatchProjection(str, Enum): - """批次读模型投影:工作台全量 / Tool 精简。""" - - SUMMARY = "summary" - TOOL = "tool" - - def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by( @@ -219,25 +210,6 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] } -def _task_batch_no(task: ShippingNotice) -> str | None: - """shipping_batches 已删除;任务不再挂 batch_no。""" - del task - return None - - -def task_sort_key(task: ShippingNotice) -> tuple[int, str]: - """批次内任务排序键:batch_index 优先,其次 created_at。""" - return ( - task.batch_index if task.batch_index is not None else 10**9, - task.created_at.isoformat() if task.created_at else "", - ) - - -def sort_batch_tasks(tasks: list[ShippingNotice]) -> list[ShippingNotice]: - """按 batch_index、created_at 对批次任务列表排序(返回新列表)。""" - return sorted(tasks, key=task_sort_key) - - def get_task_by_ref(task_ref: str) -> ShippingNotice | None: """按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。""" value = str(task_ref or "").strip() @@ -271,12 +243,6 @@ def get_task_by_ref(task_ref: str) -> ShippingNotice | None: return None -def get_batch_by_no(batch_no: str) -> None: - """按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。""" - del batch_no - return None - - def resolve_order_extraction_ui_target( *, user_id: int, @@ -286,15 +252,15 @@ def resolve_order_extraction_ui_target( """ 按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。 - 核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时, - 再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。 + 核心逻辑:沿 Candidate.consumed_task_id 查找当前用户的既有 Task。 + 禁止回退到“用户最近任务”,避免并发会话串单。 Args: user_id: 当前聊天用户 ID。 conversation_id: 当前 HXOPS ChatSession.session_id。 intake_nos: 本轮 agent_runtime_context.refs.intake_nos。 Returns: - `(batch, task)`;新建批次时 batch 非空,只有 open_existing 时 task 非空。 + `(None, task)`;`shipping_batches` 已删除,任务是唯一恢复锚点。 """ normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()}) session_id = str(conversation_id or '').strip() @@ -328,12 +294,6 @@ def resolve_order_extraction_ui_target( return None, task -def get_task_in_batch(batch_no: str, task_no: str) -> ShippingNotice | None: - """查找属于指定批次的任务;shipping_batches 已删除,固定返回 None。""" - del batch_no, task_no - return None - - def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str] | None: """解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。""" if not task or not task.export_file_path: @@ -366,102 +326,6 @@ def task_export_error_message(task: ShippingNotice | None) -> str: return "" -def list_sorted_batch_tasks(batch: Any) -> list[ShippingNotice]: - """shipping_batches 已删除;保留签名供过渡调用方,固定返回空列表。""" - del batch - return [] - - -def list_batch_task_summaries(batch: Any) -> list[dict[str, Any]]: - """shipping_batches 已删除;固定返回空列表。""" - del batch - return [] - - -def compute_batch_process_summary(tasks: list[ShippingNotice]) -> dict[str, int]: - """批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。""" - total = len(tasks) - completed = sum(1 for item in tasks if _is_task_completed(item)) - failed = sum(1 for item in tasks if _is_task_failed(item)) - running = sum(1 for item in tasks if _is_task_active(item)) - pending = max(0, total - completed - failed - running - sum(1 for item in tasks if _is_task_needs_human(item))) - focus = next( - ( - item for item in sort_batch_tasks(tasks) - if not _is_task_completed(item) and not _is_task_failed(item) - ), - None, - ) - return { - "total": total, - "completed": completed, - "failed": failed, - "running": running, - "pending": pending, - "current_index": int(focus.batch_index or 0) if focus else (total if total else 0), - "current_task_no": focus.task_no if focus else None, - } - - -def _is_task_completed(task: ShippingNotice) -> bool: - """判断任务是否已进入完成态,用于会话级聚合统计。""" - upload_status = str(getattr(task, "upload_status", None) or "").strip().lower() - return upload_status in {"uploaded", "succeeded", "success"} or bool( - str(getattr(task, "freight_ref_no", None) or "").strip() - ) - - -def _is_task_failed(task: ShippingNotice) -> bool: - """判断任务是否失败或上传失败,用于会话级异常优先展示。""" - return ( - str(getattr(task, "review_status", None) or "").strip().lower() == "rejected" - or str(getattr(task, "upload_status", None) or "").strip().lower() == "failed" - ) - - -def _is_task_needs_human(task: ShippingNotice) -> bool: - """判断任务是否停在人工门;失败态不重复计入人工门。""" - if _is_task_failed(task) or _is_task_completed(task): - return False - return bool(getattr(task, "review_status", None) or getattr(task, "pending_human_reason", None)) - - -def _is_task_active(task: ShippingNotice) -> bool: - """判断任务是否仍处于自动执行或等待外部系统返回的状态。""" - if _is_task_completed(task) or _is_task_failed(task) or _is_task_needs_human(task): - return False - lifecycle = str(getattr(task, "lifecycle_status", "active") or "active").strip().lower() - if lifecycle != "active": - return False - return bool( - getattr(task, "current_step", None) - or getattr(task, "inventory_snapshot_id", None) - or getattr(task, "export_file_path", None) - or getattr(task, "upload_status", None) - ) - - -def compute_conversation_workspace_summary(batches: list[Any]) -> dict[str, int]: - """按会话聚合多个批次的状态计数,供 Agent 会话级工作台展示。""" - tasks: list[ShippingNotice] = [] - for batch in batches: - tasks.extend(list(getattr(batch, "tasks", None) or [])) - completed = sum(1 for task in tasks if _is_task_completed(task)) - failed = sum(1 for task in tasks if _is_task_failed(task)) - needs_human = sum(1 for task in tasks if _is_task_needs_human(task)) - running = sum(1 for task in tasks if _is_task_active(task)) - pending = max(0, len(tasks) - completed - failed - needs_human - running) - return { - "batch_count": len(batches), - "total": len(tasks), - "completed": completed, - "running": running, - "failed": failed, - "needs_human": needs_human, - "pending": pending, - } - - def extract_task_no_from_text(text: str) -> str | None: """从自然语言文本中提取 SN 技术号或客户业务号。""" raw = str(text or "") @@ -674,12 +538,9 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "shipping_case_id": task.shipping_case_id, "case_no": task.shipping_case.case_no if task.shipping_case else None, "business_no": task.shipping_case.business_no if task.shipping_case else None, - "batch_no": _task_batch_no(task), "source_type": task.source_type, "source_file_name": task.source_file_name, "source_file_type": task.source_file_type, - "batch_index": task.batch_index, - "batch_total": task.batch_total, "customer_name": header.get('customer_name') or header.get('bill_to_customer'), "customer_resolution_status": task.customer_resolution_status, "customer_resolution_method": task.customer_resolution_method, @@ -790,41 +651,6 @@ def serialize_task_for_tool(task: ShippingNotice) -> dict[str, Any]: return serialize_task(task, TaskProjection.TOOL) -def serialize_batch(batch: Any, projection: BatchProjection) -> dict[str, Any]: - """shipping_batches 已删除;禁止序列化批次对象。""" - del batch, projection - raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE) - - -def serialize_batch_for_tool(batch: Any | None) -> dict[str, Any] | None: - """Tool 批次 data 投影;shipping_batches 已删除。""" - del batch - return None - - -def serialize_batch_summary(batch: Any) -> dict[str, Any]: - """shipping_batches 已删除;禁止序列化批次摘要。""" - del batch - raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE) - - -def serialize_conversation_batch_workspace(batch: Any) -> dict[str, Any]: - """shipping_batches 已删除;禁止构建会话批次工作台。""" - del batch - raise ValidationError(SHIPPING_BATCHES_REMOVED_MESSAGE) - - -def get_conversation_batch_workspace(conversation_id: str, user_id: int) -> dict[str, Any]: - """返回一个 Agent 会话下用户可见的所有发货批次与聚合摘要(co8 起固定空集)。""" - value = str(conversation_id or "").strip() - del user_id - return { - "conversation_id": value, - "summary": compute_conversation_workspace_summary([]), - "batches": [], - } - - def task_todo_category(task: ShippingNotice) -> str: """ 由 checkpoint_kind + 复核检查点推导待办分类(服务端唯一口径)。 @@ -1112,46 +938,15 @@ def serialize_task_detail( ) -def get_batch_for_user(batch_no: str, user_id: int) -> None: - """按 batch_no 查找批次;shipping_batches 已删除,固定返回 None。""" - del batch_no, user_id - return None - - -def list_batches_for_user( - user_id: int, - *, - limit: int = 100, -) -> list[dict[str, Any]]: - """列出用户可见批次摘要;shipping_batches 已删除,固定返回空列表。""" - del user_id, limit - return [] - - -def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]: - """列出批次下任务;shipping_batches 已删除,固定返回空列表。""" - del batch_no, user_id - return [] - - -def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingNotice | None: - """获取批次 focus 任务;shipping_batches 已删除,固定返回 None。""" - del batch_no, user_id - return None - - def list_tasks_for_user( user_id: int, *, - batch_no: str | None = None, limit: int = 100, ) -> list[dict[str, Any]]: - """列出用户可见任务摘要,可按批次或工作台用户态状态过滤。""" + """列出用户可见任务摘要。""" q = ShippingNotice.query.filter( (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) ) - if batch_no: - return [] rows = q.order_by(desc(ShippingNotice.created_at)).limit(max(1, min(limit, 500))).all() return [ serialize_task_summary(c, viewer_user_id=user_id) @@ -1164,7 +959,6 @@ def list_tasks_page_for_user( *, page: int = 1, page_size: int = 20, - batch_no: str | None = None, lifecycle_status: str | None = None, ) -> dict[str, Any]: """ @@ -1178,8 +972,6 @@ def list_tasks_page_for_user( q = ShippingNotice.query.filter( (ShippingNotice.user_id == user_id) | (ShippingNotice.user_id.is_(None)) ) - if batch_no: - return {"items": [], "page": normalized_page, "page_size": normalized_page_size, "total": 0} if lifecycle_status: normalized_lifecycle = str(lifecycle_status).strip().lower() if normalized_lifecycle == 'deleted': diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 63c3bf20..e96d7a99 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -36,7 +36,6 @@ def enqueue_shipping_notice_job( *, task_no: str, created_by_id: int | None = None, - batch_no: str | None = None, commit: bool = True, ) -> tuple[bool, str]: """ @@ -48,7 +47,6 @@ def enqueue_shipping_notice_job( Args: task_no: 发货任务号。 created_by_id: 创建人。 - batch_no: 可选批次号。 commit: False 时与业务同事务提交;此时 sync 模式返回 queued_sync_pending:。 Returns: @@ -63,7 +61,6 @@ def enqueue_shipping_notice_job( JobType.SHIPPING_NOTICE_RUN, { 'task_no': normalized_task_no, - 'batch_no': str(batch_no or '').strip().upper() or None, }, domain=SHIPPING_NOTICE_JOB_DOMAIN, business_ref=normalized_task_no, @@ -124,7 +121,6 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: JobType.SHIPPING_NOTICE_RUN, { 'task_no': task_no, - 'batch_no': (job.payload_json or {}).get('batch_no') if job and job.payload_json else None, }, domain=SHIPPING_NOTICE_JOB_DOMAIN, business_ref=task_no, @@ -225,7 +221,6 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_PROCESS_GATE, JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS, - JobType.SHIPPING_AUTO_PROGRESS, JobType.SHIPPING_PDF_AUTOMARK, JobType.SHIPPING_STP_AUTO_CREATE, JobType.SHIPPING_LINE_AUTO_FULFILL, diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index e4ee45c6..9f741b0f 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -566,12 +566,20 @@ def _project_case_formal_gate_summary( # 纯投影契约测试与离线诊断没有 Flask application context;此时没有可读 # 的持久化 Execution,保持原有 Case 派生事实即可。 return None + from app import db + + cache = db.session.info.get('shipping_conversation_projection_read_cache') execution = ( - ShippingProcessExecution.query.filter_by(review_case_id=int(case_id)) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() + cache.get('execution_by_case_id', {}).get(int(case_id)) + if isinstance(cache, dict) else None ) + if execution is None: + execution = ( + ShippingProcessExecution.query.filter_by(review_case_id=int(case_id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) if execution is None: return None from app.services.shipping_notice.process_gate_projection import project_user_gate_summary @@ -588,8 +596,8 @@ def _project_case_formal_gate_facts( 将正式 Gate 摘要归一化为 Case bundle 的三项用户事实。 正式 Execution 存在时,Gate 事实必须覆盖 Case 的历史阻断: - 只有已入队/运行或等待外部回执才表示系统正在推进;建单前的订单冻结 - 校验仍需用户从编辑区提交,不能因 ``pending`` 误显示为系统处理中。 + 已落库的正式 Gate 表示流程已进入该节点;建单前的订单冻结校验仍需用户 + 从编辑区提交,是唯一不能因 ``pending`` 显示为系统处理中的例外。 """ if not isinstance(summary, dict): return None @@ -634,10 +642,10 @@ def _project_case_formal_gate_facts( blocking_reason = BlockingReason(code=None, i18n_key=None, details=None) user_status: UserStatus = 'running' elif gate_status == 'pending': - # pending 仅表示尚未进入该 Gate,不能伪装为系统已在推进。保留当前 - # Case 的可编辑 idle 语义,直到 Gate 实际入队或运行。 + # Execution 已持久化后 pending 是该 Gate 的初始系统推进态;不能回退到 + # Case 草稿的 idle 语义,否则五阶段会把已进入下游节点的文件错误标为空闲。 blocking_reason = BlockingReason(code=None, i18n_key=None, details=None) - user_status = 'idle' + user_status = 'running' elif gate_status == 'blocked_manual': user_status: UserStatus = 'waiting_human' elif gate_status in {'blocked_retryable', 'invalidated'}: @@ -805,24 +813,24 @@ def project_case_primary_action( return {'code': 'open_order_review', 'variant': 'warning', 'label_key': 'shipping.actions.open_order_review'} - # 1f: 草稿编辑和保存校验分别属于主编辑区与底栏,不得升级为当前任务 CTA。 - if user_status == 'waiting_human': - return None - - # 1g: idle → 有 create_draft 优先(首次打开草稿面板 CTA) - if user_status == 'idle': + # 1f: 已授权草稿操作是文件列表的下一项业务操作。点击只导航到该文件的 + # 复核上下文;validate 仍由工作台底栏执行,不能提升为列表 CTA。 + if user_status in {'waiting_human', 'idle'}: if 'create_draft' in actions: - return None + return {'code': 'create_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft'} if 'edit_draft' in actions: - return None + return {'code': 'edit_draft', 'variant': 'primary', + 'label_key': 'shipping.actions.edit_draft'} - # 1h: running/queued → 次优先 view(但 edit_draft 仍然允许) + # 1g: running/queued → 次优先 view(但 edit_draft 仍然允许) if user_status == 'running' and 'edit_draft' in actions: return None - # 1i: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个命中的动作码 + # 1h: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个业务动作;view 是只读 + # 查询能力,阶段导航由五阶段入口承担,不能伪装成文件当前业务 CTA。 for code in _PRIMARY_ACTION_ORDER: - if code in {'edit_draft', 'create_draft', 'validate'}: + if code in {'edit_draft', 'create_draft', 'validate', 'view'}: continue if code in actions: variant = 'default' @@ -913,31 +921,46 @@ def _project_fine_grained_pre_stp_blocking( _latest_not_blocking = True if run_no and document_id is not None and draft_version is not None: business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:" + cache = db.session.info.get('shipping_conversation_projection_read_cache') + prefix_jobs = ( + cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, []) + if isinstance(cache, dict) else None + ) active_job = ( - db.session.query(Job) - .filter( - Job.domain == 'shipping_notice', - Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, - Job.status.in_(('queued', 'running')), - Job.business_ref.like(f"{business_ref_prefix}%"), + next( + (job for job in prefix_jobs if str(job.status or '').strip().lower() in {'queued', 'running'}), + None, + ) if prefix_jobs is not None else ( + db.session.query(Job) + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.status.in_(('queued', 'running')), + Job.business_ref.like(f"{business_ref_prefix}%"), + ) + .order_by(Job.id.desc()) + .first() ) - .order_by(Job.id.desc()) - .first() ) _no_active_job = active_job is None if not _no_active_job: pass else: latest_failed = ( - db.session.query(Job) - .filter( - Job.domain == 'shipping_notice', - Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, - Job.status.in_(('failed', 'dead')), - Job.business_ref.like(f"{business_ref_prefix}%"), + next( + (job for job in prefix_jobs if str(job.status or '').strip().lower() in {'failed', 'dead'}), + None, + ) if prefix_jobs is not None else ( + db.session.query(Job) + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.status.in_(('failed', 'dead')), + Job.business_ref.like(f"{business_ref_prefix}%"), + ) + .order_by(Job.id.desc()) + .first() ) - .order_by(Job.id.desc()) - .first() ) if latest_failed is not None: rj = ( @@ -1036,16 +1059,24 @@ def _project_fine_grained_pre_stp_blocking( queued_job = None if run_no and document_id is not None and draft_version is not None: business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:" + cache = db.session.info.get('shipping_conversation_projection_read_cache') + prefix_jobs = ( + cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, []) + if isinstance(cache, dict) else None + ) queued_job = ( - db.session.query(Job) - .filter( - Job.domain == 'shipping_notice', - Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, - Job.status == 'queued', - Job.business_ref.like(f"{business_ref_prefix}%"), + next((job for job in prefix_jobs if str(job.status or '').strip().lower() == 'queued'), None) + if prefix_jobs is not None else ( + db.session.query(Job) + .filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.status == 'queued', + Job.business_ref.like(f"{business_ref_prefix}%"), + ) + .order_by(Job.id.desc()) + .first() ) - .order_by(Job.id.desc()) - .first() ) _worker_unavailable_hit = False diff --git a/backend/app/services/shipping_notice/reconciliation_service.py b/backend/app/services/shipping_notice/reconciliation_service.py index 84259674..f0da259f 100644 --- a/backend/app/services/shipping_notice/reconciliation_service.py +++ b/backend/app/services/shipping_notice/reconciliation_service.py @@ -426,13 +426,11 @@ def reconcile_and_progress( expected_case_version: int | None = None, source_content_hash: str | None = None, is_admin: bool = False, - legacy_job_id: int | None = None, - replay_mode: bool = False, ) -> ReconcileProgressResult: """ 统一对账恢复总入口(Q6 reconcile-and-progress API 委托本函数)。 - 【AI 触发时机】:用户点击「处理重复任务」走自动化恢复、或历史 Job 928/929 的 - 受权限控制的管理入口、或前端 duplicate_decision_required 裁决后调用。 + 【AI 触发时机】:用户点击「处理重复任务」走自动化恢复,或前端 + duplicate_decision_required 裁决后调用。 核心执行顺序(Q11 短事务锁 + Q1 五级归属 + Q3 复用 Candidate 裁决 + Q2 写回绑定): 1. 加载 Case(FOR UPDATE 短锁);查可见性;构建 request_snapshot(参数一致性校验) @@ -447,14 +445,9 @@ def reconcile_and_progress( 5. 写审计(fulfillment_audit + CaseEvent 幂等持久化) 6. commit 后触发 auto-progress post-commit 钩子 - Phase 4-1 管理端扩展: - • legacy_job_id(int):历史 STP Job 928/929 锚点。管理员仅;必须真实、 - 必须 domain=shipping_notice、必须 status in {failed, dead}。 - • replay_mode(bool):允许 legacy_job_id.reference_key != case_no。 - 默认 false(防跨 Case 错挂)。 - • BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计 - → 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY, - 否则返回 outcome=ownership_anomaly_rejected。 + BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计 + → 归属异常统一抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY, + 否则返回 outcome=ownership_anomaly_rejected。 Args: user_id: 操作人。 @@ -464,8 +457,6 @@ def reconcile_and_progress( expected_case_version: 前端传来的草稿版本(过期抛 409 VERSION_CONFLICT)。 source_content_hash: 请求快照指纹(用于参数一致性比对)。 is_admin: 是否管理员(force_create 受权限控制)。 - legacy_job_id: Phase 4 —— 历史 928/929 Job 锚点(管理员专用)。 - replay_mode: Phase 4 —— 允许跨 case_no 重放 legacy_job(管理员专用)。 Returns: ReconcileProgressResult(公开响应 to_public() 方法)。 @@ -493,61 +484,6 @@ def reconcile_and_progress( details={'allowed': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']}, ) - # [Phase 4 PRE-CHECK-A] replay_mode / legacy_job_id → 必须 admin - if replay_mode and not is_admin: - raise ValidationError( - 'replay_mode requires admin', - code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED', - details={'legacy_job_id': legacy_job_id, 'replay_mode': replay_mode}, - ) - if legacy_job_id is not None and not is_admin: - raise ValidationError( - 'legacy_job_id requires admin', - code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED', - details={'legacy_job_id': legacy_job_id}, - ) - # [Phase 4 PRE-CHECK-B] legacy_job_id 真实性、失败态、domain、reference 对齐 - _legacy_job = None - if legacy_job_id is not None: - from app.models import Job, JobType - _legacy_job = db.session.get(Job, int(legacy_job_id)) - if _legacy_job is None: - raise ValidationError( - f'legacy_job_id not found: {legacy_job_id}', - code='SHIPPING.REVIEW_CASE_NOT_FOUND', - details={'legacy_job_id': legacy_job_id}, - ) - if str(_legacy_job.domain or '').strip() != 'shipping_notice': - raise ValidationError( - 'legacy_job must be shipping_notice domain', - code='SHIPPING.RECONCILE_INVALID_USER_ACTION', - details={'legacy_job_id': legacy_job_id, 'domain': str(getattr(_legacy_job, 'domain', None) or '')}, - ) - if str(getattr(_legacy_job, 'job_type', None) or '') not in { - JobType.SHIPPING_STP_AUTO_CREATE.value, - str(JobType.SHIPPING_STP_AUTO_CREATE.value), - 'shipping_stp_auto_create', - }: - # 放宽兼容:允许 SHIPPING_STP_AUTO_CREATE,其它 928/929 类型 fail-closed - pass - if str(_legacy_job.status or '').strip().lower() not in {'failed', 'dead'}: - raise ValidationError( - f'legacy_job must be failed/dead to replay (current status={_legacy_job.status})', - code='SHIPPING.RECONCILE_INVALID_USER_ACTION', - details={'legacy_job_id': legacy_job_id, 'legacy_status': str(_legacy_job.status or '')}, - ) - if str(_legacy_job.reference_key or '') != str(case_no).strip() and not replay_mode: - raise ValidationError( - 'legacy_job.reference_key mismatches case_no; enable replay_mode to override', - code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT', - details={ - 'legacy_job_id': legacy_job_id, - 'legacy_reference_key': str(_legacy_job.reference_key or ''), - 'case_no': str(case_no).strip(), - 'replay_mode_required': True, - }, - ) - # [STEP 1] 加载 Case + 权限校验(短事务内 FOR UPDATE,Q11) from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user @@ -579,12 +515,6 @@ def reconcile_and_progress( 'contract_version': RECOVERY_CONTRACT_VERSION, 'owner_user_id': int(case.owner_user_id), 'document_id': int(case.document_id), - # Phase 4:将 legacy_job 纳入幂等键与审计链,保证 replay/同 operation 不被 Q7 误回返 - 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), - 'replay_mode': bool(replay_mode), - 'legacy_job_reference_key': ( - str(_legacy_job.reference_key or '') if _legacy_job is not None else None - ), } # [STEP 2] Q7 幂等校验(返回同 operation_id 第一次结果或抛 409) @@ -757,8 +687,6 @@ def reconcile_and_progress( 'match_level_steps': match_result.get('match_level_steps'), 'user_action': user_action, 'case_version': case_ver, - 'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None), - 'replay_mode': bool(replay_mode), } record_fulfillment_audit( user_id=int(user_id) if user else None, diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index e35af0b9..efd049fe 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -1,7 +1,7 @@ """ backend/app/services/shipping_notice/reference_context.py -用途:从发货通知批次/任务/事件构建 shipping_notice 专用 reference_context。 +用途:从发货通知任务/事件构建 shipping_notice 专用 reference_context。 依赖:models.ShippingNotice/ShippingTaskEvent、agent_runtime_context.reference。 逻辑:runtime_context 在调用 Dify 前经本模块提炼当前 focus、最近动作、最近失败和候选对象,避免把全量事件流水直接暴露给 Runtime。 """ @@ -59,7 +59,7 @@ def _task_recency_key(task: ShippingNotice) -> tuple[datetime, int]: return updated_at, int(getattr(task, "id", 0) or 0) -def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) -> list[ShippingNotice]: +def _collect_focus_task(focus_task: ShippingNotice | None) -> list[ShippingNotice]: """ 汇总当前 reference_context 可见的任务集合。 @@ -72,9 +72,9 @@ def _collect_batch_tasks(batch: Any | None, focus_task: ShippingNotice | None) - def _recent_events(tasks: list[ShippingNotice]) -> list[ShippingTaskEvent]: """ - 查询最近关键事件。 + 查询当前任务最近关键事件。 - 核心逻辑:只取当前批次/任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。 + 核心逻辑:只取当前任务的最近少量事件,用于推断最后动作,不把全量事件流水塞进上下文。 """ task_ids = [int(task.id) for task in tasks if getattr(task, "id", None) is not None] if not task_ids: @@ -210,7 +210,6 @@ def _candidate_refs(tasks: list[ShippingNotice], focus_task_no: str) -> list[dic def _build_recent_activity_summary( *, - batch: Any | None, focus_task_no: str, last_action_summary: str, last_failed_summary: str, @@ -226,8 +225,6 @@ def _build_recent_activity_summary( pieces.append(last_action_summary) if focus_task_no: pieces.append(f"当前 focus 为 {focus_task_no}") - elif _clean_text(getattr(batch, "batch_no", None)): - pieces.append(f"当前批次为 {_clean_text(batch.batch_no).upper()}") if last_failed_summary: pieces.append(last_failed_summary) if len(candidates) > 1: @@ -243,7 +240,6 @@ def _build_recent_activity_summary( def build_shipping_reference_context( *, - batch: Any | None, focus_task: ShippingNotice | None, ) -> dict[str, Any]: """ @@ -252,20 +248,17 @@ def build_shipping_reference_context( 【AI 触发时机】:当用户在 HXOPS 已做确认、重匹配、切票等动作后,又在对话里说“继续”“刚才那个”“上一个失败的”时, Dify 需要优先读取这份上下文理解当前现场,但不能直接据此推进业务状态。 - 核心逻辑:读取 batch.current_focus_task_no、任务状态和最近少量事件,提炼 focus_object / last_action_target / + 核心逻辑:读取当前任务状态和最近少量事件,提炼 focus_object / last_action_target / last_failed_target / candidates / recent_activity_summary 五类短期线索;不输出全量任务详情或完整事件日志。 Args: - batch: 当前批次;可为空。 focus_task: 当前焦点任务;可为空。 Returns: shipping_notice 领域的 reference_context;没有有效线索时返回空 dict。 """ - tasks = _collect_batch_tasks(batch, focus_task) + tasks = _collect_focus_task(focus_task) focus_task_no = _task_no(focus_task) - if not focus_task_no and batch and _clean_text(getattr(batch, "current_focus_task_no", None)): - focus_task_no = _clean_text(batch.current_focus_task_no).upper() if not tasks and not focus_task_no: return {} @@ -278,7 +271,6 @@ def build_shipping_reference_context( focus_object = build_object_ref("task", focus_task_no) if focus_task_no else {} recent_activity_summary = _build_recent_activity_summary( - batch=batch, focus_task_no=focus_task_no, last_action_summary=last_action_summary, last_failed_summary=last_failed_summary, diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index d9c1466e..7c1d1a03 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -34,20 +34,6 @@ def _clean_text(value: Any) -> str: return str(value or "").strip() -def _batch_no(batch: Any | None, task: ShippingNotice | None) -> str: - """ - 获取当前上下文的批次号。 - - 核心逻辑:shipping_batches 已删除;仅保留显式传入 batch 对象的兼容读取。 - - Returns: - 批次号;无法识别时返回空字符串。 - """ - if batch and _clean_text(getattr(batch, "batch_no", None)): - return _clean_text(batch.batch_no).upper() - return "" - - def _task_no(task: ShippingNotice | None) -> str: """ 获取当前上下文的任务号。 @@ -66,7 +52,6 @@ def _task_no(task: ShippingNotice | None) -> str: def _build_refs( *, task: ShippingNotice | None, - batch: Any | None, run_purpose: str | None, intake_nos: list[str] | None = None, capability: str | None = None, @@ -76,11 +61,10 @@ def _build_refs( """ 构建新版 agent_runtime_context.refs。 - 核心逻辑:使用稳定业务字段名 task_no/batch_no/run_purpose/file_name,区别于旧 hxops_context 的 task/batch。 + 核心逻辑:使用稳定业务字段名 task_no/run_purpose/file_name。 Args: task: 当前任务。 - batch: 当前批次。 run_purpose: 本次 Dify run 的目的。 intake_nos: 点击发送时锁定的 Intake 编号集合。 capability: 当前固定画布能力,如 order_extraction。 @@ -90,13 +74,10 @@ def _build_refs( """ refs: dict[str, str] = {} task_no = _task_no(task) - batch_no = _batch_no(batch, task) file_name = _clean_text(getattr(task, "source_file_name", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: refs["task_no"] = task_no - if batch_no: - refs["batch_no"] = batch_no if normalized_run_purpose: refs["run_purpose"] = normalized_run_purpose if file_name: @@ -115,7 +96,7 @@ def _build_refs( return refs -def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[str, Any]: +def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: """ 构建发货通知运行态提示。 @@ -123,7 +104,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st Args: task: 当前任务。 - batch: 当前批次。 Returns: 状态提示字典。 @@ -132,8 +112,6 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st task_no = _task_no(task) if task_no: state_hint["focus_task_no"] = task_no - elif batch and _clean_text(getattr(batch, "current_focus_task_no", None)): - state_hint["focus_task_no"] = _clean_text(batch.current_focus_task_no).upper() if task is not None: for attr, key in ( @@ -147,26 +125,21 @@ def _build_state_hint(task: ShippingNotice | None, batch: Any | None) -> dict[st if value: state_hint[key] = value - batch_no = _batch_no(batch, task) - if batch_no: - state_hint["batch_no"] = batch_no return state_hint def _build_summary( *, task: ShippingNotice | None, - batch: Any | None, run_purpose: str | None, ) -> str: """ 构建给 Dify 阅读的短摘要。 - 核心逻辑:用自然语言说明当前 run 的任务、批次、文件和状态,避免 Dify 依赖 conversation memory 猜现场。 + 核心逻辑:用自然语言说明当前 run 的任务、文件和状态,避免 Dify 依赖 conversation memory 猜现场。 Args: task: 当前任务。 - batch: 当前批次。 run_purpose: 本次 Dify run 的目的。 Returns: @@ -174,14 +147,11 @@ def _build_summary( """ pieces: list[str] = [] task_no = _task_no(task) - batch_no = _batch_no(batch, task) file_name = _clean_text(getattr(task, "source_file_name", None)) current_step = _clean_text(getattr(task, "current_step", None)) normalized_run_purpose = _clean_text(run_purpose) if task_no: pieces.append(f"当前任务 {task_no}") - if batch_no: - pieces.append(f"属于批次 {batch_no}") if file_name: pieces.append(f"来源文件 {file_name}") if normalized_run_purpose: @@ -189,7 +159,7 @@ def _build_summary( if current_step: pieces.append(f"当前步骤 {current_step}") if not pieces: - return "当前为货代发货通知 Agent 会话,尚未解析出明确任务或批次锚点。" + return "当前为货代发货通知 Agent 会话,尚未解析出明确任务锚点。" return ",".join(pieces) + "。" @@ -197,7 +167,6 @@ def build_shipping_runtime_context( *, session_id: str, task: ShippingNotice | None = None, - batch: Any | None = None, trigger_source: str | None = None, request_id: str | None = None, locale: str | None = None, @@ -211,13 +180,12 @@ def build_shipping_runtime_context( """ 构建货代发货通知 Agent 的 agent_runtime_context。 - 核心逻辑:以 HXOPS DB 中的 task/batch 为事实源,生成 refs/domain.state_hint/reference_context snapshot, + 核心逻辑:以 HXOPS DB 中的 task 为事实源,生成 refs/domain.state_hint/reference_context snapshot, 供 Dify 每次 run 显式识别现场。 Args: session_id: HXOPS 本地 ChatSession.session_id。 task: 当前显式任务;禁止在本函数内按会话猜测。 - batch: 当前批次。 trigger_source: 触发来源,如 frontend_chat/backend_orchestrator。 request_id: 本次请求 ID。 locale: 用户语言。 @@ -233,14 +201,11 @@ def build_shipping_runtime_context( """ domain = { "type": SHIPPING_NOTICE_AGENT_CODE, - "summary": _build_summary(task=task, batch=batch, run_purpose=run_purpose), - "state_hint": _build_state_hint(task, batch), + "summary": _build_summary(task=task, run_purpose=run_purpose), + "state_hint": _build_state_hint(task), "available_actions_hint": [], } - reference_context = build_shipping_reference_context( - batch=batch, - focus_task=task, - ) + reference_context = build_shipping_reference_context(focus_task=task) return build_agent_runtime_context( agent_code=SHIPPING_NOTICE_AGENT_CODE, scope=scope, @@ -250,7 +215,6 @@ def build_shipping_runtime_context( locale=locale, refs=_build_refs( task=task, - batch=batch, run_purpose=run_purpose, intake_nos=intake_nos, capability=capability, diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 9b2d4b09..66b14348 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -14,29 +14,39 @@ services/shipping_notice/shipping_processing_projection.py 写入 stage_nodes 与 available_actions;stage/status 以 OT 已写入值为准(BE-07,禁止 Notice 覆盖); 已挂正式 Notice 时 stage/stage_label_key 与 Case.current_stage 同源(project_stage_for_task); **只读加载**已有 shipping_order_tasks(禁止 GET 路径 upsert);已建 Notice 时填 shipping_notice_no; - work_items 构建后由 _conversation_processing_from_work_items 重建兼容 conversation_processing; + work_items 构建后由 _conversation_processing_from_work_items 构建正式 conversation_processing; 不投影会话级批量恢复动作;失败必须由用户在当前 Gate 选择具体动作。 """ from __future__ import annotations import logging +from dataclasses import dataclass from datetime import datetime from typing import Any +from sqlalchemy.orm import load_only, selectinload + from app import db from app.core.errors import NotFoundError, ValidationError from app.models import ( FileAsset, + Job, ShippingNotice, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderProcessingRun, ShippingOrderProcessingRunIntake, + ShippingOrderProcessingPlan, ShippingOrderProcessingUnit, ShippingOrderReviewCase, + ShippingOrderReviewDraft, ShippingOrderReviewStream, + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, + ShippingProcessRecoveryPlan, ShippingOrderSubmission, ShippingOrderTask, ) @@ -48,6 +58,9 @@ from app.services.shipping_notice.processing_projection_invariants import ( from app.services.shipping_notice.processing_ownership import ( record_projection_inconsistency_audit, ) +from app.services.shipping_notice.reconciliation_projector import ( + project_case_primary_action, +) from app.services.shipping_notice.lifecycle_projection import ( LIFECYCLE_STAGE_CODES, project_lifecycle, @@ -63,6 +76,269 @@ from app.services.shipping_notice.progress_audit_contract import ( logger = logging.getLogger(__name__) + +@dataclass(frozen=True) +class _ConversationProjectionLoadContext: + """会话投影的一次性只读预取结果,避免 EML 附件按 Intake 重复查询。""" + + documents_by_intake_id: dict[int, list[ShippingOrderDocument]] + intakes_by_no: dict[str, ShippingOrderIntake] + prefetched_gate_attempts: list[ShippingProcessGateAttempt] + read_cache: dict[str, Any] + + +_CONVERSATION_PROJECTION_READ_CACHE_KEY = 'shipping_conversation_projection_read_cache' + + +def _conversation_projection_read_cache() -> dict[str, Any] | None: + """返回当前会话投影的临时只读缓存;单项投影不启用该缓存。""" + cached = db.session.info.get(_CONVERSATION_PROJECTION_READ_CACHE_KEY) + return cached if isinstance(cached, dict) else None + + +def _conversation_projection_load_context( + intakes: list[ShippingOrderIntake], +) -> _ConversationProjectionLoadContext: + """批量加载会话 Intake 的业务附件,供同一请求内所有 EML 聚合复用。""" + intake_ids = [int(intake.id) for intake in intakes] + documents_by_intake_id: dict[int, list[ShippingOrderDocument]] = { + intake_id: [] for intake_id in intake_ids + } + if intake_ids: + documents = ( + ShippingOrderDocument.query.filter( + ShippingOrderDocument.intake_id.in_(intake_ids), + ShippingOrderDocument.document_type != 'email_body', + ) + .order_by( + ShippingOrderDocument.intake_id.asc(), + ShippingOrderDocument.id.asc(), + ) + .all() + ) + for document in documents: + documents_by_intake_id.setdefault(int(document.intake_id), []).append(document) + document_ids = [ + int(document.id) + for documents in documents_by_intake_id.values() + for document in documents + ] + prefetched_gate_attempts: list[ShippingProcessGateAttempt] = [] + read_cache: dict[str, Any] = { + 'current_case_by_document_id': {}, + 'run_links_by_intake_id': {}, + 'runs_by_id': {}, + 'stp_jobs_by_ref': {}, + 'stp_jobs_by_prefix': {}, + 'execution_by_case_id': {}, + 'gates_by_execution_id': {}, + 'latest_attempt_by_id': {}, + 'active_recovery_plans_by_execution_id': {}, + 'parse_jobs_by_id': {}, + 'candidate_count_by_intake_id': {}, + 'candidate_by_id': {}, + 'reparseable_batch_by_run_id': {}, + 'reparseable_batch_for_conversation': None, + } + if document_ids: + cases = ( + ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.document_id.in_(document_ids), + ) + .options( + selectinload(ShippingOrderReviewCase.current_draft), + selectinload(ShippingOrderReviewCase.run).selectinload( + ShippingOrderProcessingRun.extraction_plan, + ).selectinload(ShippingOrderProcessingPlan.units), + ) + .all() + ) + case_ids = [int(case.id) for case in cases] + current_case_ids = { + int(case_id) + for (case_id,) in db.session.query( + ShippingOrderReviewStream.current_case_id, + ).filter( + ShippingOrderReviewStream.document_id.in_(document_ids), + ShippingOrderReviewStream.current_case_id.isnot(None), + ).all() + } + read_cache['current_case_by_document_id'] = { + int(case.document_id): case + for case in cases + if int(case.id) in current_case_ids + } + for case in cases: + if case.run is not None: + read_cache['runs_by_id'][int(case.run.id)] = case.run + if case_ids: + executions = ( + ShippingProcessExecution.query.filter( + ShippingProcessExecution.review_case_id.in_(case_ids), + ShippingProcessExecution.status != 'superseded', + ) + .order_by(ShippingProcessExecution.id.desc()) + .options(selectinload(ShippingProcessExecution.gates).selectinload( + ShippingProcessGate.attempts, + )) + .all() + ) + for execution in executions: + read_cache['execution_by_case_id'].setdefault( + int(execution.review_case_id), execution, + ) + read_cache['gates_by_execution_id'][int(execution.id)] = list( + getattr(execution, 'gates', []) or [], + ) + execution_ids = [int(execution.id) for execution in executions] + if execution_ids: + latest_attempt_ids = [ + int(attempt_id) + for (attempt_id,) in db.session.query( + ShippingProcessGate.latest_attempt_id, + ).filter( + ShippingProcessGate.execution_id.in_(execution_ids), + ShippingProcessGate.latest_attempt_id.isnot(None), + ).all() + ] + if latest_attempt_ids: + # serialize_process_gate 使用 session.get(latest_attempt_id)。保留这些 + # 实体引用可使同一次投影命中 identity map,避免每个 Gate 再查一次。 + prefetched_gate_attempts = ShippingProcessGateAttempt.query.filter( + ShippingProcessGateAttempt.id.in_(latest_attempt_ids), + ).all() + read_cache['latest_attempt_by_id'] = { + int(attempt.id): attempt for attempt in prefetched_gate_attempts + } + recovery_plans = ShippingProcessRecoveryPlan.query.filter( + ShippingProcessRecoveryPlan.execution_id.in_(execution_ids), + ShippingProcessRecoveryPlan.status.in_({ + 'planned', 'invalidating', 'queued', 'running', + 'waiting_external', 'waiting_manual', + }), + ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() + for plan in recovery_plans: + read_cache['active_recovery_plans_by_execution_id'].setdefault( + int(plan.execution_id), [], + ).append(plan) + # 读取所有当前 Case 的 STP Job 一次;后续 Case bundle 以幂等键从缓存裁决。 + stp_prefixes = { + f"stp-auto:{case.run.run_no}:doc-{int(case.document_id)}:" + for case in cases + if case.run is not None and case.document_id is not None + } + if stp_prefixes: + from sqlalchemy import or_ + from app.jobs.types import JobType + + jobs = Job.query.filter( + Job.domain == 'shipping_notice', + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + or_(*(Job.business_ref.like(f'{prefix}%') for prefix in stp_prefixes)), + ).order_by(Job.id.desc()).all() + for job in jobs: + ref = str(job.business_ref or '').strip() + read_cache['stp_jobs_by_ref'].setdefault(ref, []).append(job) + prefix = next((item for item in stp_prefixes if ref.startswith(item)), None) + if prefix: + read_cache['stp_jobs_by_prefix'].setdefault(prefix, []).append(job) + if intake_ids: + asset_ids = [int(intake.asset_id) for intake in intakes if intake.asset_id] + if asset_ids: + FileAsset.query.filter(FileAsset.id.in_(asset_ids)).all() + parse_job_ids = [int(intake.parse_job_id) for intake in intakes if intake.parse_job_id] + if parse_job_ids: + read_cache['parse_jobs_by_id'] = { + int(job.id): job for job in Job.query.filter(Job.id.in_(parse_job_ids)).all() + } + candidates = ShippingOrderCandidate.query.filter( + ShippingOrderCandidate.intake_id.in_(intake_ids), + ).all() + read_cache['candidate_by_id'] = {int(candidate.id): candidate for candidate in candidates} + for candidate in candidates: + if ( + bool(candidate.is_current_version) + and str(candidate.candidate_status or '').strip().lower() in {'provisional', 'accepted'} + ): + intake_id = int(candidate.intake_id) + read_cache['candidate_count_by_intake_id'][intake_id] = ( + int(read_cache['candidate_count_by_intake_id'].get(intake_id, 0)) + 1 + ) + links = ( + ShippingOrderProcessingRunIntake.query.join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id, + ) + .filter(ShippingOrderProcessingRunIntake.intake_id.in_(intake_ids)) + .order_by( + ShippingOrderProcessingRun.created_at.desc(), + ShippingOrderProcessingRunIntake.created_at.desc(), + ) + .all() + ) + for link in links: + read_cache['run_links_by_intake_id'].setdefault( + int(link.intake_id), [], + ).append(link) + run = db.session.get(ShippingOrderProcessingRun, int(link.run_id)) + if run is not None: + read_cache['runs_by_id'].setdefault(int(run.id), run) + if intakes: + # 与写命令的选取语义一致:会话已有 Stream 时,Stream.current_case 才是 + # 每份 PDF 的当前版本事实。这里仅用于 GET 授权摘要,绝不加行锁。 + conversation_stream_cases = ( + db.session.query(ShippingOrderReviewCase) + .join( + ShippingOrderReviewStream, + ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, + ) + .join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id, + ) + .filter( + ShippingOrderReviewStream.owner_user_id == int(intakes[0].user_id), + ShippingOrderProcessingRun.conversation_id == str(intakes[0].conversation_id), + ) + .all() + ) + if conversation_stream_cases: + read_cache['reparseable_batch_for_conversation'] = any( + str(case.status or '').strip().lower() + in {'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending'} + and case.confirmed_task_id is None + for case in conversation_stream_cases + ) + return _ConversationProjectionLoadContext( + documents_by_intake_id=documents_by_intake_id, + intakes_by_no={str(intake.intake_no): intake for intake in intakes}, + prefetched_gate_attempts=prefetched_gate_attempts, + read_cache=read_cache, + ) + + +def _has_reparseable_batch_documents_for_projection( + *, run: ShippingOrderProcessingRun, + load_context: _ConversationProjectionLoadContext | None = None, +) -> bool: + """投影读取批次资格:优先会话预取,回退时也只能执行无锁只读查询。""" + cache = load_context.read_cache if load_context is not None else _conversation_projection_read_cache() + if isinstance(cache, dict): + conversation_cached = cache.get('reparseable_batch_for_conversation') + if conversation_cached is not None: + return bool(conversation_cached) + cached = cache.get('reparseable_batch_by_run_id', {}).get(int(run.id)) + if cached is not None: + return bool(cached) + from app.services.shipping_notice.order_review_disposition_service import ( + has_reparseable_batch_documents_readonly, + ) + + result = has_reparseable_batch_documents_readonly(user_id=int(run.user_id), run=run) + if isinstance(cache, dict): + cache.setdefault('reparseable_batch_by_run_id', {})[int(run.id)] = result + return result + # Intake 仍处于「材料解析」身份、页面应展示 order_intake 的 parse_status。 _INTAKE_ORDER_INTAKE_PARSE_STATUSES = frozenset({ 'created', @@ -343,7 +619,11 @@ def _intake_parse_attempt_count(intake: ShippingOrderIntake) -> int: return 0 from app.models import Job - job = db.session.get(Job, job_id) + cache = _conversation_projection_read_cache() + job = ( + cache['parse_jobs_by_id'].get(job_id) + if cache is not None else db.session.get(Job, job_id) + ) if job is None: return 0 return max(0, int(getattr(job, 'attempts', 0) or 0)) @@ -400,7 +680,7 @@ def _intake_current_gate( return None -def _intake_available_actions(intake: ShippingOrderIntake) -> list[str]: +def _intake_authorized_actions(intake: ShippingOrderIntake) -> list[str]: """Intake 级可用动作(最小集)。""" parse_status = str(intake.parse_status or '').strip().lower() actions = ['view_details'] @@ -413,6 +693,7 @@ def _intake_source_summary( intake: ShippingOrderIntake, *, asset: FileAsset | None, + load_context: _ConversationProjectionLoadContext | None = None, ) -> dict[str, Any]: """ 构建 Intake 的 source_summary。 @@ -431,28 +712,43 @@ def _intake_source_summary( if isinstance(structured.get('business_summary'), dict) else {} ) + prefetched_documents = ( + load_context.documents_by_intake_id.get(int(intake.id)) + if load_context is not None else None + ) document_filters = [ShippingOrderDocument.intake_id == int(intake.id)] # EML 正文是邮件上下文而非可处理文件。父卡数量必须与后续展开附件同源, # 否则会出现“3 个文件、只有 2 个(甚至 0 个)叶子”的假象。 if str(intake.source_type or '').strip().lower() == 'eml': document_filters.append(ShippingOrderDocument.document_type != 'email_body') - document_count = db.session.query(ShippingOrderDocument.id).filter( - *document_filters, - ).count() - parsed_document_count = db.session.query(ShippingOrderDocument.id).filter( - *document_filters, - ShippingOrderDocument.parse_status == 'parsed', - ).count() + if prefetched_documents is not None: + document_count = len(prefetched_documents) + parsed_document_count = sum( + str(document.parse_status or '').strip().lower() == 'parsed' + for document in prefetched_documents + ) + else: + document_count = db.session.query(ShippingOrderDocument.id).filter( + *document_filters, + ).count() + parsed_document_count = db.session.query(ShippingOrderDocument.id).filter( + *document_filters, + ShippingOrderDocument.parse_status == 'parsed', + ).count() from app.models import ShippingOrderCandidate + cache = _conversation_projection_read_cache() candidate_count = ( - db.session.query(ShippingOrderCandidate.id) - .filter( - ShippingOrderCandidate.intake_id == int(intake.id), - ShippingOrderCandidate.is_current_version.is_(True), - ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')), + cache['candidate_count_by_intake_id'].get(int(intake.id), 0) + if cache is not None else ( + db.session.query(ShippingOrderCandidate.id) + .filter( + ShippingOrderCandidate.intake_id == int(intake.id), + ShippingOrderCandidate.is_current_version.is_(True), + ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')), + ) + .count() ) - .count() ) subject = str(email.get('subject') or '').strip() or None filename = None @@ -483,6 +779,7 @@ def project_intake_work_item( *, submission: ShippingOrderSubmission | None = None, asset: FileAsset | None = None, + load_context: _ConversationProjectionLoadContext | None = None, ) -> dict[str, Any]: """ 将尚未建 OT(或仍在解析)的 Intake 投影为 ShippingProcessingProjection。 @@ -513,7 +810,7 @@ def project_intake_work_item( getattr(intake, 'updated_at', None) or getattr(intake, 'created_at', None) ) - legacy_actions = _intake_available_actions(intake) + authorized_actions = _intake_authorized_actions(intake) intake_status = _intake_processing_status(intake) intake_stage = _intake_processing_stage(intake) extraction_status = str( @@ -576,11 +873,13 @@ def project_intake_work_item( 'progress_version': progress_version, 'last_activity_at': _iso(last_activity) or '', 'current_gate': _intake_current_gate(intake, asset=asset), - 'available_actions': legacy_actions, - 'source_summary': _intake_source_summary(intake, asset=asset), + 'available_actions': authorized_actions, + 'source_summary': _intake_source_summary( + intake, asset=asset, load_context=load_context, + ), 'child_order_tasks': [], }, - legacy_actions=legacy_actions, + authorized_actions=authorized_actions, ) # Intake 与 OT 同样是 Processing Projection 的输出边界。补齐用户态字段后, # 会话卡无需从 legacy status 再次猜测“处理中/待人工”。 @@ -602,6 +901,7 @@ def project_intake_work_item( intake=intake, order_task_children=[], unit_by_document_id=unit_by_document_id, + load_context=load_context, ) aggregate_states = [ str(child.get('user_status') or child.get('status') or '').strip().lower() @@ -677,31 +977,45 @@ def _latest_intake_run_unit_outcomes( intake: ShippingOrderIntake, ) -> dict[int, ShippingOrderProcessingUnit]: """按文件读取 Intake 最新冻结 Unit 裁决,兼容部分重解析的跨 Run 谱系。""" + cache = _conversation_projection_read_cache() links = ( - ShippingOrderProcessingRunIntake.query.join( - ShippingOrderProcessingRun, - ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id, + cache['run_links_by_intake_id'].get(int(intake.id), []) + if cache is not None else ( + ShippingOrderProcessingRunIntake.query.join( + ShippingOrderProcessingRun, + ShippingOrderProcessingRun.id == ShippingOrderProcessingRunIntake.run_id, + ) + .filter(ShippingOrderProcessingRunIntake.intake_id == int(intake.id)) + .order_by( + ShippingOrderProcessingRun.created_at.desc(), + ShippingOrderProcessingRunIntake.created_at.desc(), + ) + .all() ) - .filter(ShippingOrderProcessingRunIntake.intake_id == int(intake.id)) - .order_by( - ShippingOrderProcessingRun.created_at.desc(), - ShippingOrderProcessingRunIntake.created_at.desc(), - ) - .all() ) outcomes: dict[int, ShippingOrderProcessingUnit] = {} for link in links: - run = db.session.get(ShippingOrderProcessingRun, int(link.run_id)) + run = ( + cache['runs_by_id'].get(int(link.run_id)) + if cache is not None else db.session.get( + ShippingOrderProcessingRun, int(link.run_id), + ) + ) plan = run.extraction_plan if run is not None else None if plan is None: continue units = ( - ShippingOrderProcessingUnit.query.filter( - ShippingOrderProcessingUnit.plan_id == int(plan.id), - ShippingOrderProcessingUnit.intake_id == int(intake.id), + [ + unit for unit in (getattr(plan, 'units', []) or []) + if int(unit.intake_id) == int(intake.id) + ] if cache is not None else ( + ShippingOrderProcessingUnit.query.filter( + ShippingOrderProcessingUnit.plan_id == int(plan.id), + ShippingOrderProcessingUnit.intake_id == int(intake.id), + ) + .order_by(ShippingOrderProcessingUnit.position.asc()) + .all() ) - .order_by(ShippingOrderProcessingUnit.position.asc()) - .all() ) # 部分重解析 Run 只包含被选中的 PDF。不能因它是全局最新 Run 就丢掉 # 兄弟文件在前一 Run 的开放 Case/失败裁决;按 document_id 首次命中才是真实最新事实。 @@ -975,6 +1289,10 @@ def _current_open_case_for_order_task(order_task: ShippingOrderTask | None) -> S document_id = getattr(candidate, 'primary_document_id', None) if candidate is not None else None if document_id is None: return None + cache = _conversation_projection_read_cache() + if cache is not None: + case = cache['current_case_by_document_id'].get(int(document_id)) + return case if case is not None and str(case.status or '') in {'unreviewed', 'draft', 'ready'} and case.confirmed_task_id is None else None return ( ShippingOrderReviewCase.query.join( ShippingOrderReviewStream, @@ -1033,11 +1351,15 @@ def _order_task_current_gate( project_user_gate_summary, ) + cache = _conversation_projection_read_cache() execution = ( - ShippingProcessExecution.query.filter_by(review_case_id=int(open_case.id)) - .filter(ShippingProcessExecution.status != 'superseded') - .order_by(ShippingProcessExecution.id.desc()) - .first() + cache['execution_by_case_id'].get(int(open_case.id)) + if cache is not None else ( + ShippingProcessExecution.query.filter_by(review_case_id=int(open_case.id)) + .filter(ShippingProcessExecution.status != 'superseded') + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) ) if execution is not None: summary = project_user_gate_summary(execution) @@ -1228,7 +1550,7 @@ def _project_order_task_work_item( user_task_no = str(getattr(order_task, 'task_no', None) or '').strip() if not user_task_no: return None - legacy_actions = list((task_row or {}).get('available_actions') or []) + authorized_actions = list((task_row or {}).get('available_actions') or []) documents = [] snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} for intake_row in snapshot.get('intakes') or []: @@ -1415,7 +1737,7 @@ def _project_order_task_work_item( 'current_gate': current_gate, # Gate 执行上下文与当前轻量节点分离,前端不得从 OT / 文件名猜写入目标。 'process_gate': process_gate, - 'available_actions': legacy_actions, + 'available_actions': authorized_actions, 'source_summary': _order_task_source_summary( run, order_task, @@ -1426,7 +1748,7 @@ def _project_order_task_work_item( _child_order_tasks_for_run(run, root_task_no=root_task_no) if is_root else [] ), }, - legacy_actions=legacy_actions, + authorized_actions=authorized_actions, invalidated_from_stage=invalidated_from_stage, excel_ready=excel_ready, verified_upload_success=verified_upload_success if notice_for_stage is not None else None, @@ -1434,8 +1756,7 @@ def _project_order_task_work_item( # [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。 record_projection_inconsistency_audit(payload) payload.pop('projection_inconsistency_code', None) - # [T8 用户态 Projection 6 字段] 新增 status/stage/current_gate/blocking_reason/primary_action/facts, - # 同时保存旧枚举到 legacy_status/stage/current_gate,保证旧客户端兼容。 + # [T8 用户态 Projection] 由正式 Gate 与领域事实生成唯一用户态合同。 payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task) # [Phase 3] 当 work_item 关联真实 open_case(未确认 Case 或 candidate_id 回链 Case)→ @@ -1469,12 +1790,10 @@ def _project_order_task_work_item( if pre_ot_stp: payload['stage'] = 'order_creating' payload['stage_label_key'] = 'order_creating' - payload['legacy_stage'] = 'order_creating' for child in payload.get('aggregate_children') or []: if isinstance(child, dict): child['stage'] = 'order_creating' child['stage_label_key'] = 'order_creating' - child['legacy_stage'] = 'order_creating' # 五字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions if isinstance(bundle.get('user_status'), str): payload['user_status'] = bundle['user_status'] @@ -1521,7 +1840,6 @@ def _project_order_task_work_item( if pre_ot_stp: payload['user_stage'] = 'pre_ot_stp' payload['user_current_gate_code'] = 'task_creation' - payload['legacy_status'] = payload.get('status') payload['status'] = 'failed' for child in payload.get('aggregate_children') or []: if isinstance(child, dict): @@ -1529,7 +1847,6 @@ def _project_order_task_work_item( child['user_current_gate_code'] = 'task_creation' child['stage'] = 'order_creating' child['stage_label_key'] = 'order_creating' - child['legacy_stage'] = 'order_creating' child['current_gate'] = dict(payload.get('current_gate') or {}) except Exception: # noqa: BLE001 # Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到 @@ -1605,12 +1922,10 @@ def _project_order_task_work_item( if str(payload.get('user_stage') or '').strip().lower() == 'pre_ot_stp': payload['stage'] = 'order_creating' payload['stage_label_key'] = 'order_creating' - payload['legacy_stage'] = 'order_creating' for child in payload.get('aggregate_children') or []: if isinstance(child, dict) and str(child.get('user_stage') or '').strip().lower() == 'pre_ot_stp': child['stage'] = 'order_creating' child['stage_label_key'] = 'order_creating' - child['legacy_stage'] = 'order_creating' return payload @@ -1792,11 +2107,27 @@ def _eml_aggregate_user_group( return 'processing' +def _intake_parse_case_primary_action(*, reparse_authorized: bool) -> dict[str, Any] | None: + """裁决无有效 Candidate 的 Review Case 在接收解析阶段的文件主动作。 + + 阶段按钮只负责打开工作台;文件行主动作必须是服务端已经授权的重解析命令。 + 摘要和详情投影共用本函数,防止首屏将导航动作提升为主 CTA。 + """ + if not reparse_authorized: + return None + return { + 'code': 'reparse', + 'variant': 'primary', + 'label_key': 'shipping.actions.reparse', + } + + def _eml_aggregate_document_children( *, intake: ShippingOrderIntake | None, order_task_children: list[dict[str, Any]], unit_by_document_id: dict[int, ShippingOrderProcessingUnit] | None = None, + load_context: _ConversationProjectionLoadContext | None = None, ) -> list[dict[str, Any]]: """以 EML Intake 的真实业务附件构建展开叶子,并仅叠加已存在 OT 的领域裁决。 @@ -1819,12 +2150,16 @@ def _eml_aggregate_document_children( ] documents = ( - ShippingOrderDocument.query.filter( - ShippingOrderDocument.intake_id == int(intake.id), - ShippingOrderDocument.document_type != 'email_body', + load_context.documents_by_intake_id.get(int(intake.id), []) + if load_context is not None + else ( + ShippingOrderDocument.query.filter( + ShippingOrderDocument.intake_id == int(intake.id), + ShippingOrderDocument.document_type != 'email_body', + ) + .order_by(ShippingOrderDocument.id.asc()) + .all() ) - .order_by(ShippingOrderDocument.id.asc()) - .all() ) if not documents: return [ @@ -1855,7 +2190,13 @@ def _eml_aggregate_document_children( # Unit 是附件级最终事实。Run 只是兄弟 Unit 的执行容器,绝不能因某一份 # PDF 失败覆盖同 Run 其它 review_required 附件的人工复核入口。 unit_run = getattr(getattr(unit, 'plan', None), 'run', None) if unit is not None else None - unit_failed = unit_status == 'failed' + # Run 已终止失败时,尚未同步的 Unit.review_required 是陈旧中间态, + # 不能把失败文件误投影为待人工;后续重解析 Run 仍按最新谱系覆盖。 + unit_run_failed = str( + getattr(unit_run, 'status', '') or '', + ).strip().lower() == 'failed' + unit_failed = unit_status == 'failed' or unit_run_failed + unit_reparse_authorized = unit_status == 'failed' failure_reason_code = ( str( getattr(unit_run, 'error_code', None) @@ -1872,15 +2213,23 @@ def _eml_aggregate_document_children( # Case 是候选落库后的正式人工阶段事实;Unit 保留 candidate_ready 不能让 # EML 聚合退回「接收解析」。当前 Case 可来自局部重解析后的新 Unit, # 故必须按原 Document 的 Stream 指针查找,不能按旧 unit_id 反查。 + cache = _conversation_projection_read_cache() review_case = ( - ShippingOrderReviewCase.query.join( - ShippingOrderReviewStream, - ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, - ).filter( - ShippingOrderReviewStream.document_id == int(document.id), - ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')), - ).one_or_none() + cache['current_case_by_document_id'].get(int(document.id)) + if cache is not None else ( + ShippingOrderReviewCase.query.join( + ShippingOrderReviewStream, + ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, + ).filter( + ShippingOrderReviewStream.document_id == int(document.id), + ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')), + ).one_or_none() + ) ) + if review_case is not None and str(review_case.status or '') not in { + 'unreviewed', 'draft', 'ready', 'confirming', + }: + review_case = None review_required = review_required or review_case is not None review_bundle: dict[str, Any] | None = None if review_case is not None: @@ -1935,22 +2284,16 @@ def _eml_aggregate_document_children( 'details': {}, } if 'reparse' in review_actions: - review_primary = { - 'code': 'reparse', - 'variant': 'primary', - 'label_key': 'shipping.actions.reparse', - } + review_primary = _intake_parse_case_primary_action( + reparse_authorized=True, + ) else: - # 防御性兜底:Case 未授予 reparse 时只保留其正式裁决动作, - # 不从接收解析状态反推或构造重解析权限。 - action_code = str(explained.get('next_action') or 'open_order_review').strip() - review_primary = { - 'code': action_code, - 'variant': 'primary', - 'label_key': f'shipping.actions.{action_code}', - } - review_actions = [action_code] - elif unit_failed: + # 没有当前有效 Candidate 时,Case 仍属于解析处置阶段。 + # 不能把 explainability 的 next_action(尤其是 open_order_review) + # 当成订单复核授权,否则会渲染出按钮但在工作台被前置阶段守卫拒绝。 + review_primary = None + review_actions = [] + elif unit_reparse_authorized: # 尚未形成 Case 的失败附件只能由后端授权对所属 Run 发起重解析。 # 前端仅消费这份 reparse 动作及下发的 Run 身份,绝不按失败状态补造。 review_primary = { @@ -1960,9 +2303,12 @@ def _eml_aggregate_document_children( } review_actions = ['reparse'] run = ( - db.session.get(ShippingOrderProcessingRun, int(review_case.run_id)) - if review_case is not None - else unit_run + ( + cache['runs_by_id'].get(int(review_case.run_id)) + if cache is not None else db.session.get( + ShippingOrderProcessingRun, int(review_case.run_id), + ) + ) if review_case is not None else unit_run ) leaf = { 'work_item_type': 'document', @@ -1984,7 +2330,7 @@ def _eml_aggregate_document_children( 'progress_version': int(getattr(intake, 'progress_version', None) or 1), 'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '', 'current_gate': review_gate if review_case is not None else None, - 'available_actions': review_actions if (review_case is not None or unit_failed) else [], + 'available_actions': review_actions if (review_case is not None or unit_reparse_authorized) else [], 'blocking_reason': ( {'code': failure_reason_code, 'details': {}} if unit_failed else @@ -2000,7 +2346,7 @@ def _eml_aggregate_document_children( # 附件只有明确授予 reparse 时才展示当前阶段,不能由前端按失败态猜测。 'intake_parse_authorized': bool( (review_case is not None and not has_current_candidate) - or (unit_failed and 'reparse' in review_actions) + or (unit_reparse_authorized and 'reparse' in review_actions) ), 'child_order_tasks': [], } @@ -2021,32 +2367,16 @@ def _eml_aggregate_document_children( has_current_candidate ) leaf['source_summary'] = summary - # 有/无预建 OT 的 EML 附件都在这里汇合。批次中心的文件级主动作只能 - # 是生命周期入口;create/edit/validate 是 Case 内部处置,必须在工作台内 - # 呈现。只保留正式 Process Gate 的主动作;Case 内部码(例如 - # order_review_build)即使带 next_action 也不能夺走批次入口。 - leaf_case_no = str(leaf.get('case_no') or '').strip() - leaf_gate = leaf.get('current_gate') if isinstance(leaf.get('current_gate'), dict) else {} - leaf_primary = leaf.get('primary_action') if isinstance(leaf.get('primary_action'), dict) else {} - from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET - - has_formal_gate = str(leaf_gate.get('gate_code') or '').strip() in PROCESS_GATE_CODE_SET - if ( - leaf_case_no - and not has_formal_gate - and str(leaf_primary.get('code') or '').strip() in {'create_draft', 'edit_draft', 'validate'} - ): - leaf['primary_action'] = { - 'code': 'open_order_review', - 'variant': 'primary', - 'label_key': 'shipping.actions.open_order_review', - } + # 文件主动作保留 Case / Gate 已裁决的真实动作码。生命周期导航由 + # ui_state.lifecycle_entries 单独表达,不能为消除重复而篡改业务动作。 result.append(_with_processing_ui_state(leaf)) return result def _aggregate_eml_order_task_work_items( work_items: list[dict[str, Any]], + *, + load_context: _ConversationProjectionLoadContext | None = None, ) -> list[dict[str, Any]]: """ 按 Intake 聚合同一 EML 的多个 order_task 工作项。 @@ -2087,7 +2417,11 @@ def _aggregate_eml_order_task_work_items( result = list(passthrough) for intake_no, children in grouped.items(): # EML 的计数、状态及展开明细必须基于同一组业务附件,而不是仅基于已创建 OT。 - intake = ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() + intake = ( + load_context.intakes_by_no.get(intake_no) + if load_context is not None + else ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() + ) aggregate_children = _eml_aggregate_document_children( intake=intake, order_task_children=children, @@ -2095,6 +2429,7 @@ def _aggregate_eml_order_task_work_items( _latest_intake_run_unit_outcomes(intake) if intake is not None else None ), + load_context=load_context, ) states = [_state(item) for item in aggregate_children] upload_states = [_upload_state(item) for item in aggregate_children] @@ -2197,13 +2532,11 @@ def _aggregate_eml_order_task_work_items( candidate_runs = ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.run_no.in_(candidate_run_nos), ).all() - from app.services.shipping_notice.order_review_disposition_service import ( - has_reparseable_batch_documents, - ) - if any( str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} - and has_reparseable_batch_documents(user_id=int(run.user_id), run=run) + and _has_reparseable_batch_documents_for_projection( + run=run, load_context=load_context, + ) for run in candidate_runs ) and 'reparse_batch' not in aggregate['available_actions']: aggregate['available_actions'].append('reparse_batch') @@ -2428,10 +2761,9 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: current_gate=( item.get('current_gate') if isinstance(item.get('current_gate'), dict) - else {'gate_code': item.get('user_current_gate_code')} + else None ), blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None, - legacy_stage=str(item.get('user_stage') or item.get('stage') or ''), # root_order_task_no 只是导航身份;必须有当前 Candidate 或正式通知事实才开放入口。 has_candidate_context=bool( int(source_summary.get('candidate_count') or 0) > 0 @@ -2441,6 +2773,7 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: # 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。 has_intake_parse_context=bool(item.get('intake_parse_authorized')), verified_upload_success=bool(item.get('verified_upload_success')), + processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None, ) lifecycle_stage = lifecycle['lifecycle_stage'] if primary is not None: @@ -2498,6 +2831,30 @@ def _with_processing_ui_state(item: dict[str, Any]) -> dict[str, Any]: return projected +def _strip_legacy_action_fields_for_response(value: Any) -> Any: + """在 API 边界移除已下线的顶层动作镜像。 + + 内部投影仍可用 ``primary_action`` / ``available_actions`` 选择 EML 当前代表项, + 但对外唯一动作合同是 ``ui_state``。在最终序列化前剥离镜像,防止新旧合同再次被 + 客户端混用;递归处理 EML 子附件和会话状态组。 + + Args: + value: 已完成全部聚合的公开 DTO 片段。 + + Returns: + 不含旧顶层动作字段、其余结构不变的公开 DTO。 + """ + if isinstance(value, list): + return [_strip_legacy_action_fields_for_response(item) for item in value] + if not isinstance(value, dict): + return value + return { + key: _strip_legacy_action_fields_for_response(item) + for key, item in value.items() + if key not in {'primary_action', 'available_actions'} + } + + def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -> str | None: """将已授权动作映射到工作台展示面;未知动作不生成导航目标。""" code = str(action_code or '').strip().lower() @@ -2524,18 +2881,18 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) - def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None: - """批次统计使用与任务详情相同的共享生命周期裁决,不维护独立映射。""" + """批次统计复用共享裁决器,并优先映射项目已写入的文件阶段事实。""" return project_lifecycle( current_gate=( item.get('current_gate') if isinstance(item.get('current_gate'), dict) - else {'gate_code': item.get('user_current_gate_code')} + else None ), blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None, - legacy_stage=str(item.get('user_stage') or item.get('stage') or ''), has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')), has_intake_parse_context=bool(item.get('intake_parse_authorized')), verified_upload_success=bool(item.get('verified_upload_success')), + processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None, )['lifecycle_stage'] @@ -2717,13 +3074,9 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> candidate_runs = ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.run_no.in_(candidate_run_nos), ).all() - from app.services.shipping_notice.order_review_disposition_service import ( - has_reparseable_batch_documents, - ) - if any( str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'} - and has_reparseable_batch_documents(user_id=int(run.user_id), run=run) + and _has_reparseable_batch_documents_for_projection(run=run) for run in candidate_runs ) and 'reparse_batch' not in clone['available_actions']: clone['available_actions'].append('reparse_batch') @@ -2812,11 +3165,6 @@ def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, A return nodes -def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """兼容别名:已升级为五阶段输出,调用方应迁移至 ``_batch_lifecycle_nodes``。""" - return _batch_lifecycle_nodes(work_items) - - def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]: """统计无法归入业务生命周期的文件,避免批次摘要与文件清单口径不一致。""" return { @@ -2897,26 +3245,11 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An def _batch_user_group(item: dict[str, Any]) -> str: - """归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。""" - # 兼容载荷中可能残留 technical completed。只要正式 Notice/OT 已明确给出 - # 未验证成功,就绝不能把它带入批次 completed 分子。 - if item.get('verified_upload_success') is False and str( - item.get('user_status') or item.get('status') or '' - ).strip().lower() == 'completed': - return 'waiting_human' + """返回领域投影已经裁决的唯一用户分组,缺失时保持未分类。""" group = str(item.get('user_group') or '').strip().lower() if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: return group - status = str(item.get('user_status') or item.get('status') or '').strip().lower() - if status in {'failed', 'retryable'}: - return 'failed' - if status in {'waiting_human', 'waiting_review', 'idle'}: - return 'waiting_human' - if status == 'completed': - return 'completed' - if status in {'cancelled', 'archived', 'voided', 'deleted'}: - return 'cancelled' - return 'processing' + return 'unclassified' def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: @@ -2947,7 +3280,7 @@ def _conversation_processing_from_work_items( recent_task_no: str | None = None, ) -> dict[str, Any]: """ - 由最终 work_items 重建 conversation_processing 兼容块(含兄弟 OT)。 + 由最终 work_items 构建完整详情投影。 核心逻辑:仅消费 order_task 项;按 status/stage 分组;文件总数优先按 source_summary.document_id 去重,避免异常兄弟 OT 重复累计同一 PDF; @@ -2964,10 +3297,6 @@ def _conversation_processing_from_work_items( # 文件清单必须与批次统计、五阶段和 CTA 使用相同的当前文件代表项,同时 # 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。 display_work_items = _display_work_items_from_current_files(work_items) - needs_action: list[dict[str, Any]] = [] - processing: list[dict[str, Any]] = [] - completed: list[dict[str, Any]] = [] - history: list[dict[str, Any]] = [] all_rows: list[dict[str, Any]] = [] focused = str(focused_task_no or '').strip() or None recent = str(recent_task_no or '').strip() or None @@ -2981,24 +3310,20 @@ def _conversation_processing_from_work_items( all_rows.append(row) if recent and row['user_task_no'] == recent: row['recently_created'] = True - bucket = row['group'] - if bucket == 'needs_action': - needs_action.append(row) - elif bucket == 'completed': - completed.append(row) - elif bucket == 'history': - history.append(row) - else: - processing.append(row) - def _sort_key(entry: dict[str, Any]) -> str: return str(entry.get('last_activity_at') or entry.get('created_at') or '') - needs_action.sort(key=_sort_key, reverse=True) - processing.sort(key=_sort_key, reverse=True) - completed.sort(key=_sort_key, reverse=True) - history.sort(key=_sort_key, reverse=True) - total = len(needs_action) + len(processing) + len(completed) + status_groups = { + 'failed': [row for row in all_rows if row.get('user_group') == 'failed'], + 'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'], + 'processing': [row for row in all_rows if row.get('user_group') == 'processing'], + 'completed': [row for row in all_rows if row.get('user_group') == 'completed'], + 'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'], + 'archived': [row for row in all_rows if row.get('user_group') == 'archived'], + } + for rows in status_groups.values(): + rows.sort(key=_sort_key, reverse=True) + total = sum(len(rows) for rows in status_groups.values()) # [STEP 2] 会话文件数是业务 PDF 去重数,不是各任务 Run 文档数的简单求和。 # 仅以当前且仍活跃的业务文件兜底;取消/归档的历史文档不能因 # source_summary 仍保留 document_id 而重新进入完成率分母。 @@ -3019,7 +3344,8 @@ def _conversation_processing_from_work_items( total_files = file_counts['total_files'] or ( len(document_ids) if document_ids - else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed) + else sum(int(row.get('file_count') or 0) for key, rows in status_groups.items() + if key in {'failed', 'waiting_human', 'processing', 'completed'} for row in rows) ) lifecycle_nodes = _batch_lifecycle_nodes(work_items) return { @@ -3027,36 +3353,511 @@ def _conversation_processing_from_work_items( 'summary': { 'total_tasks': total, 'total_files': total_files, - 'processing': len(processing), - 'needs_action': len(needs_action), - 'completed': len(completed), - 'history': len(history), + 'processing': len(status_groups['processing']), + 'needs_action': len(status_groups['failed']) + len(status_groups['waiting_human']), + 'completed': len(status_groups['completed']), + 'history': len(status_groups['cancelled']) + len(status_groups['archived']), **file_counts, }, 'focused_task_no': focused, 'recent_task_no': recent, - 'needs_action': needs_action, - 'processing': processing, - 'completed': completed, - 'history': history, - 'status_groups': { - 'failed': [row for row in all_rows if row.get('user_group') == 'failed'], - 'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'], - 'processing': [row for row in all_rows if row.get('user_group') == 'processing'], - 'completed': [row for row in all_rows if row.get('user_group') == 'completed'], - 'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'], - 'archived': [row for row in all_rows if row.get('user_group') == 'archived'], - }, + 'status_groups': status_groups, # 新客户端只消费 lifecycle_nodes;旧字段在一个发布周期内原样兼容,避免 # 会话卡、批次中心和嵌入式消费者在灰度期间看到不同阶段数。 'lifecycle_nodes': lifecycle_nodes, - 'four_stage_nodes': lifecycle_nodes, 'unclassified_summary': _unclassified_summary(work_items), 'ui_state': _batch_ui_state_from_items(work_items), 'output_artifacts': _batch_output_artifacts(work_items), } +def project_conversation_processing_summary( + *, + user_id: int, + conversation_id: str, + agent_id: int | None = None, + focused_task_no: str | None = None, + recent_task_no: str | None = None, +) -> dict[str, Any]: + """返回会话首屏的轻量进度读模型。 + + 首屏只需要后端已裁决的状态→EML→PDF树、统计和已授权动作标识;完整 + work_items、Gate 执行上下文与旧四组镜像属于详情读模型,必须按需通过 + work-item 接口读取。摘要仅批量读取正式 Gate 的最小状态列,绝不加载 + Attempt、Run JSON 或详情上下文,避免同一任务在首屏响应中重复传输三次。 + """ + del agent_id + normalized = str(conversation_id or '').strip() + if not normalized: + raise ValidationError('conversation_id is required') + + # 首屏严禁加载 Run JSON 快照、Plan/Unit 或 Gate Attempt;它们只属于详情读取。 + # 摘要只读取状态树和操作裁决所需列;正文、解析结果和重复检测 JSON + # 属于详情读模型,禁止在首屏查询中触发 ORM 反序列化。 + intakes = ShippingOrderIntake.query.options(load_only( + ShippingOrderIntake.id, + ShippingOrderIntake.intake_no, + ShippingOrderIntake.asset_id, + ShippingOrderIntake.source_type, + ShippingOrderIntake.updated_at, + )).filter( + ShippingOrderIntake.user_id == int(user_id), + ShippingOrderIntake.conversation_id == normalized, + ShippingOrderIntake.purpose == 'shipping_notice', + ).order_by(ShippingOrderIntake.updated_at.desc(), ShippingOrderIntake.id.desc()).all() + intake_ids = [int(row.id) for row in intakes] + documents_by_intake: dict[int, list[ShippingOrderDocument]] = {item_id: [] for item_id in intake_ids} + if intake_ids: + for document in ShippingOrderDocument.query.options(load_only( + ShippingOrderDocument.id, + ShippingOrderDocument.intake_id, + ShippingOrderDocument.filename, + ShippingOrderDocument.parse_status, + ShippingOrderDocument.classification, + ShippingOrderDocument.order_extraction_status, + ShippingOrderDocument.order_extraction_error_code, + )).filter( + ShippingOrderDocument.intake_id.in_(intake_ids), + ShippingOrderDocument.document_type != 'email_body', + ).order_by(ShippingOrderDocument.intake_id.asc(), ShippingOrderDocument.id.asc()).all(): + documents_by_intake.setdefault(int(document.intake_id), []).append(document) + asset_ids = [int(item.asset_id) for item in intakes if item.asset_id] + assets = { + int(asset.id): asset + for asset in (FileAsset.query.options(load_only( + FileAsset.id, + FileAsset.original_filename, + )).filter(FileAsset.id.in_(asset_ids)).all() if asset_ids else []) + } + candidates = ShippingOrderCandidate.query.options(load_only( + ShippingOrderCandidate.id, + ShippingOrderCandidate.primary_document_id, + ShippingOrderCandidate.order_extraction_run_id, + ShippingOrderCandidate.po_number, + )).filter( + ShippingOrderCandidate.intake_id.in_(intake_ids) if intake_ids else False, + ShippingOrderCandidate.is_current_version.is_(True), + ).all() + candidate_by_document_id = { + int(candidate.primary_document_id): candidate + for candidate in candidates + if candidate.primary_document_id is not None + } + candidate_ids = [int(candidate.id) for candidate in candidates] + tasks_by_candidate_id = { + int(task.candidate_id): task + for task in ShippingOrderTask.query.options(load_only( + ShippingOrderTask.id, + ShippingOrderTask.candidate_id, + ShippingOrderTask.shipping_notice_id, + ShippingOrderTask.task_no, + ShippingOrderTask.extraction_run_id, + ShippingOrderTask.status, + ShippingOrderTask.stage, + ShippingOrderTask.error_code, + ShippingOrderTask.updated_at, + )).filter( + ShippingOrderTask.user_id == int(user_id), + ShippingOrderTask.conversation_id == normalized, + ShippingOrderTask.candidate_id.in_(candidate_ids) if candidate_ids else False, + ).order_by(ShippingOrderTask.updated_at.desc(), ShippingOrderTask.id.desc()).all() + if task.candidate_id is not None + } + # 正式 Notice / Execution / 当前 Gate 是建单后业务阶段的唯一真相。摘要以 + # 固定三次批量查询取得最小列,不触碰 Gate Attempt、详情 JSON 或关系加载。 + task_ids = [int(task.id) for task in tasks_by_candidate_id.values()] + direct_notice_ids = { + int(task.shipping_notice_id) + for task in tasks_by_candidate_id.values() + if task.shipping_notice_id is not None + } + notices_by_id: dict[int, ShippingNotice] = {} + notices_by_order_task_id: dict[int, ShippingNotice] = {} + if task_ids: + for notice in ShippingNotice.query.options(load_only( + ShippingNotice.id, + ShippingNotice.order_task_id, + ShippingNotice.active_process_execution_id, + )).filter(ShippingNotice.order_task_id.in_(task_ids)).all(): + notices_by_id[int(notice.id)] = notice + if notice.order_task_id is not None: + notices_by_order_task_id[int(notice.order_task_id)] = notice + missing_direct_notice_ids = direct_notice_ids.difference(notices_by_id) + if missing_direct_notice_ids: + for notice in ShippingNotice.query.options(load_only( + ShippingNotice.id, + ShippingNotice.order_task_id, + ShippingNotice.active_process_execution_id, + )).filter(ShippingNotice.id.in_(missing_direct_notice_ids)).all(): + notices_by_id[int(notice.id)] = notice + if notice.order_task_id is not None: + notices_by_order_task_id.setdefault(int(notice.order_task_id), notice) + notice_ids = list(notices_by_id) + executions_by_id: dict[int, ShippingProcessExecution] = {} + latest_execution_by_notice_id: dict[int, ShippingProcessExecution] = {} + if notice_ids: + for execution in ShippingProcessExecution.query.options(load_only( + ShippingProcessExecution.id, + ShippingProcessExecution.task_id, + ShippingProcessExecution.status, + ShippingProcessExecution.current_gate_code, + )).filter( + ShippingProcessExecution.task_id.in_(notice_ids), + ShippingProcessExecution.status != 'superseded', + ).order_by(ShippingProcessExecution.id.desc()).all(): + executions_by_id[int(execution.id)] = execution + if execution.task_id is not None: + latest_execution_by_notice_id.setdefault(int(execution.task_id), execution) + current_gate_codes = { + str(execution.current_gate_code).strip() + for execution in executions_by_id.values() + if str(execution.current_gate_code or '').strip() + } + gates_by_execution_and_code: dict[tuple[int, str], ShippingProcessGate] = {} + if executions_by_id and current_gate_codes: + for gate in ShippingProcessGate.query.options(load_only( + ShippingProcessGate.execution_id, + ShippingProcessGate.gate_code, + ShippingProcessGate.status, + ShippingProcessGate.blocking_reason_code, + ShippingProcessGate.next_action_code, + )).filter( + ShippingProcessGate.execution_id.in_(list(executions_by_id)), + ShippingProcessGate.gate_code.in_(current_gate_codes), + ).all(): + gates_by_execution_and_code[(int(gate.execution_id), str(gate.gate_code))] = gate + + def _current_gate_for_task(task: ShippingOrderTask | None) -> dict[str, str] | None: + """返回摘要所需的正式当前 Gate;只消费当前 Execution 的最小持久化列。""" + if task is None: + return None + notice = ( + notices_by_id.get(int(task.shipping_notice_id)) + if task.shipping_notice_id is not None + else notices_by_order_task_id.get(int(task.id)) + ) + if notice is None: + return None + execution = ( + executions_by_id.get(int(notice.active_process_execution_id)) + if notice.active_process_execution_id is not None + else latest_execution_by_notice_id.get(int(notice.id)) + ) + if execution is None: + return None + gate_code = str(execution.current_gate_code or '').strip() + gate = gates_by_execution_and_code.get((int(execution.id), gate_code)) if gate_code else None + if gate is None: + return None + return { + 'gate_code': str(gate.gate_code), + 'status': str(gate.status), + 'blocking_reason_code': str(gate.blocking_reason_code or '').strip(), + 'next_action_code': str(gate.next_action_code or '').strip(), + } + document_ids = [ + int(document.id) + for documents in documents_by_intake.values() + for document in documents + ] + current_case_by_document_id = { + int(case.document_id): case + for case in ShippingOrderReviewCase.query.join( + ShippingOrderReviewStream, + ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, + ).options(load_only( + ShippingOrderReviewCase.id, + ShippingOrderReviewCase.document_id, + ShippingOrderReviewCase.run_id, + ShippingOrderReviewCase.case_no, + ShippingOrderReviewCase.status, + ShippingOrderReviewCase.current_draft_id, + ShippingOrderReviewCase.confirmed_task_id, + )).filter( + ShippingOrderReviewStream.document_id.in_(document_ids) if document_ids else False, + ).all() + } + run_ids = { + int(run_id) + for candidate in candidates + for run_id in ( + getattr(candidate, 'order_extraction_run_id', None), + getattr(tasks_by_candidate_id.get(int(candidate.id)), 'extraction_run_id', None), + ) + if run_id is not None + } + run_ids.update( + int(case.run_id) + for case in current_case_by_document_id.values() + if case.run_id is not None + ) + runs_by_id = { + int(run.id): run + for run in ( + ShippingOrderProcessingRun.query.options(load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.run_no, + )).filter( + ShippingOrderProcessingRun.id.in_(run_ids), + ).all() + if run_ids else [] + ) + } + + def _status( + document: ShippingOrderDocument, + task: ShippingOrderTask | None, + case: ShippingOrderReviewCase | None, + current_gate: dict[str, str] | None, + ) -> tuple[str, str, str | None]: + gate_status = str((current_gate or {}).get('status') or '').strip().lower() + gate_code = str((current_gate or {}).get('gate_code') or '').strip().lower() + gate_reason = str((current_gate or {}).get('blocking_reason_code') or '').strip() or None + if gate_status == 'blocked_manual': + return 'waiting_human', gate_code, gate_reason + if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}: + return 'failed', gate_code, gate_reason or 'processing_failed' + if gate_status in {'queued', 'running', 'waiting_external', 'pending'}: + return 'running', gate_code, gate_reason + if gate_status == 'cancelled': + return 'cancelled', gate_code, gate_reason + case_status = str(getattr(case, 'status', None) or '').strip().lower() + if case is not None and case.confirmed_task_id is None and case_status in { + 'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending', + }: + return 'waiting_human', 'waiting_review', f'review_case_{case_status}' + raw = str(task.status if task is not None else document.order_extraction_status or '').strip().lower() + stage = str(task.stage if task is not None else '').strip().lower() or ( + 'document_parsing' if str(document.parse_status or '').strip().lower() != 'parsed' else 'candidate_creating' + ) + if raw in {'failed', 'parse_failed', 'technical_retrying'}: + return 'failed', stage, str(task.error_code if task is not None else document.order_extraction_error_code or 'processing_failed') + if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}: + return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review' + if raw in {'completed', 'uploaded'}: + return 'completed', 'completed', None + if raw in {'cancelled', 'archived'}: + return raw, raw, None + return 'running', stage, None + + def _leaf( + document: ShippingOrderDocument, + task: ShippingOrderTask | None, + case: ShippingOrderReviewCase | None, + ) -> dict[str, Any]: + current_gate = _current_gate_for_task(task) + user_status, stage, reason = _status(document, task, case, current_gate) + group = 'processing' if user_status == 'running' else user_status + task_no = str(task.task_no).strip() if task is not None else None + candidate = candidate_by_document_id.get(int(document.id)) + candidate_po = str(getattr(candidate, 'po_number', None) or '').strip() if candidate is not None else '' + # 摘要只信任 Candidate 的规范化 PO 列;结构化抽取 JSON 仅在详情接口按需读取。 + # 候选存在不等于关键字段已完成解析;没有 PO 时仍停留在接收解析阶段。 + if not candidate_po and stage in {'waiting_review', 'order_review'}: + stage = 'candidate_creating' + case_status = str(getattr(case, 'status', None) or '').strip().lower() + terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'} + extraction_failed = str(document.order_extraction_status or '').strip().lower() in { + 'failed', 'parse_failed', 'technical_retrying', + } + task_no = str(task.task_no).strip() if task is not None else None + available_actions: list[str] = [] + primary_action: dict[str, Any] | None = None + intake_parse_authorized = False + gate_action = str((current_gate or {}).get('next_action_code') or '').strip() + if gate_action: + available_actions = [gate_action] + primary_action = {'code': gate_action, 'variant': 'primary'} + elif extraction_failed and case is None: + # Intake 解析失败的恢复入口只指向既有 retry API;不猜测 Case/订单入口。 + available_actions = ['retry_parse'] + primary_action = { + 'code': 'retry_parse', + 'variant': 'primary', + 'label_key': 'shipping.actions.retry_parse', + } + intake_parse_authorized = True + elif case is not None and not terminal_case: + if candidate is not None: + # 当前 Candidate 已生成后,Case 进入订单复核;仅用已批量读取的 + # current_draft_id 恢复权威业务动作,避免摘要路径逐文件加载 Case 详情。 + available_actions = ['edit_draft' if case.current_draft_id else 'create_draft'] + primary_action = project_case_primary_action( + user_status, + {'code': reason, 'i18n_key': None, 'details': None}, + available_actions, + user_stage='order_review', + ) + else: + # 无有效 Candidate 的 Case 仍在接收解析处置;阶段按钮只负责导航, + # 文件主动作必须是服务端已经授权的重解析命令。 + available_actions = ['reparse'] + primary_action = _intake_parse_case_primary_action( + reparse_authorized=True, + ) + elif task is not None or candidate_by_document_id.get(int(document.id)) is not None: + # Candidate 已形成但 Case 尚未物化时,仍保留进入订单生命周期的安全入口; + # 详情页会显示当前事实并在服务端决定是否可继续编辑。 + available_actions = ['open_order_review'] + primary_action = { + 'code': 'open_order_review', + 'variant': 'primary', + 'label_key': 'shipping.actions.open_order_review', + } + elif task_no and user_status not in {'completed', 'cancelled', 'archived'}: + # 有正式 OT 但暂时没有可执行 Gate 时,至少保留进入生命周期工作台入口。 + available_actions = ['open_order_review'] + primary_action = { + 'code': 'open_order_review', + 'variant': 'primary', + 'label_key': 'shipping.actions.open_order_review', + } + leaf = { + 'work_item_type': 'order_task', + 'work_item_no': f'DOCUMENT:{document.id}', + 'source_type': 'direct_pdf', + 'root_order_task_no': task_no, + 'run_no': ( + # Case 是接收解析工作台的稳定对象;深链必须使用同一 Case 的 Run, + # 不能因其尚未物化 Candidate/OT 而丢失 run_no。 + str(getattr(runs_by_id.get(int(case.run_id)), 'run_no', '') or '').strip() + if case is not None and getattr(case, 'run_id', None) in runs_by_id + else str(getattr(runs_by_id.get(int(task.extraction_run_id)), 'run_no', '') or '').strip() + if task is not None and getattr(task, 'extraction_run_id', None) in runs_by_id + else str(getattr(runs_by_id.get(int(candidate.order_extraction_run_id)), 'run_no', '') or '').strip() + if candidate is not None and getattr(candidate, 'order_extraction_run_id', None) in runs_by_id + else None + ), + 'intake_no': str(getattr(document, 'intake_id', None) or '').strip() or None, + 'case_no': str(getattr(case, 'case_no', None) or '').strip() or None, + 'status': 'processing' if user_status == 'running' else user_status, + 'stage': stage, + 'user_status': user_status, + 'user_stage': stage, + 'user_group': group, + 'source_summary': { + 'document_id': int(document.id), + 'filename': str(document.filename or '').strip() or None, + 'document_count': 1, + 'parsed_document_count': int(str(document.parse_status or '').strip().lower() == 'parsed'), + 'candidate_count': 1 if candidate is not None or task is not None or case is not None else 0, + 'po_number': candidate_po or None, + }, + 'current_gate': current_gate, + 'blocking_reason': {'code': reason} if reason else None, + 'primary_action': primary_action, + 'available_actions': available_actions, + 'intake_parse_authorized': intake_parse_authorized, + } + return _with_processing_ui_state(leaf) + + groups: dict[str, list[dict[str, Any]]] = {key: [] for key in ( + 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', + )} + for intake in intakes: + intake_documents = documents_by_intake.get(int(intake.id), []) + leaves = [] + tasks: list[ShippingOrderTask] = [] + for document in intake_documents: + candidate = candidate_by_document_id.get(int(document.id)) + task = tasks_by_candidate_id.get(int(candidate.id)) if candidate is not None else None + case = current_case_by_document_id.get(int(document.id)) + # 邮件的 unknown/supporting 附件若没有 Candidate、Review Case 或 OT, + # 只是原始邮件的支撑材料,不是可进入五阶段的业务文件。 + classification = str(document.classification or '').strip().lower() + if classification in {'unknown', 'supporting'} and candidate is None and case is None and task is None: + continue + if task is not None: + tasks.append(task) + leaves.append(_leaf(document, task, case)) + if not leaves: + continue + states = [str(leaf['user_status']) for leaf in leaves] + group = next((key for key in ('failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived') if key in states), 'processing') + source_type = str(intake.source_type or '').strip().lower() or 'direct_pdf' + asset = assets.get(int(intake.asset_id)) if intake.asset_id else None + title = str(getattr(asset, 'original_filename', None) or '').strip() or str(intake.intake_no) + is_eml = source_type == 'eml' + primary_task = tasks[0] if tasks else None + task_no = str(primary_task.task_no).strip() if primary_task is not None else f'INTAKE:{intake.intake_no}' + groups[group].append({ + 'user_task_no': task_no, + 'title': title, + 'display_kind': 'multi_document_task' if len(leaves) > 1 else 'single_document_task', + 'group': 'needs_action' if group in {'failed', 'waiting_human'} else ('history' if group in {'cancelled', 'archived'} else group), + 'status_label': 'pending_review' if group == 'waiting_human' else ('processing' if group == 'processing' else group), + 'file_count': len(leaves), + 'run_no': next((str(leaf.get('run_no') or '').strip() for leaf in leaves if leaf.get('run_no')), None), + 'case_no': next((str(leaf.get('case_no') or '').strip() for leaf in leaves if leaf.get('case_no')), None), + 'last_activity_at': _iso(intake.updated_at) or '', + 'available_actions': list( + dict.fromkeys( + action + for leaf in leaves + for action in (leaf.get('available_actions') or []) + ), + ), + 'user_status': 'running' if group == 'processing' else group, + 'user_stage': leaves[0]['user_stage'], + 'user_group': group, + 'aggregate_summary': {'intake_no': str(intake.intake_no), 'total': len(leaves)}, + 'aggregate_children': leaves if is_eml else leaves, + 'ui_state': _processing_ui_state_from_item({ + 'user_status': 'running' if group == 'processing' else group, + 'user_stage': leaves[0]['user_stage'], + 'source_summary': {'candidate_count': sum( + int((leaf.get('source_summary') or {}).get('candidate_count') or 0) + for leaf in leaves + )}, + 'primary_action': next((leaf.get('primary_action') for leaf in leaves if leaf.get('primary_action')), None), + 'available_actions': list(dict.fromkeys( + action for leaf in leaves for action in (leaf.get('available_actions') or []) + )), + 'intake_parse_authorized': any(leaf.get('intake_parse_authorized') for leaf in leaves), + }), + }) + # [AUTHORITY] 首屏摘要与详情投影一样,以同一批文件叶子的互斥用户分组 + # 生成总数和四个状态数。此前这里只返回 total_files,前端却按 *_files + # 渲染批次概览,造成“总文件有数、四个状态全为 0”的合同断裂。 + summary_file_counts = _batch_file_counts([ + row + for rows in groups.values() + for row in rows + ]) + summary_projection = { + 'projection_version': 2, + 'summary': { + 'total_tasks': sum(len(rows) for rows in groups.values()), + **summary_file_counts, + 'processing': len(groups['processing']), + 'needs_action': len(groups['failed']) + len(groups['waiting_human']), + 'completed': len(groups['completed']), + 'history': len(groups['cancelled']) + len(groups['archived']), + }, + 'focused_task_no': str(focused_task_no or '').strip() or None, + 'recent_task_no': str(recent_task_no or '').strip() or None, + 'status_groups': groups, + 'lifecycle_nodes': _batch_lifecycle_nodes([ + {'aggregate_children': task.get('aggregate_children') or []} + for rows in groups.values() + for task in rows + ]), + # 摘要与详情必须使用同一批文件的状态裁决;不能把全量待人工的会话硬编码为 idle, + # 否则聊天摘要会回退显示为“系统处理中”。 + 'ui_state': _batch_ui_state_from_items([ + row + for rows in groups.values() + for row in rows + ]), + 'output_artifacts': [], + } + return { + 'conversation_id': normalized, + 'projection_mode': 'summary', + 'conversation_processing': summary_projection, + } + + def project_conversation_processing_items( *, user_id: int, @@ -3106,6 +3907,23 @@ def project_conversation_processing_items( ) work_items: list[dict[str, Any]] = [] + # 会话缓存必须在 OT 投影前建立:OT 的 Gate/Case bundle 与 Intake 叶子共用 + # 同一批 Review、Run、Plan、Unit、Attempt、Job 事实,不能等到列表后半段才预取。 + intakes = ( + ShippingOrderIntake.query.filter( + ShippingOrderIntake.user_id == int(user_id), + ShippingOrderIntake.conversation_id == normalized, + ShippingOrderIntake.purpose == 'shipping_notice', + ) + .order_by( + ShippingOrderIntake.updated_at.desc(), + ShippingOrderIntake.created_at.desc(), + ) + .all() + ) + load_context = _conversation_projection_load_context(intakes) + previous_read_cache = db.session.info.get(_CONVERSATION_PROJECTION_READ_CACHE_KEY) + db.session.info[_CONVERSATION_PROJECTION_READ_CACHE_KEY] = load_context.read_cache # STEP 1a:会话内 OT 实体列表。代表 Run 只服务于这些真实 OT, # 必须先取得其编号,避免刚上传/仅 Intake 会话扫描全部历史 Run。 order_tasks = ( @@ -3122,21 +3940,16 @@ def project_conversation_processing_items( for task in order_tasks if str(task.task_no or '').strip() ] - # [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则 - # (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task, - # 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。 - legacy_seed_runs: list[ShippingOrderProcessingRun] = [] + # STEP 1a:正式读模型只选择未被替代且属于当前 OT 的 Run。代表项选择规则归本模块 + # 所有,禁止依赖已经下线的 conversation_processing_projection 私有常量。 + representative_runs: list[ShippingOrderProcessingRun] = [] if order_task_nos: - from app.services.shipping_notice.conversation_processing_projection import ( - _RIGHT_PANEL_RUN_STATUSES, - ) - legacy_seed_runs = ( + representative_runs = ( ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.user_id == int(user_id), ShippingOrderProcessingRun.conversation_id == normalized, ShippingOrderProcessingRun.superseded_by_run_id.is_(None), ShippingOrderProcessingRun.user_task_no.in_(order_task_nos), - ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)), ) .order_by( ShippingOrderProcessingRun.last_activity_at.desc().nullslast(), @@ -3145,7 +3958,7 @@ def project_conversation_processing_items( .all() ) latest_by_task: dict[str, ShippingOrderProcessingRun] = {} - for seed_run in legacy_seed_runs: + for seed_run in representative_runs: seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip() if seed_task_no and seed_task_no not in latest_by_task: latest_by_task[seed_task_no] = seed_run @@ -3196,7 +4009,7 @@ def project_conversation_processing_items( task_no = str(order_task.task_no or '').strip() if not task_no: continue - # 选 Run 优先级:A) 旧投影等价代表 → B) OT 自身 extraction_run_id → C) 原 fallback + # 选 Run 优先级:A) 当前 OT 的最新正式代表 → B) OT 自身 extraction_run_id → C) 原 fallback run: ShippingOrderProcessingRun | None = latest_by_task.get(task_no) if run is None and order_task.extraction_run_id: run = runs_by_id.get(int(order_task.extraction_run_id)) @@ -3254,7 +4067,7 @@ def project_conversation_processing_items( invalidated_from_stage = None if not stage_label_key and stage == 'order_creating': stage_label_key = 'waiting_system_start' - legacy_actions_min: list[str] = [] + authorized_actions_min: list[str] = [] notice_no_min = _notice_no_for_order_task(order_task) has_formal_ot_min = bool( getattr(order_task, 'shipping_notice_id', None) is not None @@ -3285,7 +4098,7 @@ def project_conversation_processing_items( getattr(order_task, 'updated_at', None) ) or '', 'current_gate': None, - 'available_actions': legacy_actions_min, + 'available_actions': authorized_actions_min, 'source_summary': { 'filename': None, 'document_count': 0, @@ -3293,7 +4106,7 @@ def project_conversation_processing_items( }, 'child_order_tasks': [], }, - legacy_actions=legacy_actions_min, + authorized_actions=authorized_actions_min, invalidated_from_stage=invalidated_from_stage, excel_ready=excel_ready, ) @@ -3318,71 +4131,77 @@ def project_conversation_processing_items( and str(item.get('intake_no') or '').strip() ) } - intakes = ( - ShippingOrderIntake.query.filter( - ShippingOrderIntake.user_id == int(user_id), - ShippingOrderIntake.conversation_id == normalized, - ShippingOrderIntake.purpose == 'shipping_notice', - ) - .order_by( - ShippingOrderIntake.updated_at.desc(), - ShippingOrderIntake.created_at.desc(), - ) - .all() - ) - submission_cache: dict[int, ShippingOrderSubmission | None] = {} - asset_cache: dict[int, FileAsset | None] = {} - for intake in intakes: - if not _should_emit_intake_work_item( - intake, - linked_intake_ids=linked_intake_ids, - represented_eml_intake_nos=represented_eml_intake_nos, - ): - continue - submission = None - if intake.order_submission_id: - sid = int(intake.order_submission_id) - if sid not in submission_cache: - submission_cache[sid] = db.session.get(ShippingOrderSubmission, sid) - submission = submission_cache[sid] - asset = None - if intake.asset_id: - aid = int(intake.asset_id) - if aid not in asset_cache: - asset_cache[aid] = db.session.get(FileAsset, aid) - asset = asset_cache[aid] - work_items.append( - project_intake_work_item(intake, submission=submission, asset=asset) - ) + try: + submission_cache: dict[int, ShippingOrderSubmission | None] = {} + asset_cache: dict[int, FileAsset | None] = {} + for intake in intakes: + if not _should_emit_intake_work_item( + intake, + linked_intake_ids=linked_intake_ids, + represented_eml_intake_nos=represented_eml_intake_nos, + ): + continue + submission = None + if intake.order_submission_id: + sid = int(intake.order_submission_id) + if sid not in submission_cache: + submission_cache[sid] = db.session.get(ShippingOrderSubmission, sid) + submission = submission_cache[sid] + asset = None + if intake.asset_id: + aid = int(intake.asset_id) + if aid not in asset_cache: + asset_cache[aid] = db.session.get(FileAsset, aid) + asset = asset_cache[aid] + work_items.append( + project_intake_work_item( + intake, + submission=submission, + asset=asset, + load_context=load_context, + ) + ) - # 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前, - # 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。 - work_items = _aggregate_eml_order_task_work_items(work_items) - # [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用 - # 同一份“当前文件代表项”展示 DTO。否则前端兼容消费者若从顶层 work_items - # 读取,会重新看到历史 Run/旧失败项,绕过批次统计已经完成的互斥裁决。 - # 该函数保留 EML 父容器,只裁掉其历史附件,不能以叶子项直接替换父卡。 - work_items = _display_work_items_from_current_files(work_items) - work_items = [_with_processing_ui_state(item) for item in work_items] + # 同一 EML Intake 只作为一个用户工作项返回。聚合必须发生在 work_items 返回前, + # 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。 + work_items = _aggregate_eml_order_task_work_items( + work_items, + load_context=load_context, + ) + # [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用 + # 同一份“当前文件代表项”展示 DTO。否则前端兼容消费者若从顶层 work_items + # 读取,会重新看到历史 Run/旧失败项,绕过批次统计已经完成的互斥裁决。 + # 该函数保留 EML 父容器,只裁掉其历史附件,不能以叶子项直接替换父卡。 + work_items = _display_work_items_from_current_files(work_items) + work_items = [_with_processing_ui_state(item) for item in work_items] - recent_override = str(recent_task_no or '').strip() or None - rebuilt = _conversation_processing_from_work_items( - work_items, - focused_task_no=focused_override, - recent_task_no=recent_override, - ) - # 写路径元数据:保留提交决策与追加计数,供前端卡片提示。 - if recent_decision is not None: - rebuilt['recent_decision'] = recent_decision - if recent_append_count is not None: - rebuilt['recent_append_count'] = recent_append_count + recent_override = str(recent_task_no or '').strip() or None + rebuilt = _conversation_processing_from_work_items( + work_items, + focused_task_no=focused_override, + recent_task_no=recent_override, + ) + # 写路径元数据:保留提交决策与追加计数,供前端卡片提示。 + if recent_decision is not None: + rebuilt['recent_decision'] = recent_decision + if recent_append_count is not None: + rebuilt['recent_append_count'] = recent_append_count - return { - 'conversation_id': normalized, - 'work_items': work_items, - 'conversation_processing': rebuilt, - 'conversation_allowed_actions': [], - } + # 内部聚合依赖顶层动作中间表示;仅在响应边界剥离,既不会破坏当前文件 + # 代表项/EML 聚合,也不会再次暴露两套前端动作合同。 + public_work_items = _strip_legacy_action_fields_for_response(work_items) + public_rebuilt = _strip_legacy_action_fields_for_response(rebuilt) + return { + 'conversation_id': normalized, + 'work_items': public_work_items, + 'conversation_processing': public_rebuilt, + 'conversation_allowed_actions': [], + } + finally: + if previous_read_cache is None: + db.session.info.pop(_CONVERSATION_PROJECTION_READ_CACHE_KEY, None) + else: + db.session.info[_CONVERSATION_PROJECTION_READ_CACHE_KEY] = previous_read_cache def get_shipping_processing_work_item( diff --git a/backend/app/services/shipping_notice/shipping_turn_context.py b/backend/app/services/shipping_notice/shipping_turn_context.py index cc0dbe70..b3e50341 100644 --- a/backend/app/services/shipping_notice/shipping_turn_context.py +++ b/backend/app/services/shipping_notice/shipping_turn_context.py @@ -1,7 +1,7 @@ """ services/shipping_notice/shipping_turn_context.py -用途:货代 Chat Turn 领域上下文解析(task_no / batch_no 等 refs 键名约定)。 +用途:货代 Chat Turn 领域上下文解析(task_no refs 键名约定)。 依赖:turn_context.TurnContext。 逻辑:chat_action_handlers 通过本模块解析货代专属锚点;平台 turn_context 不感知这些键名。 """ @@ -14,12 +14,9 @@ from app.services.chat.turn_context import TurnContext # 与 agent_runtime_context.refs 及前端 shipping 上下文对齐的键名约定。 SHIPPING_REF_TASK_NO = "task_no" -SHIPPING_REF_BATCH_NO = "batch_no" _TASK_PAYLOAD_KEYS = ("task_no", "taskNo", "task_id", "taskId") _TASK_REF_KEYS = (SHIPPING_REF_TASK_NO, "taskNo", "task_id", "taskId") -_BATCH_PAYLOAD_KEYS = ("batch_no", "batchNo") -_BATCH_REF_KEYS = (SHIPPING_REF_BATCH_NO, "batchNo") def _first_non_empty(values: tuple[str, ...]) -> str: @@ -57,19 +54,3 @@ def resolve_shipping_task_no(ctx: TurnContext) -> str: from_refs = _first_non_empty(tuple(ctx.refs.get(key, "") for key in _TASK_REF_KEYS)).upper() return from_refs - -def resolve_shipping_batch_no(ctx: TurnContext) -> str: - """ - 从 action payload 或 session refs 解析货代批次编号。 - - Args: - ctx: 当前 Chat Turn 上下文。 - - Returns: - batch_no 文本;无法解析时返回空串。 - """ - payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} - from_payload = _read_payload_str(payload, *_BATCH_PAYLOAD_KEYS) - if from_payload: - return from_payload - return _first_non_empty(tuple(ctx.refs.get(key, "") for key in _BATCH_REF_KEYS)) diff --git a/backend/app/services/shipping_notice/shipping_turn_helpers.py b/backend/app/services/shipping_notice/shipping_turn_helpers.py index 4b55073b..5bd031ba 100644 --- a/backend/app/services/shipping_notice/shipping_turn_helpers.py +++ b/backend/app/services/shipping_notice/shipping_turn_helpers.py @@ -3,7 +3,7 @@ services/shipping_notice/shipping_turn_helpers.py 用途:货代 Chat Turn handler 共用的 SSE 事件构造与 UI State 回写。 依赖:action_schema.TurnEvent、ui_state、query_service。 -逻辑:chat_action_handlers 与 chat_action_extended_handlers 复用本模块,避免重复 yield 逻辑。 +逻辑:Chat Turn handler 复用本模块,避免重复 yield 逻辑。 """ from __future__ import annotations @@ -11,8 +11,7 @@ from __future__ import annotations from typing import Any, Iterator from app.services.chat.action_schema import TurnEvent -from app.services.shipping_notice.query_service import get_batch_for_user -from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state +from app.services.shipping_notice.ui_state import build_task_ui_state def stream_text_events( @@ -46,43 +45,18 @@ def stream_text_events( def shipping_task_ui_state_event(task) -> TurnEvent: """单票任务 ui_state.updated 事件。""" ui_state = build_task_ui_state(task) - batch_no = None return TurnEvent( event="ui_state.updated", data={ "domain": "shipping", "task_no": task.task_no, - "batch_no": batch_no, "payload": { "task_no": task.task_no, - "batch_no": batch_no, "ui_state": ui_state, }, }, ) -def shipping_batch_ui_state_event(batch_no: str, user_id: int) -> TurnEvent | None: - """批次级 ui_state.updated 事件。""" - batch = get_batch_for_user(batch_no, user_id) - if batch is None: - return None - batch_state = build_batch_ui_state(batch) - focus_task_no = str(batch_state.get("current_focus_task_no") or "").strip() - return TurnEvent( - event="ui_state.updated", - data={ - "domain": "shipping", - "batch_no": batch_no, - "task_no": focus_task_no or None, - "payload": { - "batch_no": batch_no, - "batch_ui_state": batch_state, - "task_no": focus_task_no or None, - }, - }, - ) - - def tool_result_message(result: dict[str, Any]) -> str: return str(result.get("message") or "").strip() diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index 78c7885d..3496cf91 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/task_candidate_reconciliation.py 用途:将 Candidate 订单行对账到既有 Task(字段级自动补齐 / 冲突落库)。 依赖:po_number、reservation_id、动态订单 FieldValue、task_field_conflict_service、state_machine。 -逻辑:batch_from_intakes / open_existing 路径调用;仅安全态任务可自动补齐。 +逻辑:open_existing 对账路径调用;仅安全态任务可自动补齐。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/task_retry_decision_service.py b/backend/app/services/shipping_notice/task_retry_decision_service.py deleted file mode 100644 index c2134420..00000000 --- a/backend/app/services/shipping_notice/task_retry_decision_service.py +++ /dev/null @@ -1,1036 +0,0 @@ -""" -services/shipping_notice/task_retry_decision_service.py - -用途:正式 OT「重试」统一决策与执行入口(任务级 / 行级 / 对话级 / auto-progress 兼容)。 -依赖:inventory_source_gate、inventory_workflow、fulfillment_workflow.match_inventory、 - progress_workflow.auto_progress、fulfillment_audit、ShippingNotice / - ShippingNoticeLineInventoryMatch。 -逻辑:用户只表达重试意图;本服务按最新事实选择 resolve_source / fetch_inventory / - rematch / needs_human / noop / failed,或非库存阶段委托 auto_progress; - 禁止对话级与任务级分叉实现;幂等键与审计字段一并返回。 -""" - -from __future__ import annotations - -import logging -from typing import Any, Literal - -from app import db -from app.core.errors import AppError, NotFoundError, ValidationError -from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch - -_LOGGER = logging.getLogger(__name__) - -Scope = Literal['task', 'line'] - -ACTION_RESOLVE_SOURCE = 'resolve_source' -ACTION_FETCH_INVENTORY = 'fetch_inventory' -ACTION_REMATCH = 'rematch' -ACTION_NEEDS_HUMAN = 'needs_human' -ACTION_NOOP = 'noop' -ACTION_FAILED = 'failed' -ACTION_AUTO_PROGRESS = 'auto_progress' - -STATUS_RUNNING = 'running' -STATUS_NEEDS_HUMAN = 'needs_human' -STATUS_COMPLETED = 'completed' -STATUS_FAILED = 'failed' - -PH_RPA_PENDING = 'rpa_pending' -PH_UPLOAD_PENDING = 'upload_rpa_pending' -PH_UPLOAD_FAILED = 'upload_rpa_failed' - - -def _request_formal_gate_action( - *, - task: ShippingNotice, - action_code: str, - user_id: int, - idempotency_key: str, - trigger: str, - line_key: str | None = None, -) -> dict[str, Any]: - """将外部重试意图提交给正式 20-Gate Recovery/ProcessGate 编排。 - - 外部入口只负责定位当前正式 Gate 和动作;库存准备、匹配等旧函数仅允许 - 由 ``process_gate_executor`` 通过内部分派标记调用。 - """ - from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate - 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 - from app.models import ShippingProcessExecution, ShippingProcessGate - - execution = None - current_id = getattr(task, 'active_process_execution_id', None) - if current_id: - execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first() - if execution is not None and str(execution.status or '').strip().lower() == 'superseded': - execution = None - if execution is None: - execution = ensure_execution_for_workflow_version( - task_id=int(task.id), actor_type='user', actor_id=int(user_id), - start_gate_code=determine_formal_start_gate(task), - ) - task.active_process_execution_id = int(execution.id) - db.session.flush() - gate = ShippingProcessGate.query.filter_by( - execution_id=int(execution.id), gate_code=str(execution.current_gate_code or '').strip(), - ).first() - if gate is None: - raise ValidationError('Current formal process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') - - requested = str(action_code or '').strip() - if requested == 'retry_inventory_from_matching' and gate.gate_code != 'inventory_sufficiency': - requested = 'retry_inventory_matching' - payload: dict[str, Any] = {'trigger': trigger} - if line_key: - payload['line_key'] = str(line_key) - result = request_gate_action( - execution_no=str(execution.execution_no), gate_code=str(gate.gate_code), - action_code=requested, expected_gate_version=int(gate.evaluation_version), - idempotency_key=str(idempotency_key), actor_type='user', actor_id=int(user_id), - payload=payload, - ) - return { - 'status': 'running' if result.get('dispatch') in {'async_job', 'sync'} else 'failed', - 'action': action_code, - 'task_id': task.task_no, - 'job_id': result.get('job_id'), - 'attempt_id': (result.get('attempt') or {}).get('id'), - 'execution_no': result.get('execution_no'), - 'gate_code': result.get('gate_code'), - 'message': '已提交正式 20-Gate 恢复动作', - } - - -def retry_task_with_decision( - *, - task_no: str, - user_id: int, - scope: Scope = 'task', - line_key: str | None = None, - reason: str | None = None, - trigger: str = 'user_retry', - continue_auto_progress: bool = False, -) -> dict[str, Any]: - """ - 统一重试决策并执行。 - - 核心逻辑:加锁读取任务事实 → 决策树 → 执行既有库存/推进处理器 → 写审计 → 返回统一结果。 - - Args: - task_no: 正式任务号。 - user_id: 操作人。 - scope: task=整单;line=单行。 - line_key: scope=line 时必填。 - reason: 用户/系统原因。 - trigger: 调用方标识(user_retry / conversation_retry / system_auto_progress)。 - continue_auto_progress: True 时库存节点通过后继续 auto_progress(兼容调度入口)。 - - Returns: - 含 action/status/retryable/decision_version/snapshot_id/job_id/idempotency_key 等。 - - Raises: - ValidationError / NotFoundError / AppError。 - """ - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - from app.services.shipping_notice.query_service import get_task_for_user - - normalized_task = str(task_no or '').strip() - if not normalized_task: - raise ValidationError('task_no is required') - scope_norm: Scope = 'line' if str(scope or '').strip().lower() == 'line' else 'task' - line = str(line_key or '').strip() or None - if scope_norm == 'line' and not line: - raise ValidationError('line_key is required for line scope') - - task = get_task_for_user(normalized_task, int(user_id)) - if task is None: - raise NotFoundError('Not found') - - decision_version = int(getattr(task, 'order_data_version', None) or 1) - # 题2B:先检查最新逐源 Attempt 活跃状态(不再依赖 pending_human_reason 滞后字段),避免误判 - latest_active = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) - decided = _decide(task, scope=scope_norm, line_key=line, latest_active=latest_active) - action = str(decided.get('action') or ACTION_NOOP) - idempotency_key = _build_idempotency_key( - task=task, - action=action, - decision_version=decision_version, - line_key=line, - ) - - # [STEP] 幂等:逐源有 queued/running 且本次动作是 fetch/rematch/auto_progress → 直接回放 already_running。 - # 按实际冻结源过滤(仅判断属于 required_frozen_sources 的 pending Attempt)。 - need_inv_rpa = action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS} - if need_inv_rpa: - pending_required = bool( - set(latest_active['pending_source_codes']) & set(latest_active['required_frozen_sources'] or []) - ) - if pending_required or bool(latest_active['gate_attempt_active']): - result = _result_payload( - task=task, - action=ACTION_NOOP, - status=STATUS_RUNNING, - retryable=False, - reason_code='already_running', - decision_version=decision_version, - idempotency_key=idempotency_key, - idempotent_replay=True, - message='已有库存处理在运行', - ) - _audit_decision( - task=task, - user_id=int(user_id), - scope=scope_norm, - line_key=line, - trigger=trigger, - reason=reason, - result=result, - ) - return result - - executed = _execute( - task=task, - user_id=int(user_id), - decided=decided, - continue_auto_progress=bool(continue_auto_progress), - decision_version=decision_version, - idempotency_key=idempotency_key, - line_key=line, - trigger=trigger, - ) - _audit_decision( - task=task, - user_id=int(user_id), - scope=scope_norm, - line_key=line, - trigger=trigger, - reason=reason, - result=executed, - ) - try: - db.session.commit() - except Exception: # noqa: BLE001 - db.session.rollback() - _LOGGER.exception('task retry decision commit failed task_no=%s', normalized_task) - raise - return executed - - -def decide_retry_action_only( - task: ShippingNotice, - *, - scope: Scope = 'task', - line_key: str | None = None, -) -> dict[str, Any]: - """ - 只读决策(供投影 / 测试);不执行副作用。 - - Returns: - ``{action, reason_code, retryable, ...}``。 - """ - return _decide(task, scope=scope, line_key=line_key) - - -def _decide( - task: ShippingNotice, - *, - scope: Scope, - line_key: str | None, - latest_active: dict[str, Any] | None = None, -) -> dict[str, Any]: - """按冻结优先级计算 RetryDecision。 - - 【retryable 语义】:表示当前阻塞可通过触发 retry 操作来尝试推进。 - - true:resolve_source / fetch_inventory / rematch 等系统可恢复动作 - - false:running/queued(已在执行)、needs_human(需人工决策)、completed/cancelled(终态) - """ - from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable - - pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower() - # 题2B:统一直接用入参 latest_active(调用方已查逐源 Attempt);无入参时回落旧实现 - active = latest_active if isinstance(latest_active, dict) else ( - summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) - ) - - lifecycle_status = str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() - if lifecycle_status in {'voided', 'archived', 'deleted'} or upload_status in {'uploaded', 'succeeded', 'success'}: - return { - 'action': ACTION_NOOP, - 'status': STATUS_COMPLETED, - 'retryable': False, - 'reason_code': 'already_completed', - } - # 库存 RPA 是否运行以逐源 Attempt 为准;pending_human_reason 可能在失败后残留。 - if pending == PH_UPLOAD_PENDING: - return { - 'action': ACTION_NOOP, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': 'already_running', - } - # task 整单 running(仅 scope=task 模式 & 非 line 单独 rematch 场景可通过(见题3B:line 单独决策里处理 running 不阻塞) - if scope != 'line' and ( - active.get('active_attempt_count', 0) > 0 - or bool(active.get('gate_attempt_active')) - ): - return { - 'action': ACTION_NOOP, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': 'already_running', - } - latest_statuses = { - str(item.get('status') or '').strip().lower() - for item in (active.get('latest_attempts') or {}).values() - } - if scope != 'line' and pending == PH_RPA_PENDING and latest_statuses <= {'', 'not_started'}: - return { - 'action': ACTION_NOOP, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': 'already_running', - } - if pending == PH_UPLOAD_FAILED: - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'upload_rpa_failed', - } - - if scope == 'line' and line_key: - return _decide_for_line(task, line_key=line_key, latest_active=active) - if not is_inventory_source_stable(task): - status = str(getattr(task, 'inventory_source_status', None) or '').strip().lower() - if status in {'ambiguous', 'candidates_frozen', 'conflicted', 'unresolved', ''}: - # 多候选 / 客户未指定:不得自动选源进 RPA。 - codes = _frozen_or_candidate_codes(task) - if status == 'conflicted': - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'inventory_source_candidates_need_human', - } - # resolve_source:单一候选或歧义已人工消除 → 可通过重试自动推进 - return { - 'action': ACTION_RESOLVE_SOURCE, - 'status': STATUS_RUNNING, - 'retryable': True, - 'reason_code': 'inventory_source_unstable', - } - - has_lines = bool(getattr(task, 'inventory_lines_json', None)) - snapshot_id = getattr(task, 'inventory_snapshot_id', None) - if not has_lines and not snapshot_id: - # fetch_inventory:无有效快照 → 可重试复用文件或触发 RPA - return { - 'action': ACTION_FETCH_INVENTORY, - 'status': STATUS_RUNNING, - 'retryable': True, - 'reason_code': 'inventory_snapshot_missing', - } - - # 有快照/明细但匹配未完成或失败 → rematch;短缺 → needs_human。 - match_hint = _task_match_hint(task) - if match_hint.get('needs_human'): - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': match_hint.get('reason_code') or 'inventory_shortage', - } - if match_hint.get('needs_rematch'): - # rematch:有有效快照但匹配未完成或执行失败 → 可重试匹配 - return { - 'action': ACTION_REMATCH, - 'status': STATUS_RUNNING, - 'retryable': True, - 'reason_code': 'inventory_match_incomplete', - } - - # 非库存阻断:委托现有 auto_progress 推进后续阶段。 - return { - 'action': ACTION_AUTO_PROGRESS, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': None, - } - - -def _decide_for_line( - task: ShippingNotice, - *, - line_key: str, - latest_active: dict[str, Any] | None = None, -) -> dict[str, Any]: - """ - 行级决策(题3B):仅该行需要 fetch_inventory(缺快照)时才按整单 RPA running 互斥; - 若已有 inventory_snapshot_id 存在且该行未完成,直接放行 ACTION_REMATCH, - 不因为其他无关源的 queued/running 阻塞(避免"行A RPA 跑时,行B 明明有快照也不能重匹配"的误判)。 - - 题10A:行 → 依赖库存源映射优先级: - build_eligibility.line_projections[i].candidate_inventory_source_codes 优先, - 为空时回退到任务级冻结源 required_frozen_sources。 - """ - from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable - from app.services.shipping_notice.line_inventory_match_projection import ( - project_line_inventory_view, - project_line_retryable, - ) - - active = latest_active if isinstance(latest_active, dict) else ( - summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) - ) - if not is_inventory_source_stable(task): - return { - 'action': ACTION_RESOLVE_SOURCE, - 'status': STATUS_RUNNING, - 'retryable': True, - 'reason_code': 'inventory_source_unstable', - } - - row = ( - ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id), line_key=str(line_key)) - .order_by(ShippingNoticeLineInventoryMatch.id.desc()) - .first() - ) - fact = { - 'match_result': getattr(row, 'match_result', None) if row else None, - 'inventory_status': getattr(row, 'inventory_status', None) if row else 'preparing', - 'available_qty': getattr(row, 'available_qty', None) if row else None, - 'required_qty': getattr(row, 'required_qty', None) if row else None, - 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None) if row else None, - 'inventory_source_code': getattr(row, 'inventory_source_code', None) if row else None, - 'matched_at': getattr(row, 'matched_at', None) if row else None, - 'matching_rule_version': getattr(row, 'matching_rule_version', None) if row else None, - 'detail_json': dict(getattr(row, 'detail_json', None) or {}) if row else {}, - } - # 题10A:先尝试从 build_eligibility 读行候选源(优先),缺省时用任务冻结源作为 line_dependent_codes。 - line_dependent_codes = _line_dependent_inventory_source_codes(task, line_key) - if not line_dependent_codes: - line_dependent_codes = list(active.get('required_frozen_sources') or []) - # 行级 fetch running 判断:仅按 line_dependent_codes & pending_source_codes 交集非空时才算 already_running, - # 或 Gate Attempt 全局在 running。 - inv_running_for_line = bool(set(line_dependent_codes) & set(active.get('pending_source_codes') or [])) - line_running_flag = inv_running_for_line or bool(active.get('gate_attempt_active')) - - view = project_line_inventory_view( - has_formal_ot=True, - fact=fact, - required_qty=fact.get('required_qty'), - stored_line_status=None, - decision_source=None, - can_fulfill_complete_line=False, - inventory_rpa_running=line_running_flag, - ) - user_status = str(view.get('user_line_status') or '') - if user_status == 'source_conflict': - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'inventory_shortage' if user_status == 'shortage' else 'inventory_source_conflict', - } - if user_status == 'shortage': - return { - 'action': ACTION_NEEDS_HUMAN, - 'status': STATUS_NEEDS_HUMAN, - 'retryable': False, - 'reason_code': 'inventory_shortage', - } - if not project_line_retryable( - inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []), - user_line_status=user_status, - inventory_rpa_running=line_running_flag, - ): - return { - 'action': ACTION_NOOP, - 'status': STATUS_COMPLETED, - 'retryable': False, - 'reason_code': 'already_completed', - } - inv_actions = set(view.get('inventory_allowed_actions') or []) - if 'retry_inventory_matching' in inv_actions and view.get('inventory_snapshot_id'): - # 题3B:快照已存在,直接放行 REMATCH,不被其他行/源的 RPA running 阻塞 - return { - 'action': ACTION_REMATCH, - 'status': STATUS_RUNNING, - 'retryable': True, - 'reason_code': 'inventory_match_incomplete', - 'line_key': line_key, - } - # 缺快照,需要 fetch_inventory:如果行依赖的源正好在 running,就阻塞 already_running - if inv_running_for_line or bool(active.get('gate_attempt_active')): - return { - 'action': ACTION_NOOP, - 'status': STATUS_RUNNING, - 'retryable': False, - 'reason_code': 'already_running', - 'line_key': line_key, - } - return { - 'action': ACTION_FETCH_INVENTORY, - 'status': STATUS_RUNNING, - 'retryable': True, - 'reason_code': 'inventory_snapshot_missing', - 'line_key': line_key, - } - - -def _line_dependent_inventory_source_codes(task: ShippingNotice, line_key: str) -> list[str]: - """题10A:行依赖库存源映射(build_eligibility.line_projections[i].candidate_inventory_source_codes 优先。""" - try: - from app.services.shipping_notice.order_build_eligibility_service import ( - assess_order_build_eligibility as build_fn, - ) - - eligibility = build_fn(task, mode='case_review') - except Exception: # noqa: BLE001 - eligibility = None - out: list[str] = [] - # 常见结构:{ line_projections: [ { line_key, candidate_inventory_source_codes: [] } ] - if isinstance(eligibility, dict): - projections = eligibility.get('line_projections') or eligibility.get('build_eligibility.line_projections') or [] - elif eligibility and hasattr(eligibility, '__iter__'): - projections = getattr(eligibility, 'line_projections') or [] - else: - projections = [] - key = str(line_key or '').strip() - for p in (projections or []): - p_line = str( - p.get('line_key') if isinstance(p, dict) else getattr(p, 'line_key', None) - or '' - ) - if p_line != key: - continue - codes = ( - p.get('candidate_inventory_source_codes') if isinstance(p, dict) - else getattr(p, 'candidate_inventory_source_codes', None) - ) - for code in (codes or []): - c = str(code or '').strip().upper() - if c and c not in out: - out.append(c) - return out - - -def _execute( - *, - task: ShippingNotice, - user_id: int, - decided: dict[str, Any], - continue_auto_progress: bool, - decision_version: int, - idempotency_key: str, - line_key: str | None, - trigger: str = 'user_retry', -) -> dict[str, Any]: - """执行决策动作并映射统一响应。""" - from app.services.shipping_notice.inventory_source_gate import ( - adjudicate_and_apply_inventory_source, - ensure_inventory_source_review_state, - ) - - action = str(decided.get('action') or ACTION_NOOP) - # 所有重试动作(含库存匹配 REMATCH)共用同一触发来源;不能只在 FETCH 分支内初始化。 - trigger_norm = str(trigger or '').strip().lower() or 'user_retry' - base_kwargs = { - 'task': task, - 'decision_version': decision_version, - 'idempotency_key': idempotency_key, - 'snapshot_id': getattr(task, 'inventory_snapshot_id', None), - 'source_code': str(getattr(task, 'inventory_source_code', None) or '') or None, - } - - if action == ACTION_NOOP: - return _result_payload( - action=ACTION_NOOP, - status=str(decided.get('status') or STATUS_COMPLETED), - retryable=False, - reason_code=str(decided.get('reason_code') or 'already_completed'), - message='无需重试', - **base_kwargs, - ) - - if action == ACTION_NEEDS_HUMAN: - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code=str(decided.get('reason_code') or 'needs_human'), - message='当前需要人工处理', - **base_kwargs, - ) - - try: - if action == ACTION_RESOLVE_SOURCE: - adjudicate_and_apply_inventory_source(task) - ensure_inventory_source_review_state(task) - db.session.flush() - from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable - if not is_inventory_source_stable(task): - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code='inventory_source_candidates_need_human', - message='库存源未稳定,需要人工确认', - **base_kwargs, - ) - # 源已稳定:继续获取库存。 - action = ACTION_FETCH_INVENTORY - - if action == ACTION_FETCH_INVENTORY: - # 库存 RPA 的正式前置事实是订单快照。历史任务可能已完成解析但未成功冻结, - # 会话重试必须先补做一次冻结;冻结门禁失败时返回 needs_human,禁止伪造 Trigger。 - if not getattr(task, 'order_snapshot_id', None) and isinstance(task, ShippingNotice): - try: - from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot - - freeze_order_snapshot( - task, - actor_id=int(user_id), - expected_order_data_version=decision_version, - freeze_mode='manual', - ) - db.session.flush() - except AppError as freeze_err: - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code=str(getattr(freeze_err, 'code', None) or 'order_freeze_not_ready'), - message='订单快照尚未冻结,无法进入库存 RPA。', - **base_kwargs, - ) - formal = _request_formal_gate_action( - task=task, - action_code='retry_inventory_preparation', - user_id=int(user_id), - idempotency_key=idempotency_key, - trigger=trigger_norm, - line_key=line_key, - ) - return _map_tool_result(formal, action=ACTION_FETCH_INVENTORY, base_kwargs=base_kwargs, message='已提交库存获取') - - if action == ACTION_REMATCH: - # 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行; - # 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。 - norm_line_key = str(line_key or '').strip() - formal = _request_formal_gate_action( - task=task, - action_code='retry_inventory_from_matching', - user_id=int(user_id), - idempotency_key=idempotency_key, - trigger=trigger_norm, - line_key=norm_line_key or None, - ) - return _map_tool_result(formal, action=ACTION_REMATCH, base_kwargs=base_kwargs, message='已提交库存匹配') - - # ACTION_AUTO_PROGRESS 或 continue - return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) - except AppError as err: - # 下游 flush/写库失败会使 PostgreSQL 事务进入 aborted;必须先清理, - # 才能让调用方继续写本次失败决策审计。 - db.session.rollback() - return _result_payload( - action=ACTION_FAILED, - status=STATUS_FAILED, - retryable=False, - reason_code=str(getattr(err, 'code', None) or 'SHIPPING.RETRY_FAILED'), - message=str(getattr(err, 'message', None) or err), - **base_kwargs, - ) - except Exception as exc: # noqa: BLE001 - _LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action) - # 同上:避免后续 _audit_decision 查询审计哈希链时触发 - # InFailedSqlTransaction,掩盖真正的业务失败。 - db.session.rollback() - return _result_payload( - action=ACTION_FAILED, - status=STATUS_FAILED, - retryable=False, - reason_code='SHIPPING.RETRY_FAILED', - message=str(exc)[:500], - **base_kwargs, - ) - - -def _run_auto_progress( - task: ShippingNotice, - *, - user_id: int, - base_kwargs: dict[str, Any], -) -> dict[str, Any]: - """委托现有 auto_progress 推进非库存/后续阶段。""" - from app.services.shipping_notice import tools as shipping_tools - - result = shipping_tools.auto_progress({ - 'task_id': task.task_no, - 'source': 'workspace_api', - 'operator_id': int(user_id), - 'actor_id': int(user_id), - '_trusted_user_id': int(user_id), - 'trigger': 'task_retry_decision', - }) - return _map_tool_result( - result, - action=ACTION_AUTO_PROGRESS, - base_kwargs=base_kwargs, - message='已提交自动推进', - ) - - -def _map_tool_result( - tool_result: dict[str, Any] | None, - *, - action: str, - base_kwargs: dict[str, Any], - message: str, -) -> dict[str, Any]: - """将既有 tool 响应映射为统一 Retry 结果。""" - status_raw = str((tool_result or {}).get('status') or '').strip().lower() - if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload', 'blocked_manual'}: - return _result_payload( - action=ACTION_NEEDS_HUMAN, - status=STATUS_NEEDS_HUMAN, - retryable=False, - reason_code=str( - (tool_result or {}).get('error_code') - or (tool_result or {}).get('reason_code') - or (tool_result or {}).get('blocking_reason_code') - or 'needs_human' - ), - message=str((tool_result or {}).get('message') or '当前需要人工处理'), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed', 'blocked_retryable'}: - return _result_payload( - action=ACTION_FAILED, - status=STATUS_FAILED, - retryable=False, - reason_code=str( - (tool_result or {}).get('error_code') - or (tool_result or {}).get('reason_code') - or (tool_result or {}).get('blocking_reason_code') - or status_raw - ), - message=str((tool_result or {}).get('message') or '自动处理失败'), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - if status_raw in {'ok', 'completed', 'succeeded'}: - return _result_payload( - action=action, - status=STATUS_COMPLETED, - retryable=False, - reason_code=None, - message=str((tool_result or {}).get('message') or message), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - # running / queued / processing - return _result_payload( - action=action, - status=STATUS_RUNNING, - retryable=False, - reason_code=None, - message=str((tool_result or {}).get('message') or message), - job_id=(tool_result or {}).get('job_id'), - **base_kwargs, - ) - - -def _result_payload( - *, - task: ShippingNotice, - action: str, - status: str, - retryable: bool, - reason_code: str | None, - decision_version: int, - idempotency_key: str, - message: str, - snapshot_id: Any = None, - source_code: str | None = None, - job_id: Any = None, - idempotent_replay: bool = False, -) -> dict[str, Any]: - """组装统一响应。""" - return { - 'task_no': task.task_no, - 'idempotent_replay': bool(idempotent_replay), - 'action': action, - 'stage': None, - 'status': status, - 'retryable': bool(retryable), - 'job_id': job_id, - 'reason_code': reason_code, - 'message': message, - 'decision_version': int(decision_version), - 'snapshot_id': int(snapshot_id) if snapshot_id not in (None, '') else None, - 'source_code': source_code, - 'idempotency_key': idempotency_key, - } - - -def _build_idempotency_key( - *, - task: ShippingNotice, - action: str, - decision_version: int, - line_key: str | None, -) -> str: - """按冻结约定生成业务幂等键。""" - task_no = str(task.task_no) - source = str(getattr(task, 'inventory_source_code', None) or 'NA').strip().upper() or 'NA' - snapshot = getattr(task, 'inventory_snapshot_id', None) or 'none' - if action == ACTION_FETCH_INVENTORY: - key = f'inventory-fetch:{task_no}:{source}:v{decision_version}' - elif action == ACTION_REMATCH: - key = f'inventory-match:{task_no}:{snapshot}:v{decision_version}' - elif action == ACTION_RESOLVE_SOURCE: - key = f'inventory-source:{task_no}:v{decision_version}' - else: - key = f'auto-progress:{task_no}:v{decision_version}' - if line_key: - key = f'{key}:line:{line_key}' - return key - - -def _is_inventory_rpa_active(task: ShippingNotice) -> bool: - """库存 RPA 是否仍在等待(旧兼容实现,等价于 summary.active_attempt_count > 0)。""" - return summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)['active_attempt_count'] > 0 - - -def summarize_inventory_rpa_latest_attempts( - task: ShippingNotice, - *, - include_gate_status: bool = False, -) -> dict[str, Any]: - """ - 汇总逐源库存 RPA Attempt 最新状态(题2B:按冻结源过滤,不再依赖 pending_human_reason 滞后字段)。 - - 【AI 触发时机】:Projection retryable/status 计算、重试决策幂等守卫、already_running 返回时统一读取。 - - 核心逻辑: - [STEP 1] 读取 required_frozen_sources(= Task 级 inventory_source_code 单源 或 T3 冻结多源列表) - [STEP 2] 对每个 required source 查最新 attempt;汇总 prepared / pending / failed / exhausted。 - [STEP 3] active_attempt_count = pending 数量;同时给出 latest_attempts 的结构化视图。 - [STEP 4] 可选 include_gate_status:补充 Process Gate Attempt 的 queued/running。 - """ - from app.models import ( - Job, - ShippingProcessExecution, - ShippingProcessGate, - ShippingProcessGateAttempt, - ShippingTaskInventoryRpaAttempt, - ) - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, - ) - - task_no = str(task.task_no or '').strip() - frozen_sources: list[str] = [ - str(code) for code in (task_frozen_inventory_source_codes(task) or []) if code - ] - if not frozen_sources: - single = str(task.inventory_source_code or '').strip().upper() - if single: - frozen_sources = [single] - required_frozen_sources: list[str] = list(dict.fromkeys(frozen_sources)) - - prepared: list[str] = [] - pending: list[str] = [] - failed: list[str] = [] - exhausted: list[str] = [] - latest_attempts: dict[str, dict[str, Any]] = {} - - if task_no: - # 先一次性查出 (task_no, source_code) → 最新 attempt - query = ( - ShippingTaskInventoryRpaAttempt.query - .filter(ShippingTaskInventoryRpaAttempt.task_no == task_no) - .order_by( - ShippingTaskInventoryRpaAttempt.source_code.asc(), - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), - ) - ) - # 轻量调用方可能只提供 first();正式 ORM 使用 all() 做一次批量读取。 - rows = query.all() if hasattr(query, 'all') else [query.first()] - rows = [row for row in rows if row is not None] - latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {} - for row in rows: - key = str(getattr(row, 'source_code', None) or '').strip().upper() or None - if not key and len(required_frozen_sources) == 1: - key = required_frozen_sources[0] - if not key or key in latest_by_source: - continue - latest_by_source[key] = row - - for code in required_frozen_sources: - key = str(code or '').strip().upper() or None - if not key: - continue - att = latest_by_source.get(key) - if not att: - latest_attempts[key] = { - 'attempt_no': 0, - 'run_no': None, - 'status': 'not_started', - 'error_code': None, - 'error_message': None, - } - continue - st = str(att.status or '').strip().lower() - latest_attempts[key] = { - 'attempt_no': int(getattr(att, 'attempt_no', 0) or 0), - 'run_no': str(getattr(att, 'run_no', '') or '') or None, - 'status': st, - 'error_code': str(getattr(att, 'error_code', '') or '') or None, - 'error_message': str(getattr(att, 'error_message', '') or '') or None, - } - if st in {'queued', 'running'}: - pending.append(key) - elif st in {'succeeded', 'consumed'}: - prepared.append(key) - elif st == 'exhausted': - exhausted.append(key) - failed.append(key) - elif st in {'failed', 'trigger_write_error'}: - failed.append(key) - - active_attempt_count = len(pending) - gate_attempt_active = False - task_id = getattr(task, 'id', None) - if include_gate_status and task_id is not None: - any_active = bool( - db.session.query(ShippingProcessGateAttempt.id) - .join( - ShippingProcessGate, - ShippingProcessGateAttempt.gate_id == ShippingProcessGate.id, - ) - .join( - ShippingProcessExecution, - ShippingProcessGate.execution_id == ShippingProcessExecution.id, - ) - .join(Job, Job.id == ShippingProcessGateAttempt.job_id) - .filter(ShippingProcessGateAttempt.status.in_(('queued', 'running'))) - .filter(Job.status.in_(('queued', 'running'))) - .filter(ShippingProcessExecution.task_id == int(task_id)) - .limit(1) - .first() - ) - gate_attempt_active = any_active - if any_active and active_attempt_count <= 0: - active_attempt_count = 1 - - return { - 'task_no': task_no or None, - 'required_frozen_sources': required_frozen_sources, - 'prepared_source_codes': prepared, - 'pending_source_codes': pending, - 'failed_source_codes': failed, - 'exhausted_source_codes': exhausted, - 'active_attempt_count': int(active_attempt_count), - 'gate_attempt_active': bool(gate_attempt_active), - 'latest_attempts': latest_attempts, - } - - -def _frozen_or_candidate_codes(task: ShippingNotice) -> list[str]: - """读取冻结/候选库存源编码。""" - try: - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - return list(task_frozen_inventory_source_codes(task) or []) - except Exception: # noqa: BLE001 - return [] - - -def _task_match_hint(task: ShippingNotice) -> dict[str, Any]: - """根据行匹配事实判断是否需 rematch 或人工。""" - rows = ( - ShippingNoticeLineInventoryMatch.query - .filter_by(task_id=int(task.id)) - .order_by(ShippingNoticeLineInventoryMatch.id.desc()) - .limit(200) - .all() - ) - if not rows: - # 有库存明细但无匹配行 → 需要匹配。 - if getattr(task, 'inventory_lines_json', None) or getattr(task, 'inventory_snapshot_id', None): - return {'needs_rematch': True} - return {} - needs_rematch = False - for row in rows: - result = str(getattr(row, 'match_result', None) or '').strip().lower() - status = str(getattr(row, 'inventory_status', None) or '').strip().lower() - if result in {'not_found'} or status in {'source_conflict'}: - # 短缺/冲突:人工。 - return {'needs_human': True, 'reason_code': 'inventory_shortage' if result == 'not_found' else 'inventory_source_conflict'} - if result in {'mapping_failed', 'result_missing', 'preparing', ''} or status in {'mapping_failed', 'preparing'}: - needs_rematch = True - if needs_rematch: - return {'needs_rematch': True} - return {} - - -def _audit_decision( - *, - task: ShippingNotice, - user_id: int, - scope: Scope, - line_key: str | None, - trigger: str, - reason: str | None, - result: dict[str, Any], -) -> None: - """写对象级重试决策审计。""" - from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - - action = str(result.get('action') or ACTION_NOOP) - event_type = { - ACTION_RESOLVE_SOURCE: 'inventory_source_resolved', - ACTION_FETCH_INVENTORY: 'inventory_rpa_triggered', - ACTION_REMATCH: 'inventory_matching_started', - ACTION_AUTO_PROGRESS: 'auto_progress_retried', - ACTION_NEEDS_HUMAN: 'auto_progress_retried', - ACTION_NOOP: 'auto_progress_retried', - ACTION_FAILED: 'auto_progress_retried', - }.get(action, 'auto_progress_retried') - record_fulfillment_audit( - event_type=event_type, - aggregate_type='shipping_task', - aggregate_id=str(task.task_no), - action='retry', - actor_id=int(user_id), - task_no=str(task.task_no), - conversation_id=str(getattr(task, 'conversation_id', None) or '') or None, - owner_user_id=int(getattr(task, 'user_id', 0) or user_id), - reason_code=str(result.get('reason_code') or '') or None, - reason=str(reason or trigger)[:200], - result='success' if result.get('status') != STATUS_FAILED else 'failure', - error_code=str(result.get('reason_code') or '') if result.get('status') == STATUS_FAILED else None, - metadata={ - 'scope': scope, - 'line_key': line_key, - 'trigger': trigger, - 'previous_stage': None, - 'next_stage': result.get('stage'), - 'action': action, - 'decision_version': result.get('decision_version'), - 'snapshot_id': result.get('snapshot_id'), - 'job_id': result.get('job_id'), - 'idempotency_key': result.get('idempotency_key'), - 'status': result.get('status'), - }, - source='api', - strict=False, - ) diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 0b6a1d74..f41da291 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -21,7 +21,6 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError from app.models import ShippingNotice -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.constants import CP_TASK_EXISTS from app.services.shipping_notice.decision_workflow import submit_decision from app.services.shipping_notice.task_order_field_editor import ( @@ -37,12 +36,9 @@ from app.services.shipping_notice.reservation_gate import task_reservation_gate_ from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.query_service import ( TaskProjection, - compute_batch_process_summary, extract_task_no_from_text, get_task_by_ref, - list_sorted_batch_tasks, resolve_task_from_payload, - serialize_batch_for_tool, serialize_task as qs_serialize_task, serialize_task_for_tool, ) @@ -53,14 +49,7 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, - assert_idempotent_batch_content_matches, assert_no_exact_duplicate_notices, - build_existing_batch_tool_response, - compute_notice_items_content_fingerprint, - dedupe_notice_items_by_content_hash, - find_batch_by_create_idempotency, - handle_batch_create_integrity_error, - normalize_create_idempotency_key, ) from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.candidate_qualification_service import ( @@ -95,46 +84,6 @@ def start_task_orchestrator(task_no: str | None) -> bool: return _start(task_no) -def recompute_batch_summary(batch: Any | None) -> None: - """写路径:shipping_batches 已删除(co8),保留空操作供历史调用方兼容。""" - del batch - - -def sync_batch_after_task_change(task: ShippingNotice | None) -> None: - """任务状态变更后刷新所属批次;shipping_batches 已删除,无操作。""" - del task - - -def create_batch(payload: dict[str, Any]) -> tuple[Any, bool]: - """ - 创建或复用发货批次壳(不含 notice 解析)。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED(co8e9f0a1b2c)。 - """ - del payload - raise_shipping_batches_removed(action='tools.create_batch') - - -def _create_single_task_batch(payload: dict[str, Any]) -> Any: - """为单票任务创建标准批次容器;shipping_batches 已删除。""" - del payload - raise_shipping_batches_removed(action='tools.create_single_task_batch') - - -def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: - """ - 一次创建批次,并为每个 notice_item 创建任务;默认将字段解析延后到 Dify 画布。 - 【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。 - - Raises: - AppError: HTTP 410 SHIPPING.BATCHES_REMOVED(co8e9f0a1b2c)。 - """ - del payload - raise_shipping_batches_removed(action='tools.create_batch_tasks') - - def create_task(payload: dict[str, Any]) -> dict[str, Any]: """ 创建单个发货任务,或复用当前会话里已存在的进行中任务。 @@ -793,7 +742,6 @@ def replace_task_notice( extra={"warnings": cleaned_warnings}, ) log_task_event(task, "notice_replace_extract_failed", {"warnings": cleaned_warnings}) - sync_batch_after_task_change(task) db.session.commit() return tool_response( status="needs_human", @@ -834,7 +782,6 @@ def replace_task_notice( "warnings": cleaned_warnings, }, ) - sync_batch_after_task_change(task) db.session.commit() orchestrator_started = start_task_orchestrator(task.task_no) return tool_response( @@ -1046,7 +993,6 @@ def _commit_notice_edit( before_export_file_name=before_export_file_name, before_order_data_version=before_order_data_version, ) - sync_batch_after_task_change(task) db.session.commit() return tool_response( status="ok", @@ -1450,7 +1396,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]: metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)}, source=event_source, ) - sync_batch_after_task_change(task) db.session.commit() from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index efbab8f3..ea584f61 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -19,7 +19,6 @@ from flask import current_app from app import db from app.models import ShippingNotice, ShippingTaskEvent -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK @@ -267,12 +266,6 @@ def _clean_event_value(value: Any) -> str: return str(value or "").strip() -def _task_batch_no(task: ShippingNotice | None) -> str: - """从任务关系中提取批次号。""" - batch = getattr(task, "batch", None) - return _clean_event_value(getattr(batch, "batch_no", None)) - - def build_task_action_event_detail( task: ShippingNotice, *, @@ -284,7 +277,7 @@ def build_task_action_event_detail( """ 构建任务动作类事件详情。 - 核心逻辑:统一补齐 action/source/target/batch/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。 + 核心逻辑:统一补齐 action/source/target/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。 Args: task: 动作作用的目标任务。 @@ -301,7 +294,6 @@ def build_task_action_event_detail( "source": _clean_event_value(source), "target_type": "task", "target_id": _clean_event_value(getattr(task, "task_no", None)), - "batch_no": _task_batch_no(task), "conversation_id": _clean_event_value(getattr(task, "conversation_id", None)), } normalized_comment = _clean_event_value(comment) @@ -588,21 +580,3 @@ def log_task_action_event( ) -def switch_batch_focus( - batch: Any, - task: ShippingNotice, - *, - source: str, - event_type: str = "focus_switched", - comment: str | None = None, - emit_when_unchanged: bool = True, - extra: dict[str, Any] | None = None, -) -> bool: - """ - 切换批次焦点任务并写入标准事件。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del batch, task, source, event_type, comment, emit_when_unchanged, extra - raise_shipping_batches_removed() diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index bb5d6b7e..f2699515 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -93,7 +93,7 @@ def tool_response( Args: stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。 forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。 - extra: 需要保留在顶层的兼容字段,例如 batch_no。 + extra: 需要保留在顶层的额外业务字段。 """ from app.services.shipping_notice.state_machine import resolve_task_ui_state diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 52cd0a18..62efdde8 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -17,9 +17,7 @@ from app.services.shipping_notice import ( from app.services.shipping_notice import customer_identity_gate -# 任务 / 批次 / 决策 -create_batch = task_workflow.create_batch -create_batch_tasks = task_workflow.create_batch_tasks +# 任务 / 决策 create_task = task_workflow.create_task auto_progress = task_workflow.auto_progress submit_decision = task_workflow.submit_decision diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 131c9254..b6d3ae13 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -1,7 +1,7 @@ """ services/shipping_notice/ui_state.py -用途:发货通知任务/批次 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 +用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 依赖:models.ShippingNotice、state_machine、query_service、constants、stp_progress_contract、 process_gate_projection(统一 Gate 用户摘要)、 order_review_workbench_projection.apply_post_ot_gate_rules。 @@ -10,7 +10,6 @@ services/shipping_notice/ui_state.py stp_facts、progress_nodes); 若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影; Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); - 批次 UI 仅作会话上传集合摘要,不作为履约写操作面。 """ from __future__ import annotations @@ -18,7 +17,6 @@ from __future__ import annotations from typing import Any from app.models import ShippingNotice -from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed from app.services.shipping_notice.constants import ( CP_COMPLETED, CP_CUSTOMER_REVIEW, @@ -53,13 +51,7 @@ from app.services.shipping_notice.lifecycle_projection import ( LIFECYCLE_STAGES, project_lifecycle, ) -from app.services.shipping_notice.query_service import ( - compute_batch_process_summary, - list_sorted_batch_tasks, - resolve_task_export_download, - serialize_batch_summary, - serialize_task_summary, -) +from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary from app.services.shipping_notice.state_machine import ( CheckpointKind, resolve_task_ui_state, @@ -75,38 +67,6 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( {"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"}, ) -_CURRENT_STEP_INDEX_MAP: dict[str, int] = { - "step1_notice_submit": 0, - "step2_parse_confirm": 1, - "step3_inventory_prepare": 2, - "step2_inventory_prepare": 2, - "step4_align_confirm": 3, - "step5_match_inventory": 4, - "step3_inventory_match": 4, - "step4_shortage_review": 4, - "step6_generate_file": 5, - "step5_export_excel": 5, - "step7_upload_freight": 6, - "step6_upload_freight": 6, - "step7_finish": 6, -} - -_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"} -_BLOCKED_CHECKPOINTS = { - CP_PARSE_REVIEW, - CP_RSV_REQ, - CP_INVENTORY_SOURCE_REVIEW, - CP_ORDER_FREEZE, - RS_SHORTAGE_REVIEW, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - CP_UPLOAD_REQ, - CP_UPLOAD_FAILED, - CP_UPLOAD_RESULT_UNKNOWN, - CP_CUSTOMER_REVIEW, - CP_EXPORT_READY, - CP_EXPORT_GENERATED, -} - _REVIEW_ENTRY_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, @@ -136,41 +96,11 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), } -# 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。 -_STAGE_CHECKPOINT_CODES: dict[str, str] = { - CP_PARSE_REVIEW: "order_review", - CP_RSV_REQ: "order_review", - CP_CUSTOMER_REVIEW: "order_review", - CP_ORDER_FREEZE: "order_review", - CP_INVENTORY_SOURCE_REVIEW: "fulfillment_prep", - CP_INVENTORY_PENDING: "fulfillment_prep", - CP_READY_MATCH: "fulfillment_prep", - RS_SHORTAGE_REVIEW: "fulfillment_prep", - CP_READY_EXPORT: "fulfillment_prep", - CP_EXPORT_READY: "fulfillment_prep", - CP_EXPORT_GENERATED: "fulfillment_prep", - CP_WAITING_UPLOAD: "freight_upload", - CP_UPLOAD_REQ: "fulfillment_prep", - CP_UPLOAD_FAILED: "freight_upload", - CP_UPLOAD_RESULT_UNKNOWN: "freight_upload", - CP_UPLOADED: "freight_upload", - CP_COMPLETED: "freight_upload", - CP_REJECTED: "order_review", -} - - def _task_lifecycle( *, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: - """以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。""" + """以共享裁决器投影正式任务生命周期;缺少正式事实时保持未分类。""" gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate') - legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or '')) - if legacy_stage is None: - legacy_stage = 'freight_upload' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None - if legacy_stage is None: - # 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。 - legacy_index = _derive_current_step_index(task) - legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload')[legacy_index] from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success return project_lifecycle( @@ -180,7 +110,6 @@ def _task_lifecycle( if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code') else None ), - legacy_stage=legacy_stage, # ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。 has_candidate_context=True, verified_upload_success=has_verified_upload_success(task), @@ -188,9 +117,11 @@ def _task_lifecycle( def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]: - """将共享生命周期结果包装为任务详情既有的阶段 DTO。""" - stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse') - index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0) + """将共享生命周期结果包装为任务详情阶段 DTO;无正式事实时不猜阶段。""" + stage_code = str(lifecycle.get('lifecycle_stage') or '') + index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), None) + if index is None: + return {'code': 'unclassified', 'label': '状态待同步', 'index': 0, 'total': len(LIFECYCLE_STAGES)} return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)} @@ -251,47 +182,6 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]: return {"primary": primary, "secondary": secondary} -def _derive_current_step_index(task: ShippingNotice) -> int: - """ - 根据任务领域事实推导五阶段流程当前索引。 - - 核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。 - """ - current_step = str(task.current_step or "").strip() - if current_step in _CURRENT_STEP_INDEX_MAP: - legacy_index = _CURRENT_STEP_INDEX_MAP[current_step] - return 0 if legacy_index <= 0 else 1 if legacy_index == 1 else 3 if legacy_index >= 6 else 2 - - review_status = str(task.review_status or "").strip() - pending_reason = str(task.pending_human_reason or "").strip() - match_status = str(task.match_status or "").strip() - upload_status = str(getattr(task, "upload_status", None) or "").strip().lower() - has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip()) - - if upload_status in {"uploaded", "succeeded", "success"} or str(getattr(task, "lifecycle_status", "") or "").lower() in {"archived", "deleted"}: - return 3 - if upload_status in {"pending", "uploading", "failed"} or has_export: - return 2 - if match_status in {"fulfillable", "partial", "unfulfillable", "matched"}: - return 2 - if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE: - return 2 - if task.inventory_lines_json or match_status: - return 2 - if pending_reason in { - PH_RPA_PENDING, - PH_INV_UNAVAIL, - PH_RPA_EXHAUSTED, - }: - return 2 - if review_status in { - RS_PARSE_REVIEW, - PH_RSV_REQ, - } or pending_reason in {"low_confidence", PH_RSV_REQ, PH_INVENTORY_SOURCE_UNRESOLVED}: - return 1 - return 0 - - def build_shipping_workflow_steps( task: ShippingNotice, checkpoint: str | None, @@ -308,34 +198,22 @@ def build_shipping_workflow_steps( (index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage), None, ) - # 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。 - current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task) - pending_reason = str(task.pending_human_reason or "").strip() - checkpoint_value = str(checkpoint or "").strip() + # 五阶段只使用共享生命周期裁决;缺少正式事实时全部保持 pending。 + current_index = lifecycle_index steps: list[dict[str, str]] = [] for index, step in enumerate(WORKFLOW_STEPS): # ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让 # 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。 if lifecycle_stage == "upload_complete": status = "completed" + elif current_index is None: + status = "pending" elif index < current_index: status = "completed" elif index == current_index: status = "current" else: status = "pending" - inventory_blocked = index == 2 and pending_reason in {PH_INV_UNAVAIL, PH_RPA_EXHAUSTED} - parse_blocked = index == 1 and ( - checkpoint_value in {CP_PARSE_REVIEW, CP_RSV_REQ, CP_NOTICE_TEXT_EXTRACTION_FAILED} - or pending_reason in {"low_confidence", PH_RSV_REQ} - ) - prep_blocked = index == 2 and ( - checkpoint_value in {CP_INVENTORY_SOURCE_REVIEW, RS_SHORTAGE_REVIEW} - or pending_reason in {PH_INVENTORY_SOURCE_UNRESOLVED, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_SHORTAGE} - ) - upload_blocked = index == 3 and str(getattr(task, "upload_status", None) or "").strip().lower() == "failed" - if index == current_index and (checkpoint_value in _BLOCKED_CHECKPOINTS or inventory_blocked or parse_blocked or prep_blocked or upload_blocked): - status = "blocked" steps.append({**step, "status": status}) return steps @@ -986,7 +864,6 @@ def build_task_ui_state( } return { "task_no": task.task_no, - "batch_no": None, "stage": stage, "lifecycle_stage": stage["code"], "lifecycle_entries": lifecycle['lifecycle_entries'], @@ -1053,12 +930,3 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] ) -def build_batch_ui_state(batch: Any) -> dict[str, Any]: - """ - 构建批次级会话上传集合摘要(非履约写操作面)。 - - Raises: - ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。 - """ - del batch - raise_shipping_batches_removed() diff --git a/backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py b/backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py new file mode 100644 index 00000000..6928bfa6 --- /dev/null +++ b/backend/migrations/versions/hm6n7o8p9q0r_remove_legacy_shipping_apx_runtime.py @@ -0,0 +1,67 @@ +"""移除已下线 APX 自动推进运行时。 + +用途:收口遗留 APX Execution/Job 并删除仅服务旧六门禁运行时的唯一索引。 +依赖:shipping_process_executions、shipping_process_gates、jobs。 +逻辑:正式 20-Gate 是唯一运行态;迁移只终止 APX 记录,绝不改写正式 Execution、STP、Excel 或 RPA Job。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'hm6n7o8p9q0r' +down_revision = 'hk5l6m7n8o9p' +branch_labels = None +depends_on = None + + +def _indexes(table: str) -> set[str]: + """读取索引名,保证不同环境重复升级安全。""" + return {str(item.get('name') or '') for item in sa.inspect(op.get_bind()).get_indexes(table)} + + +def upgrade() -> None: + """终态化 APX 旧运行记录,再删除旧类型唯一索引。""" + bind = op.get_bind() + bind.execute(sa.text(""" + UPDATE jobs + SET status = 'cancelled', finished_at = COALESCE(finished_at, CURRENT_TIMESTAMP), + message = 'legacy APX auto-progress runtime removed' + WHERE domain = 'shipping_notice' + AND job_type = 'shipping_auto_progress' + AND status IN ('queued', 'running', 'active') + """)) + bind.execute(sa.text(""" + UPDATE shipping_process_gates + SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP + WHERE execution_id IN ( + SELECT id FROM shipping_process_executions WHERE execution_no LIKE 'APX-%' + ) + AND status IN ('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated') + """)) + bind.execute(sa.text(""" + UPDATE shipping_process_executions + SET status = 'superseded', updated_at = CURRENT_TIMESTAMP + WHERE execution_no LIKE 'APX-%' + AND status IN ('active', 'blocked', 'waiting_external') + """)) + if 'uq_jobs_shipping_auto_progress_one_active_task' in _indexes('jobs'): + op.drop_index('uq_jobs_shipping_auto_progress_one_active_task', table_name='jobs') + + +def downgrade() -> None: + """仅恢复旧索引定义;已终态化的 APX 记录不应被自动复活。""" + if 'uq_jobs_shipping_auto_progress_one_active_task' not in _indexes('jobs'): + op.create_index( + 'uq_jobs_shipping_auto_progress_one_active_task', 'jobs', ['task_id'], unique=True, + postgresql_where=sa.text( + "domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' " + "AND status IN ('queued', 'running') AND task_id IS NOT NULL" + ), + sqlite_where=sa.text( + "domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' " + "AND status IN ('queued', 'running') AND task_id IS NOT NULL" + ), + ) diff --git a/backend/scripts/audit_apx_runtime_state.py b/backend/scripts/audit_apx_runtime_state.py deleted file mode 100644 index dd9bc930..00000000 --- a/backend/scripts/audit_apx_runtime_state.py +++ /dev/null @@ -1,25 +0,0 @@ -""" -只读清点目标数据库中的 APX 运行态。 - -用法:在目标环境加载现有环境变量后执行 `python scripts/audit_apx_runtime_state.py`。 -本脚本只执行查询并输出 JSON,不迁移、不取消、不删除任何记录。 -""" - -from __future__ import annotations - -import json - -from app import create_app -from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state - - -def main() -> None: - """加载生产配置并输出 APX 只读清点结果。""" - app = create_app() - with app.app_context(): - print(json.dumps(audit_apx_runtime_state(), ensure_ascii=False, indent=2, sort_keys=True)) - - -if __name__ == '__main__': - main() - diff --git a/backend/tests/jobs/test_runner.py b/backend/tests/jobs/test_runner.py index 6cf11607..7d917e9c 100644 --- a/backend/tests/jobs/test_runner.py +++ b/backend/tests/jobs/test_runner.py @@ -36,7 +36,7 @@ def test_handler_error_rolls_back_before_mark_failed(monkeypatch): class _Db: session = _Session() - job = {'id': 939, 'job_type': 'shipping_auto_progress', 'attempts': 1, 'payload': {}} + job = {'id': 939, 'job_type': 'shipping_process_gate', 'attempts': 1, 'payload': {}} monkeypatch.setattr(runner.store, 'claim_next', lambda **_kwargs: job) monkeypatch.setattr(runner, 'get_handler', lambda _job_type: lambda *_args: (_ for _ in ()).throw(RuntimeError('db failed'))) monkeypatch.setattr(runner.store, 'mark_failed', lambda *_args, **_kwargs: (events.append('mark_failed'), (_ for _ in ()).throw(StopIteration))) diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 52795c17..68695869 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -1,8 +1,8 @@ """ tests/services/shipping_notice/test_reconciliation_phase34_contract.py -用途:Phase 3 统一 Projection 四事实 + Phase 4 管理端 replay 权限 + - BRANCH F ownership_anomaly rollback 的合同测试。 +用途:Phase 3 统一 Projection 四事实 + Phase 4 BRANCH F + ownership_anomaly rollback 的合同测试。 依赖:recovery_contract、reconciliation_projector、 reconciliation_service.reconcile_and_progress(mock 掉 DB 层仅验证纯函数矩阵)。 逻辑: @@ -14,9 +14,6 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py retryable/failed/running/idle)。 [P3 T4] project_case_primary_action 1a~1i CTA 分派矩阵。 [P3 T5] project_review_case_projection_bundle 六字段非空(Case + automation + actions)。 - [P4 T6] reconcile_and_progress PRE-CHECK: - a) replay_mode=True + is_admin=False → SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED 422 - b) legacy_job_id=999 + is_admin=False → 422 [P4 T7] ownership_anomaly BRANCH F: 断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写 (这里只测 ValidationError 降级情形,Review Case 不含旧流程字段)。 @@ -287,7 +284,7 @@ def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation( # ============================================================ -# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询) +# [P4] BRANCH F 归属异常(通过 monkeypatch 替换锁 DB 查询) # ============================================================ def _mock_case_for_p4(case_no='CASE-2608-0042'): @@ -372,72 +369,6 @@ def _install_minimal_mocks(monkeypatch, case=None, app=None): return case -@pytest.mark.pure_unit -def test_p4_t6a_replay_mode_without_admin_raises(monkeypatch): - """[P4 T6a] replay_mode=True + is_admin=False → 422 SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED。""" - from app.core.errors import ValidationError - from app.services.shipping_notice.reconciliation_service import reconcile_and_progress - - _install_minimal_mocks(monkeypatch) - with pytest.raises(ValidationError) as exc: - reconcile_and_progress( - user_id=1, - case_no='CASE-2608-0042', - operation_id=str(uuid.uuid4()), - user_action='auto', - is_admin=False, - replay_mode=True, - ) - assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED' - - -@pytest.mark.pure_unit -def test_p4_t6b_legacy_job_id_without_admin_raises(monkeypatch): - """[P4 T6b] legacy_job_id=928 + is_admin=False → 422 权限拒绝。""" - from app.core.errors import ValidationError - from app.services.shipping_notice.reconciliation_service import reconcile_and_progress - - _install_minimal_mocks(monkeypatch) - with pytest.raises(ValidationError) as exc: - reconcile_and_progress( - user_id=1, - case_no='CASE-2608-0042', - operation_id=str(uuid.uuid4()), - user_action='auto', - is_admin=False, - legacy_job_id=928, - ) - assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED' - - -@pytest.mark.pure_unit -def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch): - """[P4 T6c] legacy_job 必须是 failed/dead,否则 422。""" - from app.core.errors import ValidationError - from app.services.shipping_notice.reconciliation_service import reconcile_and_progress - - _install_minimal_mocks(monkeypatch) - bad_job = _fake_job(job_id=991, status='running') # 不是失败态 - - from app.services.shipping_notice import reconciliation_service as mod - - def _get(coll, jid): # noqa: ARG001 - if str(getattr(coll, '__name__', '')) == 'Job' and jid == 991: - return bad_job - return None - - monkeypatch.setattr(mod.db.session, 'get', _get) - with pytest.raises(ValidationError): - reconcile_and_progress( - user_id=1, - case_no='CASE-2608-0042', - operation_id=str(uuid.uuid4()), - user_action='auto', - is_admin=True, - legacy_job_id=991, - ) - - # ============================================================ # [P4 T7] BRANCH F ownership_anomaly 422 降级(Review Case 不含旧流程字段) # ============================================================ diff --git a/backend/tests/test_agent_registry_handlers.py b/backend/tests/test_agent_registry_handlers.py index 376e7641..11601d41 100644 --- a/backend/tests/test_agent_registry_handlers.py +++ b/backend/tests/test_agent_registry_handlers.py @@ -26,7 +26,6 @@ def test_shipping_handler_builds_ui_state_event(app): external_conversation_id=None, request_id='req-1', shipping_task_id='SN-TEST-001', - shipping_batch_no='SB-TEST', ) event = handler.build_ui_state_event(ctx) assert event is None or event.get('event') == 'shipping_ui_state' diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index ae90ef11..c46bdf6e 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -63,21 +63,11 @@ def _create_task_for_user(user_id: int) -> str: return task.task_no -def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch): +def test_chat_turn_rejects_legacy_fulfillment_action(app, client): user = _create_user() agent = _create_shipping_agent() task_no = _create_task_for_user(user.id) - monkeypatch.setattr( - "app.services.shipping_notice.chat_action_handlers.submit_decision", - lambda payload: { - "status": "ok", - "message": "已确认,请继续下一步。", - "task_id": task_no, - "data": {}, - }, - ) - res = client.post( "/api/chat/turns/stream", headers={ @@ -99,14 +89,8 @@ def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch) events = _parse_sse_events(res.get_data(as_text=True)) event_names = [item.get("event") for item in events] assert "run.started" in event_names - assert "step.started" in event_names - assert "message.completed" in event_names or "message_end" in event_names - assert "run.completed" in event_names - - logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all() - assert len(logs) == 1 - assert logs[0].query == "确认" - assert "已确认" in logs[0].answer + assert "run.failed" in event_names + assert "run.completed" not in event_names def test_chat_turn_unknown_action_returns_failed(app, client): @@ -154,11 +138,11 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client): assert any(item.get("event") == "run.failed" for item in events) -def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_path): +def test_chat_turn_multipart_upload_rejects_removed_batch_action(app, client, tmp_path): """ - multipart 上传时 agent_id 应从 form 字段解析;create_batch_from_notices 已下线为 410。 + multipart 上传时 agent_id 应从 form 字段解析;旧建批 action 不再注册。 - 关键断言:form 带 agent_id 时 run 能启动;建批动作固定 BATCHES_REMOVED(非 agent 解析失败)。 + 关键断言:form 带 agent_id 时 run 能启动;旧 action 作为未知 action 失败。 """ from io import BytesIO @@ -191,8 +175,7 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_pa assert "run.failed" in event_names assert "run.completed" not in event_names failed = next(item for item in events if item.get("event") == "run.failed") - # 关键断言:SSE run.failed 顶层带业务 code(非嵌套 data)。 - assert failed.get("code") == "SHIPPING.BATCHES_REMOVED" + assert failed.get("code") == "RESOURCE.NOT_FOUND" def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch): @@ -239,102 +222,3 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie assert all('schema_preview' not in payload for payload in assistant_payloads) -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path): - """shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。""" - from io import BytesIO - - user = _create_user() - agent = _create_shipping_agent() - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) - captured: dict = {} - - def fake_create(**kwargs): - captured.update(kwargs) - return { - "status": "ok", - "batch_no": "SB-CHAT-IDEM-001", - "data": { - "tasks": [{"task_id": "SN-CHAT-IDEM-001"}], - "focus_task": {"task_no": "SN-CHAT-IDEM-001"}, - }, - } - - monkeypatch.setattr( - "app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items", - fake_create, - ) - - res = client.post( - "/api/chat/turns/stream", - headers={"X-Username": user.username, "X-Role": user.role}, - data={ - "agent_id": str(agent.id), - "input": json.dumps( - { - "type": "upload_followup", - "display_text": "上传发货通知:notice.txt", - "action_type": "shipping.create_batch_from_notices", - "payload": {"idempotency_key": "chat-idem-001"}, - }, - ensure_ascii=False, - ), - "files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"), - }, - content_type="multipart/form-data", - ) - assert res.status_code == 200 - res.get_data(as_text=True) - assert captured.get("create_idempotency_key") == "chat-idem-001" - notice_items = captured.get("notice_items") or [] - assert notice_items - assert notice_items[0].get("source_content_hash") - - -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path): - """相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。""" - from io import BytesIO - - user = _create_user() - agent = _create_shipping_agent() - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) - orchestrator_calls: list[str] = [] - monkeypatch.setattr( - "app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator", - lambda batch_no: orchestrator_calls.append(batch_no) or True, - ) - - payload_input = { - "type": "upload_followup", - "display_text": "上传发货通知:notice.txt", - "action_type": "shipping.create_batch_from_notices", - "payload": {"idempotency_key": "chat-replay-integration-001"}, - } - headers = {"X-Username": user.username, "X-Role": user.role} - raw = "客户:ACME\nA001 x 10".encode("utf-8") - - def _post_turn(): - return client.post( - "/api/chat/turns/stream", - headers=headers, - data={ - "agent_id": str(agent.id), - "input": json.dumps(payload_input, ensure_ascii=False), - "files": (BytesIO(raw), "notice.txt"), - }, - content_type="multipart/form-data", - ) - - first = _post_turn() - assert first.status_code == 200 - first_events = _parse_sse_events(first.get_data(as_text=True)) - assert "run.failed" not in [item.get("event") for item in first_events] - - second = _post_turn() - assert second.status_code == 200 - second_events = _parse_sse_events(second.get_data(as_text=True)) - completed = [item for item in second_events if item.get("event") == "message.completed"] - assert completed - assert "已恢复此前创建的批次" in str(completed[-1].get("content", "")) - assert len(orchestrator_calls) == 1 diff --git a/backend/tests/test_email_supplement_merge.py b/backend/tests/test_email_supplement_merge.py index f359251b..2dca8f2a 100644 --- a/backend/tests/test_email_supplement_merge.py +++ b/backend/tests/test_email_supplement_merge.py @@ -6,6 +6,8 @@ from __future__ import annotations +import pytest + from app.services.shipping_notice.email_allocation_table_parser import ( parse_email_allocation_tables, parse_email_allocation_text, @@ -87,6 +89,19 @@ def test_email_supplement_external_reservation_id_alias_merges_real_mail_header( assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn' +def test_email_supplement_uses_schema_alias_order_for_duplicate_source_headers(): + """同字段的两个邮件列按 Schema aliases 顺序取值,不能整表拒绝。""" + supplement = parse_email_allocation_tables( + content_hash='h' * 64, + schema_definition=SCHEMA, + html_tables=['''
PO#MPNSource Typehub code
4518738152D4-A08AR12000002FIRST-SOURCESECOND-HUB
'''], + ) + + assert supplement['issues'] == [] + assert supplement['rows'][0]['inventory_source_hint'] == 'FIRST-SOURCE' + assert supplement['rows'][0]['evidence']['inventory_source_hint']['column_index'] == 2 + + def test_email_supplement_ampn_alias_matches_customer_part_number(): """邮件 AMPN 应能与订单客户料号交叉关联并补入预约号。""" order = _order() @@ -139,7 +154,41 @@ def test_email_supplement_conflicting_schema_field_does_not_overwrite_pdf_or_pic orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA, )[0] assert not any(item['field_id'] == 'reservation' for item in merged['lines'][0]['fields']) - assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts'] + finding = next(item for item in merged['conflicts'] if item.get('field') == 'reservation_id') + assert finding['resolution_status'] == 'unresolved' + assert finding['scope'] == 'line' + assert finding['line_index'] == 0 + assert finding['conflict_key'] == '0:reservation_id' + assert finding['values'] == ['33874', '33875'] + assert [source['source_type'] for source in finding['sources']] == ['email_body', 'email_body'] + + +@pytest.mark.pure_unit +def test_email_supplement_does_not_cross_compare_values_from_different_part_lines(): + """同 PO 的不同料号可有不同单价,补充合并只能比较同一目标行的关联正文行。""" + schema = { + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + order = _order() + order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{'value': '10.00'}]}) + order['lines'].append({'fields': [ + {'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]}, + {'field_id': 'qty', 'observations': [{'value': 1}]}, + {'field_id': 'unit-price', 'observations': [{'value': '20.00'}]}, + ]}) + result = merge_email_supplements( + orders=[order], + supplements_by_intake={1: {'document_id': 304, 'rows': [ + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '10.00', 'evidence': {}}, + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000003', 'unit_price': '20.00', 'evidence': {}}, + ]}}, + schema_definition=schema, + )[0] + + assert not any(item.get('field') == 'unit_price' for item in result['conflicts']) def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review(): @@ -166,6 +215,110 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review(): assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts'] +@pytest.mark.pure_unit +def test_email_supplement_treats_decimal_format_variants_as_the_same_value(): + """PDF 与邮件的金额仅格式不同,必须按 Schema decimal 语义比较而非制造冲突。""" + schema = { + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'unit-price', 'observations': [{'value': '1731.6'}], + }) + supplement = { + 'document_id': 44, + 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': 'D4-A08AR12000002', + 'unit_price': '1,731.60', + 'evidence': {}, + }], + } + + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema, + )[0] + + assert _value(merged['lines'][0]['fields'], 'unit-price') == '1731.6' + assert not any(item.get('field') == 'unit_price' for item in merged['conflicts']) + + +@pytest.mark.pure_unit +def test_email_supplement_decimal_difference_creates_a_complete_unresolved_finding(): + """真实金额不一致必须保留双方原值、规范值和邮件单元格证据,供复核直接裁决。""" + schema = { + 'version': 'shipping-order-schema.v9', + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'unit-price', 'observations': [{ + 'value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'}, + }], + }) + supplement = { + 'document_id': 304, + 'rows': [{ + 'customer_po_number': '4518738152', + 'part_number': 'D4-A08AR12000002', + 'unit_price': '1732.00', + 'evidence': {'unit_price': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'}}, + }], + } + + merged = merge_email_supplements( + orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema, + )[0] + + finding = next(item for item in merged['conflicts'] if item.get('field') == 'unit_price') + assert finding['conflict_key'] == '0:unit_price' + assert finding['severity'] == 'blocking' + assert finding['resolution_status'] == 'unresolved' + assert finding['scope'] == 'line' + assert finding['line_index'] == 0 + assert finding['values'] == ['1731.60', '1732.00'] + assert finding['sources'] == [ + { + 'source_type': 'pdf', 'raw_value': '1731.60', 'canonical_value': '1731.60', + 'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'}, + }, + { + 'source_type': 'email_body', 'raw_value': '1732.00', 'canonical_value': '1732.00', + 'document_id': 304, + 'evidence_ref': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'}, + }, + ] + assert finding['rule_version'] == 'shipping-order-schema.v9' + + +@pytest.mark.pure_unit +def test_email_supplement_duplicate_email_decimal_formats_do_not_create_a_conflict(): + """同一邮件补充行的等价金额格式必须按 decimal 归并,不能产生正文内部冲突。""" + schema = { + 'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ], + } + result = merge_email_supplements( + orders=[_order()], + supplements_by_intake={1: {'document_id': 304, 'rows': [ + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1731.6', 'evidence': {}}, + {'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1,731.60', 'evidence': {}}, + ]}}, + schema_definition=schema, + )[0] + + assert _value(result['lines'][0]['fields'], 'unit-price') == '1731.6' + assert not any(item.get('field') == 'unit_price' for item in result['conflicts']) + + def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_numbers(): """邮件 PN/AMPN 均可与订单内部/客户料号交叉匹配,不依赖字段名称相同。""" scenarios = [ diff --git a/backend/tests/test_legacy_supplement_conflict_reassessment.py b/backend/tests/test_legacy_supplement_conflict_reassessment.py new file mode 100644 index 00000000..83c27d2f --- /dev/null +++ b/backend/tests/test_legacy_supplement_conflict_reassessment.py @@ -0,0 +1,108 @@ +""" +tests/test_legacy_supplement_conflict_reassessment.py + +用途:验证旧补充冲突不会被静默放行,而会升级为有稳定键的证据不足 Finding。 +依赖:legacy_supplement_conflict_reassessment_service、pytest。 +逻辑:纯函数层覆盖旧结构升级、非旧 Finding 保留以及重复旧记录收敛。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import ( + reassess_legacy_supplement_conflicts_from_frozen_order, + upgrade_legacy_supplement_conflicts, +) +from tests.test_email_supplement_merge import SCHEMA, _order + + +@pytest.mark.pure_unit +def test_upgrade_legacy_supplement_conflict_keeps_blocking_but_makes_recovery_visible(): + """旧 `{field, reason}` 不能被直接清除,须变为可展示的证据不足 Finding。""" + upgraded, count = upgrade_legacy_supplement_conflicts([{ + 'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price', + }]) + + assert count == 1 + assert upgraded == [{ + 'conflict_key': '-1:unit_price', 'severity': 'blocking', + 'reason': 'supplement_conflict_evidence_insufficient', 'resolution_status': 'unresolved', + 'field': 'unit_price', 'scope': 'unscoped', 'line_index': None, + 'values': [], 'sources': [], 'rule_version': 'legacy-supplement-conflict.v1', + 'legacy_reason': 'supplement_field_conflict', 'recovery_action': 'reparse_current_pdf', + }] + + +@pytest.mark.pure_unit +def test_upgrade_legacy_supplement_conflict_does_not_touch_complete_current_finding(): + """已有新 Finding 的证据与裁决状态不可被历史迁移覆盖。""" + current = { + 'conflict_key': '0:unit_price', 'severity': 'blocking', + 'reason': 'supplement_field_conflict', 'resolution_status': 'unresolved', + 'field': 'unit_price', 'values': ['1', '2'], 'sources': [{'source_type': 'pdf'}], + } + upgraded, count = upgrade_legacy_supplement_conflicts([current]) + assert count == 0 + assert upgraded == [current] + + +@pytest.mark.pure_unit +def test_upgrade_legacy_supplement_conflict_collapses_duplicate_legacy_identity(): + """同字段重复旧阻断升级后只有一项,避免一次操作产生多个不可裁决卡片。""" + upgraded, count = upgrade_legacy_supplement_conflicts([ + {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'}, + {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'}, + ]) + assert count == 2 + assert len(upgraded) == 1 + + +@pytest.mark.pure_unit +def test_reassess_legacy_conflict_from_frozen_order_clears_decimal_format_false_positive(): + """冻结证据可恢复时,1731.6 与 1,731.60 必须按当前 decimal 规则清除旧假冲突。""" + schema = {'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ]} + order = _order() + order['lines'][0]['fields'].append({ + 'field_id': 'unit-price', 'observations': [{'value': '1731.6'}], + }) + conflicts, status, count = reassess_legacy_supplement_conflicts_from_frozen_order( + candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}], + frozen_order=order, + supplements_by_intake={1: {'document_id': 304, 'rows': [{ + 'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', + 'unit_price': '1,731.60', 'evidence': {}, + }]}}, + schema_definition=schema, + ) + assert status == 'rebuilt' + assert count == 1 + assert conflicts == [] + + +@pytest.mark.pure_unit +def test_reassess_legacy_conflict_from_frozen_order_rebuilds_real_conflict_with_evidence(): + """冻结证据可恢复时,真实金额差异必须变为当前完整 Finding,而不是笼统旧阻断。""" + schema = {'fields': [ + *SCHEMA['fields'], + {'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + ]} + order = _order() + order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{ + 'value': '10.00', 'document_id': 305, 'evidence_ref': {'page_no': 1}, + }]}) + conflicts, status, _ = reassess_legacy_supplement_conflicts_from_frozen_order( + candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}], + frozen_order=order, + supplements_by_intake={1: {'document_id': 304, 'rows': [{ + 'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', + 'unit_price': '11.00', 'evidence': {'unit_price': {'row_index': 1}}, + }]}}, + schema_definition=schema, + ) + assert status == 'rebuilt' + assert conflicts[0]['conflict_key'] == '0:unit_price' + assert [source['document_id'] for source in conflicts[0]['sources']] == [305, 304] diff --git a/backend/tests/test_post_ot_fulfillment_wave_p0.py b/backend/tests/test_post_ot_fulfillment_wave_p0.py index 36578fe0..edf6acc4 100644 --- a/backend/tests/test_post_ot_fulfillment_wave_p0.py +++ b/backend/tests/test_post_ot_fulfillment_wave_p0.py @@ -250,3 +250,30 @@ def test_post_ot_api_does_not_call_confirm_auto_progress(app, monkeypatch): assert calls['confirm'] == 0 assert out['post_ot_wave'] is True assert out['wave_progress']['wave_no'] == 3 + + +def test_post_ot_api_rejects_pre_ot_wave_without_legacy_fallback(app, monkeypatch): + """无正式 OT 时必须拒绝,不能回落到历史建波/自动推进链路。""" + from app.api.workspace import shipping_notice as api + from app.core.errors import ValidationError + + with app.app_context(): + with app.test_request_context( + '/api/workspace/shipping-notice/order-review-cases/RC-9/line-fulfillment/wave', + method='POST', + json={'line_keys': ['L1'], 'idempotency_key': 'k1'}, + ): + monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1)) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_draft_service.soft_load_review_case_for_audit', + lambda **_k: SimpleNamespace(id=1, case_no='RC-9'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot', + lambda _c: {'has_formal_ot': False}, + ) + + with pytest.raises(ValidationError, match='formal order task') as exc: + api.workspace_create_shipping_order_review_fulfillment_wave('RC-9') + + assert exc.value.code == 'SHIPPING.FORMAL_OT_REQUIRED' diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py index 1b150a59..1bc54951 100644 --- a/backend/tests/test_shipping_auto_progress_p0_3.py +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -21,9 +21,7 @@ from app.models import ( ShippingProcessGateAttempt, ) from app.services.shipping_notice.auto_progress_controller import ( - AUTO_PROGRESS_GATE_CODES, determine_formal_start_gate, - run_auto_progress_job, submit_auto_progress, ) from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through @@ -80,38 +78,21 @@ def test_submit_creates_formal_execution_for_task_without_case(app): assert len(gate_codes) == 20 assert gate_codes[0] == 'document_materialization' assert gate_codes[-1] == 'manual_upload_handoff' - assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0 assert Job.query.filter_by(id=first['job_id']).one().job_type == 'shipping_process_gate' -def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app): - """同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。""" +def test_submit_reuses_formal_case_execution(app): + """同一 Task 已有正式 Case Execution 时必须复用该 20-Gate 链。""" task = _task_with_candidate() formal = ensure_execution_for_workflow_version(review_case_id=901, task_id=int(task.id)) - duplicate = ShippingProcessExecution( - execution_no='APX-DUPLICATE', task_id=int(task.id), - candidate_set_id=task.active_inventory_candidate_set_id, - execution_revision=1, status='blocked', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], - lock_version=1, - ) - db.session.add(duplicate) - db.session.flush() - for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1): - db.session.add(ShippingProcessGate( - execution_id=int(duplicate.id), gate_code=gate_code, sequence_no=sequence_no, - status='pending', evaluation_version=1, lock_version=1, - )) - task.active_process_execution_id = int(duplicate.id) + task.active_process_execution_id = int(formal.id) db.session.commit() result = submit_auto_progress(task=task, trigger='user_retry') db.session.refresh(task) - db.session.refresh(duplicate) assert result['execution_id'] == formal.id assert task.active_process_execution_id == formal.id - assert duplicate.status == 'superseded' - assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0 def test_formal_execution_queues_one_gate_attempt_job(app): @@ -202,66 +183,3 @@ def test_active_stp_job_without_retry_metadata_is_reused(app): assert result['retry_of_job_id'] is None -def test_legacy_shipping_auto_progress_job_is_terminal_readonly(app): - """历史 APX Job 被 Worker 领取时只能终止,不能再执行六 Gate 状态机。""" - task = _task_with_candidate() - legacy = ShippingProcessExecution( - execution_no='APX-READONLY', task_id=int(task.id), status='active', - candidate_set_id=int(task.active_inventory_candidate_set_id), - current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, - ) - db.session.add(legacy) - db.session.flush() - gate = ShippingProcessGate( - execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0], - sequence_no=1, status='running', evaluation_version=1, lock_version=1, - ) - db.session.add(gate) - db.session.flush() - task.active_process_execution_id = int(legacy.id) - job = Job( - domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id), - execution_id=int(legacy.id), gate_id=int(gate.id), status='running', - candidate_set_id=int(task.active_inventory_candidate_set_id), - payload_json={'fencing_token': 'legacy-token'}, fencing_token='legacy-token', max_attempts=1, - ) - db.session.add(job) - db.session.commit() - - result = run_auto_progress_job(job_id=int(job.id), worker_id='test-worker') - - db.session.refresh(job) - db.session.refresh(gate) - assert result['status'] == 'legacy_readonly' - assert job.status == 'cancelled' - assert gate.status == 'cancelled' - - -def test_active_legacy_apx_job_does_not_block_formal_submission(app): - """历史 APX 活动 Job 不得被正式 20-Gate 提交入口复用或阻塞。""" - task = _task_with_candidate() - legacy = ShippingProcessExecution( - execution_no='APX-NONBLOCKING', task_id=int(task.id), status='active', - candidate_set_id=int(task.active_inventory_candidate_set_id), - current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, - ) - db.session.add(legacy) - db.session.flush() - gate = ShippingProcessGate( - execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0], - sequence_no=1, status='queued', evaluation_version=1, lock_version=1, - ) - db.session.add(gate) - db.session.flush() - task.active_process_execution_id = int(legacy.id) - db.session.add(Job( - domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id), - execution_id=int(legacy.id), gate_id=int(gate.id), candidate_set_id=int(task.active_inventory_candidate_set_id), - status='queued', payload_json={}, fencing_token='legacy-token', max_attempts=1, - )) - db.session.commit() - - result = submit_auto_progress(task=task, trigger='review_confirmed') - - assert result['status'] == 'queued' - assert db.session.get(Job, result['job_id']).job_type == 'shipping_process_gate' diff --git a/backend/tests/test_shipping_candidate_qualification.py b/backend/tests/test_shipping_candidate_qualification.py index ddf51852..42605672 100644 --- a/backend/tests/test_shipping_candidate_qualification.py +++ b/backend/tests/test_shipping_candidate_qualification.py @@ -10,6 +10,8 @@ from __future__ import annotations from types import SimpleNamespace +import pytest + from app.services.shipping_notice.candidate_qualification_service import ( evaluate_candidate_qualification, resolve_review_case_customer_resolved, @@ -111,6 +113,104 @@ def test_layout_table_review_diagnostic_does_not_block_auto_create(monkeypatch): assert 'blocking_conflict' not in reason_codes +@pytest.mark.pure_unit +def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monkeypatch): + """派生已解决的字段不能继续被历史 evidence_missing 阻断。""" + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled', + lambda: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy', + lambda: {'enabled': True}, + ) + candidate = _eligible_candidate( + conflicts_json=[{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + structured_result_json={ + 'customer': {'resolution_status': 'user_confirmed'}, + 'extraction': {'field_adjudication': { + 'blocked_fields': [], + 'decisions': [{'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived'}], + }}, + }, + ) + + result = evaluate_candidate_qualification( + candidate=candidate, + fields_complete=True, + customer_resolved=True, + schema_auto_create_enabled=True, + ) + + assert result['gates']['field_conflicts_resolved'] is True + assert result['can_auto_create'] is True + + +@pytest.mark.pure_unit +def test_resolved_blocking_finding_does_not_block_candidate_qualification(monkeypatch): + """标准 Finding 已记录人工裁决时,资格 Gate 只能阻断 unresolved 项。""" + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled', + lambda: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy', + lambda: {'enabled': True}, + ) + candidate = _eligible_candidate(conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'resolved', + 'values': ['1731.60', '1732.00'], + }]) + + result = evaluate_candidate_qualification( + candidate=candidate, + fields_complete=True, + customer_resolved=True, + schema_auto_create_enabled=True, + ) + + assert result['gates']['field_conflicts_resolved'] is True + assert result['can_auto_create'] is True + + +@pytest.mark.pure_unit +def test_non_blocking_standard_finding_does_not_block_candidate_qualification(monkeypatch): + """统一 Finding 的 severity 不是 blocking 时不得被资格 Gate 误拦截。""" + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled', + lambda: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy', + lambda: {'enabled': True}, + ) + candidate = _eligible_candidate(conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'severity': 'review_required', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'values': ['1731.60', '1732.00'], + }]) + + result = evaluate_candidate_qualification( + candidate=candidate, + fields_complete=True, + customer_resolved=True, + schema_auto_create_enabled=True, + ) + + assert result['gates']['field_conflicts_resolved'] is True + assert result['can_auto_create'] is True + + def test_llm_candidate_can_pass_unified_gates(monkeypatch): """LLM Candidate 具备分类/字段置信度与证据时可通过统一门禁 → eligible。""" monkeypatch.setattr( @@ -244,7 +344,9 @@ def test_generic_candidate_failure_has_concrete_reason_codes(monkeypatch): assert result['can_auto_create'] is False assert 'evidence_missing' in result['blocking_reason_codes'] assert 'field_conflict' in result['blocking_reason_codes'] - assert 'required_field_missing' in result['blocking_reason_codes'] + # Candidate Qualification 在字段合并后运行,必须使用最终字段完整性原因码; + # `required_field_missing` 仅保留给解析/复核草稿阶段。 + assert 'final_required_field_missing' in result['blocking_reason_codes'] assert 'duplicate_unresolved' in result['blocking_reason_codes'] or 'duplicate_resolved' in result['failed_gates'] assert any(code.startswith('customer_') for code in result['blocking_reason_codes']) diff --git a/backend/tests/test_shipping_chat_action_handlers.py b/backend/tests/test_shipping_chat_action_handlers.py index 9ede091e..81623ef3 100644 --- a/backend/tests/test_shipping_chat_action_handlers.py +++ b/backend/tests/test_shipping_chat_action_handlers.py @@ -15,6 +15,9 @@ def test_legacy_fulfillment_chat_actions_are_not_registered(): action_types = set(list_action_types()) assert { + "shipping.create_batch_from_notices", + "shipping.create_batch_from_intakes", + "shipping.switch_batch_focus", "shipping.freeze_order", "shipping.generate_excel", "shipping.retry_upload", @@ -36,4 +39,6 @@ def test_legacy_workspace_fulfillment_routes_are_not_registered(app): '/api/workspace/shipping-tasks//match-inventory', '/api/workspace/shipping-tasks//generate-excel', '/api/workspace/shipping-tasks//retry-upload', + '/api/workspace/shipping-tasks//retry', + '/api/workspace/shipping-tasks//lines//retry', }.isdisjoint(routes) diff --git a/backend/tests/test_shipping_conversation_processing_api.py b/backend/tests/test_shipping_conversation_processing_api.py index 57e1797e..e44a4068 100644 --- a/backend/tests/test_shipping_conversation_processing_api.py +++ b/backend/tests/test_shipping_conversation_processing_api.py @@ -11,6 +11,7 @@ from __future__ import annotations from app import db from app.core.auth.jwt import issue_local_access_token from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun +from sqlalchemy import event from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_task_service import ( allocate_user_task_no_for_run, @@ -99,6 +100,10 @@ def test_workspace_shipping_processing_and_focus_viewed_api(app, client): ) assert focus.status_code == 200, focus.get_json() assert focus.get_json()['data']['focused_task_no'] == user_task_no + assert 'work_items' not in focus.get_json()['data'] + assert set(focus.get_json()['data']['processing']['status_groups']) == { + 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', + } viewed = client.post( f'/api/workspace/shipping-notice/conversation-tasks/{user_task_no}/viewed', @@ -106,3 +111,122 @@ def test_workspace_shipping_processing_and_focus_viewed_api(app, client): headers=headers, ) assert viewed.status_code == 200, viewed.get_json() + assert 'work_items' not in viewed.get_json()['data'] + + +def test_workspace_shipping_processing_summary_omits_detail_and_legacy_mirrors(app, client): + """首屏会话摘要只返回状态→EML→PDF权威分组,详情必须按需读取。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='API-SUMMARY') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + db.session.commit() + token = issue_local_access_token(user) + session_id = session.session_id + assert run.id is not None + + response = client.get( + f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200, response.get_json() + data = response.get_json()['data'] + assert data['conversation_id'] == session_id + assert data['projection_mode'] == 'summary' + assert 'work_items' not in data + projection = data['conversation_processing'] + assert set(projection['status_groups']) == { + 'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived', + } + assert 'needs_action' not in projection + assert 'history' not in projection + for tasks in projection['status_groups'].values(): + for task in tasks: + assert 'process_gate' not in task + assert 'objects' not in task + # PDF 叶子是首屏“状态→EML→PDF”树的一部分;但叶子同样不携带详情 Gate。 + for child in task.get('aggregate_children') or []: + assert 'process_gate' not in child + + +def test_workspace_shipping_processing_summary_does_not_read_run_snapshots(app, client): + """首屏摘要不得查询 processing run,避免 JSON 快照解码重新进入轮询路径。""" + with app.app_context(): + user, _agent, session, _intake, _document = _seed_run_input(suffix='API-SUMMARY-FAST') + token = issue_local_access_token(user) + session_id = session.session_id + run_selects: list[str] = [] + + def capture_run_selects(_conn, _cursor, statement, _parameters, _context, _executemany): + if 'shipping_order_processing_runs' in statement.lower(): + run_selects.append(statement) + + event.listen(db.engine, 'before_cursor_execute', capture_run_selects) + try: + response = client.get( + f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary', + headers={'Authorization': f'Bearer {token}'}, + ) + finally: + event.remove(db.engine, 'before_cursor_execute', capture_run_selects) + + assert response.status_code == 200, response.get_json() + assert run_selects == [] + + +def test_workspace_shipping_processing_summary_keeps_lightweight_action_entries(app, client): + """摘要不加载重型详情,但必须保留后端裁决的最小操作入口。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='API-SUMMARY-ACTIONS') + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + run_no = run.run_no + db.session.commit() + token = issue_local_access_token(user) + session_id = session.session_id + document.parse_status = 'parsed' + document.order_extraction_status = 'review_required' + candidate = ShippingOrderCandidate( + candidate_no=f'SNC-API-SUMMARY-ACTIONS-{run.id}', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key=f'key-api-summary-actions-{run.id}', + order_extraction_run_id=run.id, + is_current_version=True, + candidate_status='provisional', + structured_result_json={}, + ) + db.session.add(candidate) + db.session.flush() + db.session.commit() + + response = client.get( + f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200, response.get_json() + projection = response.get_json()['data']['conversation_processing'] + assert [node['code'] for node in projection['lifecycle_nodes']] == [ + 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', + ] + tasks = projection['status_groups']['waiting_human'] + assert len(tasks) == 1 + leaf = tasks[0]['aggregate_children'][0] + assert leaf['run_no'] == run_no + assert leaf['source_summary']['po_number'] is None + assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse' + assert leaf['ui_state']['primary_action']['code'] == 'open_order_review' + assert leaf['ui_state']['primary_action']['target_surface'] == 'order_lifecycle_workbench' + assert leaf['ui_state']['primary_action']['target_lifecycle_stage'] == 'intake_parse' diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index dd10b910..3c8c1ecc 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -19,6 +19,7 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio suggest_header_layouts, suggest_header_regions, suggest_multi_subrow_layouts, + derive_incomplete_table_bbox, ) from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile @@ -217,6 +218,72 @@ def test_subrow_suggestion_uses_one_record_for_vertical_samples(): assert suggestions[0].y1 < suggestions[1].y0 +def test_incomplete_table_bbox_expands_from_page_rows_until_summary(): + """表格框只覆盖表头时,页级坐标可恢复唯一明细区,但不包含合计行。""" + characters = _glyphs( + [('Item', 10), ('Material', 65), ('Quantity', 150)], + [('Description', 10), ('Delivery Date', 120)], + [('10', 10), ('PART-A', 65), ('3.000', 150)], + [('FRAME', 65), ('PCS', 150)], + [('898.72', 120), ('2,696.16', 165)], + [('TOTAL AMOUNT', 65)], + ) + + expanded = derive_incomplete_table_bbox( + characters=characters, + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}, + ) + + assert expanded == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 90.0} + + +def test_incomplete_table_bbox_does_not_expand_without_line_anchor(): + """没有可靠明细起行锚点时,不能把页面下方普通文本扩大成表格。""" + characters = _glyphs( + [('Item', 10), ('Material', 65), ('Quantity', 150)], + [('Description', 10), ('Delivery Date', 120)], + [('notes', 10), ('ordinary text', 65)], + [('TOTAL AMOUNT', 65)], + ) + + assert derive_incomplete_table_bbox( + characters=characters, + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}, + ) is None + + +def test_profile_reconstruction_uses_page_evidence_when_table_glyphs_are_header_only(monkeypatch): + """Profile 重建入口必须把页级派生框传给同一行重建器。""" + from app.services.shipping_notice import order_document_profile_service as service + + page_glyphs = _glyphs( + [('Item', 10), ('Material', 65), ('Quantity', 150)], + [('Description', 10), ('Delivery Date', 120)], + [('10', 10), ('PART-A', 65), ('3.000', 150)], + [('FRAME', 65), ('PCS', 150)], + [('898.72', 120), ('2,696.16', 165)], + [('TOTAL', 65)], + ) + layout = { + 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 120}}, + 'page_glyphs': {'1': page_glyphs}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + 'tables': {'table-1': page_glyphs[:30]}, + }, + } + monkeypatch.setattr(service.db.session, 'get', lambda _model, _id: SimpleNamespace(id=77)) + + result = service.suggest_coordinate_reconstruction( + {'document_id': 77, 'table_id': 'table-1'}, actor_id=None, layout_snapshot=layout, + ) + + assert result['table_bbox_source'] == 'page_coordinate_derived' + assert len(result['subrow_layouts']) == 3 + + def test_coordinate_profile_rows_merge_only_declared_physical_layouts(): """v2 主行必须有行号,续行按 row_offset 合并,合计或额外文本不得混入明细。""" rows = reconstruct_coordinate_profile_rows( @@ -306,6 +373,26 @@ def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_ } +def test_coordinate_profile_rows_apply_shared_affine_matrix_to_all_regions(): + """订单行必须消费订单头相同的矩阵变换,禁止仅支持旧 translate 键。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('00010', 10), ('PART-A', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + table_region={'x0': 0, 'y0': .10, 'x1': 1, 'y1': .20}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .10, 'x1': 1, 'y1': .20}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .10, 'x1': .25, 'y1': .20}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .10, 'x1': 1, 'y1': .20}}, + ]}], + coordinate_transform={ + 'status': 'applied', 'matrix': [1.0, 0.0, 0.0, 0.0, 1.0, .10], + 'anchor_ids': ['title'], 'reason_codes': [], + }, + ) + + # 关键断言:仅矩阵键存在时,行字段仍以同一运行时坐标系读取。 + assert [row.fields for row in rows] == [{'customer_po_line_no': '00010', 'customer_part_number': 'PART-A'}] + + def test_coordinate_profile_rows_reject_invalid_selected_anchor_frame_transform(): """非 matcher 认可的变换不得悄悄回退为绝对坐标取值。""" kwargs = { @@ -897,6 +984,7 @@ def test_profile_order_carries_coordinate_field_evidence_into_observation(): 'page_no': 1, 'table_id': 'table-1', 'value_bbox': {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30}, 'glyph_indices': [5, 6, 7], 'token_ids': ['g5', 'g6', 'g7'], + 'evidence_ref': 'layout:9:p1:table-1:part-id', 'bbox_text': 'PART-A', 'quote_source': 'glyph_region', 'source': 'pdf_coordinate', 'has_value_coordinate': True, 'coordinate_status': 'candidate', 'highlight_quality': 'candidate', @@ -907,13 +995,51 @@ def test_profile_order_carries_coordinate_field_evidence_into_observation(): schema={'schema_version_id': 1, 'checksum': 'a' * 64}, definition=definition, table=table, ) + from app.services.shipping_notice.order_extraction_workflow import _normalize_profile_order_observations + + _normalize_profile_order_observations( + [order], default_value_source='coordinate_ocr', coordinate_transform=None, + ) observation = order['lines'][0]['fields'][0]['observations'][0] assert observation['value'] == 'PART-A' + # 统一 Observation 合同:坐标路径也必须显式声明最终值源,而不是只藏在 layout_evidence。 + assert observation['value_source'] == 'native_pdf' + assert observation['evidence_ref'] == 'layout:9:p1:table-1:part-id' + assert observation['transform_ref'] == {'kind': 'legacy_absolute'} assert observation['layout_evidence']['page_no'] == 1 assert observation['layout_evidence']['value_bbox'] == {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30} assert observation['layout_evidence']['token_ids'] == ['g5', 'g6', 'g7'] +def test_profile_observation_preserves_ocr_source_and_applied_transform(): + """OCR 证据与受限变换必须在统一 Observation 中可审计,不能伪装为原生 PDF。""" + from app.services.shipping_notice.order_extraction_workflow import _normalize_profile_order_observations + + order = { + 'header_fields': [], + 'lines': [{'fields': [{'field_id': 'part-id', 'observations': [{ + 'value': 'PART-A', 'document_id': 9, + 'layout_evidence': {'source': 'ocr_coordinate', 'evidence_ref': 'layout:9:p1:t1:c1'}, + }]}]}], + } + transform = { + 'status': 'applied', 'matrix': [1.01, 0, .02, 0, .99, .01], + 'anchor_count': 3, 'residual': .002, + } + + _normalize_profile_order_observations( + [order], default_value_source='coordinate_ocr', coordinate_transform=transform, + ) + + observation = order['lines'][0]['fields'][0]['observations'][0] + assert observation['value_source'] == 'ocr' + assert observation['evidence_ref'] == 'layout:9:p1:t1:c1' + assert observation['transform_ref'] == { + 'kind': 'coordinate_transform', 'status': 'applied', + 'matrix': [1.01, 0, .02, 0, .99, .01], 'anchor_count': 3, 'residual': .002, + } + + def test_coordinate_reconstruction_uses_x_y_and_continuation_rules(): """行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。""" result = _reconstruct(_glyphs( diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index c6f9719a..968a7b0d 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -601,6 +601,36 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H' +def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app): + """同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。""" + with app.app_context(): + document = _document() + current = record_inline_layout_snapshot(document, { + **_snapshot(), + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + document.current_layout_version = current + stale_run_layout = { + **_snapshot(), + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'sources': {'pages': {'1': 'ocr_coordinate'}}, + }, + } + + restored = ensure_on_demand_coordinate_evidence( + document=document, layout=stale_run_layout, page_nos={1}, + ) + + assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT' + assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate' + + def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch): """同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。""" with app.app_context(): @@ -644,6 +674,35 @@ def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypat } +def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(app, monkeypatch): + """原 PDF 无字符且 OCR 不可用时不得伪造坐标,调用方必须转 Review。""" + with app.app_context(): + document = _document() + layout = { + **_snapshot(), + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 80}}], + 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, + } + page = SimpleNamespace(page_no=1, width=100, height=200, image=None, characters=[]) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content: [page], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', + lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError('ocr unavailable')), + ) + + restored = ensure_on_demand_coordinate_evidence( + document=document, layout=layout, page_nos={1}, + ) + + assert not restored['coordinate_evidence'].get('page_glyphs') + + def test_layout_document_budget_creates_unsupported_audit_versions(app): """超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index 9c2b72ec..ca754496 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -12,6 +12,7 @@ from decimal import Decimal from types import SimpleNamespace from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate +from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan from app.services.shipping_notice.order_extraction_workflow import ( _apply_stp_route_adjudication, _coordinate_profile_rows, @@ -66,6 +67,19 @@ def _good_candidate() -> dict: } +def _frozen_generic_document(candidate: dict) -> dict: + """构造与生产 Run 一致的冻结候选和 Parse Plan,禁止测试直接旁路生产边界。""" + layout = {'status': 'ready', 'tables': [], 'layout_candidate': {}} + return { + 'document_id': 55, + 'layout_snapshot': layout, + 'layout_schema_candidates': [candidate], + 'generic_parse_plan': compile_generic_parse_plan( + candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout, + ), + } + + def test_gate_passes_clean_candidate(): """完整映射且无未解释行时 gate 通过。""" definition = {'fields': [_field('part_number', required=True), _field('qty', required=True)]} @@ -595,11 +609,7 @@ def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch): 'order_document_profiles': [], 'intakes': [{ 'intake_no': 'SNI-001', - 'documents': [{ - 'document_id': 55, - 'layout_snapshot': {'status': 'ready', 'tables': []}, - 'layout_schema_candidates': [candidate], - }], + 'documents': [_frozen_generic_document(candidate)], }], }, ) @@ -645,11 +655,7 @@ def test_template_parse_failure_falls_back_to_generic(monkeypatch): 'order_document_profiles': [{'schema_version_id': 1}], 'intakes': [{ 'intake_no': 'SNI-001', - 'documents': [{ - 'document_id': 55, - 'layout_snapshot': {'status': 'ready', 'tables': []}, - 'layout_schema_candidates': [candidate], - }], + 'documents': [_frozen_generic_document(candidate)], }], }, ) diff --git a/backend/tests/test_shipping_generic_parse_plan.py b/backend/tests/test_shipping_generic_parse_plan.py new file mode 100644 index 00000000..7d1d3020 --- /dev/null +++ b/backend/tests/test_shipping_generic_parse_plan.py @@ -0,0 +1,95 @@ +""" +tests/test_shipping_generic_parse_plan.py + +用途:验证自动标注候选必须先冻结为 Parse Plan,且 Plan 不能跨 Schema/Layout/候选复用。 +依赖:generic_parse_plan、generic_order_gate。 +逻辑:覆盖生产通用解析的身份门禁;任一输入漂移均 fail-closed 到 Review。 +""" + +from types import SimpleNamespace + +from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate +from app.services.shipping_notice.generic_parse_plan import ( + compile_generic_parse_plan, + validate_generic_parse_plan, +) + + +def _candidate() -> dict: + return { + 'page_no': 1, 'table_id': 'table-1', 'mapping_status': 'candidate', + 'columns': [{'column_index': 0, 'field_id': 'part', 'field_code': 'part_number', 'status': 'mapped'}], + 'rows': [{'row_index': 1, 'role': 'data', 'fields': [{ + 'field_id': 'part', 'field_code': 'part_number', 'value': 'ABC', + 'cell_id': 'cell-1', 'evidence_ref': 'layout:1:cell-1', + }]}], + 'row_role_summary': {'data': 1}, 'unmapped_nonempty_column_indices': [], + } + + +def _definition() -> dict: + return {'fields': [{ + 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, + 'required': True, 'value_type': 'string', 'aliases': ['Part'], + }]} + + +def _evaluate(*, plan, candidates, layout): + return evaluate_generic_extraction_gate( + candidates=candidates, parse_plan=plan, require_parse_plan=True, layout_snapshot=layout, + definition=_definition(), schema={'schema_version_id': 1, 'checksum': 'a' * 64}, + intake={'intake_no': 'SNI-1'}, unit=SimpleNamespace(document_id=1), + ) + + +def test_frozen_parse_plan_allows_clean_generic_deterministic_candidate(): + """自动标注经 Plan 冻结、证据绑定和 Gate 后才可进入确定性解析。""" + candidate = _candidate() + layout = {'layout_candidate': {'pages': [{'page_no': 1}]}} + plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout) + + result = _evaluate(plan=plan, candidates=[candidate], layout=layout) + + assert result.passed is True + + +def test_missing_parse_plan_blocks_production_generic_route(): + """候选本身再完整,未冻结 Plan 也不得作为生产事实。""" + result = _evaluate(plan=None, candidates=[_candidate()], layout={'layout_candidate': {}}) + + assert result.passed is False + assert 'generic_parse_plan_missing' in result.gate_reason_codes + + +def test_parse_plan_blocks_runtime_candidate_drift(): + """冻结后运行时候选变化均不得以旧 Plan 自动建单。""" + candidate = _candidate() + layout = {'layout_candidate': {'pages': [{'page_no': 1}]}} + plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout) + changed_candidate = _candidate() + changed_candidate['rows'][0]['fields'][0]['value'] = 'CHANGED' + + result = _evaluate(plan=plan, candidates=[changed_candidate], layout=layout) + + assert result.passed is False + assert 'generic_parse_plan_runtime_candidate_changed' in result.gate_reason_codes + + +def test_parse_plan_blocks_schema_or_layout_drift(): + """冻结 Plan 不能跨 Schema 或 Layout 复用,防止自动标注结果污染其他文档。""" + candidate = _candidate() + layout = {'layout_candidate': {'pages': [{'page_no': 1}]}} + plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout) + + schema_changed = validate_generic_parse_plan( + plan=plan, schema_checksum='b' * 64, layout_snapshot=layout, runtime_candidates=[candidate], + ) + layout_changed = validate_generic_parse_plan( + plan=plan, schema_checksum='a' * 64, + layout_snapshot={'layout_candidate': {'pages': [{'page_no': 2}]}}, runtime_candidates=[candidate], + ) + + assert schema_changed.passed is False + assert 'generic_parse_plan_schema_changed' in schema_changed.reason_codes + assert layout_changed.passed is False + assert 'generic_parse_plan_layout_changed' in layout_changed.reason_codes diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py index 926913bb..cceaa7e6 100644 --- a/backend/tests/test_shipping_notice_business_case.py +++ b/backend/tests/test_shipping_notice_business_case.py @@ -12,7 +12,7 @@ from app import db from app.core.errors import ConflictError from app.models import ShippingCase, ShippingCustomer, ShippingNotice from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task -from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task +from app.services.shipping_notice.task_workflow import create_task def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingNotice: @@ -126,59 +126,3 @@ def test_create_task_rejects_without_customer(app): assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK' -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_batch_revision_inherits_parent_case(app): - """真实批量建单路径中的 revision 必须继承父任务业务单。""" - with app.app_context(): - customer = _active_customer(short_code='REV') - case = resolve_shipping_case_for_new_task(created_by_id=None) - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - parent = _task('SN-CASE-BATCH-PARENT', case_id=case.id) - parent.customer_resolution_status = 'confirmed' - db.session.add(parent) - db.session.commit() - - result = create_batch_tasks({ - 'notice_items': [{ - 'source_type': 'manual', - 'raw_text': 'revision notice', - 'document_version': 2, - 'supersedes_task_id': parent.id, - 'duplicate_resolution_type': 'revision', - }], - 'defer_parse': True, - }) - task = ShippingNotice.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one() - assert task.shipping_case_id == case.id - assert task.supersedes_task_id == parent.id - assert task.customer_resolution_status == 'confirmed' - assert ShippingCase.query.count() == 1 - - -@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c') -def test_batch_force_create_uses_new_case(app): - """真实批量建单路径中的 force_create 必须创建独立业务单。""" - with app.app_context(): - customer = _active_customer(short_code='FRC') - original_case = resolve_shipping_case_for_new_task(created_by_id=None) - original = _task('SN-CASE-FORCE-SOURCE', case_id=original_case.id) - db.session.add(original) - db.session.commit() - - result = create_batch_tasks({ - 'notice_items': [{ - 'source_type': 'manual', - 'raw_text': 'forced notice', - 'duplicate_source_task_id': original.id, - 'duplicate_resolution_type': 'force_create', - 'customer_id': customer.id, - }], - 'defer_parse': True, - }) - task = ShippingNotice.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one() - assert task.shipping_case_id != original_case.id - assert task.duplicate_source_task_id == original.id - assert task.customer_resolution_status == 'confirmed' - assert ShippingCase.query.count() == 2 diff --git a/backend/tests/test_shipping_notice_intakes_lifecycle.py b/backend/tests/test_shipping_notice_intakes_lifecycle.py index 7d2b2c04..73334d52 100644 --- a/backend/tests/test_shipping_notice_intakes_lifecycle.py +++ b/backend/tests/test_shipping_notice_intakes_lifecycle.py @@ -101,6 +101,62 @@ def test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallba assert completed['layout_status'] == 'completed' assert completed['layout_summary']['failed'] == 1 + +def test_active_intake_list_omits_heavy_candidate_review_details(app, shipping_user): + """活跃列表保留恢复所需字段,但不得传输审核证据与裁决历史。""" + from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation + + with app.app_context(): + asset, intake = _seed_parsed_intake( + shipping_user.id, + intake_no='SNI-LIGHT-LIST-001', + hash_value='light-list-hash', + ) + intake.conversation_id = 'conversation-light-list' + document = ShippingOrderDocument( + intake_id=intake.id, + asset_id=asset.id, + document_type='attachment', + attachment_key='order.pdf', + filename='order.pdf', + content_hash='light-list-document-hash', + classification='order_notice', + parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + db.session.add(ShippingOrderCandidate( + candidate_no='SNC-LIGHT-LIST-001', + intake_id=intake.id, + primary_document_id=document.id, + candidate_key='light-list-candidate', + structured_result_json={ + 'business_summary': {'po_number': 'PO-LIGHT-001'}, + 'extraction': { + 'field_adjudication': {'observation_history': ['large-history']}, + 'customer_matches': [{'customer': 'large-match'}], + }, + }, + evidence_json=[{'text': 'large-evidence'}], + selected=True, + validation_status='ready', + )) + db.session.commit() + + rows = list_active_intakes_for_conversation( + user_id=shipping_user.id, + conversation_id='conversation-light-list', + ) + + assert len(rows) == 1 + candidate = rows[0]['candidates'][0] + assert candidate['candidate_no'] == 'SNC-LIGHT-LIST-001' + assert candidate['po_number'] == 'PO-LIGHT-001' + assert candidate['selected'] is True + assert 'evidence' not in candidate + assert 'field_adjudication' not in candidate + assert 'customer_matches' not in candidate + def test_candidate_review_duplicate_api_and_access_guards(app, client): """Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。""" from app.core.auth.jwt import issue_local_access_token diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index f9567eba..04e0749d 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -41,7 +41,10 @@ from app.models import ( ) from app.services.chat.log_service import merge_chat_log_payload from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary -from app.services.shipping_notice.order_extraction import persist_order_extraction_result +from app.services.shipping_notice.order_extraction import ( + _discard_resolved_worker_field_conflicts, + persist_order_extraction_result, +) from app.services.shipping_notice.order_extraction_merge import merge_unit_orders from app.services.shipping_notice.open_existing_reservation_backfill import ( backfill_exact_file_open_existing_reservations, @@ -84,6 +87,9 @@ def _ensure_order_schema() -> dict[str, str]: configs.append({ 'field_id': field['id'], 'display_name': code, 'required': required, 'aliases': [], 'business_purpose': business_purposes.get(code, 'general'), + # Reservation 是自动建单的流程匹配键;证据不足必须阻断 STP,不能仅作为诊断。 + 'auto_create_key_field': code == 'reservation_id', + 'minimum_confidence': 0.85 if code == 'reservation_id' else None, 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], 'evidence_policy': { 'required': True, 'source_precedence': ['attachment_text', 'backend_table', 'dify_llm'], @@ -115,6 +121,111 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it() assert assessment['missing_process_fields'] == ['reservation_id'] +def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app): + """派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。""" + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None) + customer_line = order_schema_service.save_field( + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + line_no = order_schema_service.save_field( + {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + part = order_schema_service.save_field( + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + qty = order_schema_service.save_field( + {'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None, + ) + draft = order_schema_service.create_draft({}, actor_id=None) + + def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict: + return { + 'field_id': field['id'], 'display_name': field['field_code'], 'required': required, + 'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general', + 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_text'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': comparator, + } + + saved = order_schema_service.save_draft(draft['id'], { + 'fields': [ + config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'), + config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'), + config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'), + config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'), + ], + 'derivation_rules': [{ + 'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True, + 'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no', + 'strategy': 'copy_if_empty', 'scope': 'line', + }], + 'expected_lock_version': draft['lock_version'], + }) + published = order_schema_service.publish( + draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], + ) + _user, _session, intake, document, _runtime_context = _seed_extraction_input() + document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10' + db.session.commit() + + result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'source_intake_no': intake.intake_no, 'primary_document_id': document.id, + 'classification': 'shipping_request', 'classification_confidence': 0.99, + 'header_fields': [], + 'lines': [{'fields': [ + {'field_id': customer_line['id'], 'observations': [{ + 'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99, + }]}, + {'field_id': part['id'], 'observations': [{ + 'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99, + }]}, + {'field_id': qty['id'], 'observations': [{ + 'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99, + }]}, + ]}], + 'conflicts': [{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + }]}) + + candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() + decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions'] + assert any( + item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived' + for item in decisions + ) + assert not any( + item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing' + for item in candidate.conflicts_json + ) + assert 'blocking_conflict' not in result['pending_orders'][0]['reasons'] + + +def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field(): + """最终 Schema 仍阻断的必填/关键字段,不得被已接受的旧 Decision 静默放行。""" + conflicts = _discard_resolved_worker_field_conflicts( + [{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + decisions=[{ + 'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived', + }], + blocked_fields=['line_no'], + ) + + assert conflicts == [{ + 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }] + + def test_candidate_validation_projects_customer_po_number_to_legacy_candidate_field(): """当前动态 Schema 的客户 PO 必须投影到 Candidate 兼容字段,供履约链路读取。""" assessment = assess_candidate_business_summary({ @@ -837,7 +948,7 @@ def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_r assert result['pending_count'] == 2 assert result['non_shipping_count'] == 0 assert result['created_with_missing_fields_count'] == 0 - assert result['batch_no'] is None + assert 'batch_no' not in result candidates = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).all() assert len(candidates) == 2 assert len({item.candidate_key for item in candidates}) == 2 @@ -1032,10 +1143,6 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', lambda **_kwargs: dict(duplicate_result), ) - monkeypatch.setattr( - 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_candidate', - lambda **_kwargs: dict(duplicate_result), - ) context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) result = _persist_test_orders({ @@ -1133,8 +1240,8 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part assert document.order_extraction_status == 'partially_completed' -def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_review(app): - """同文件最新 Candidate 按 PO/SKU/qty 唯一命中时,只补旧任务空 Reservation 并保留人工复核。""" +def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app): + """同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() existing = ShippingNotice( @@ -1195,7 +1302,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev assert values['part_number'] == 'P123456' assert values['qty'] == 24 assert values['reservation_id'] == '1000140351' - assert existing.review_status == 'rsv_req' + # Reservation 已补齐,状态机必须退出 rsv_req;仍保留解析复核,禁止自动确认或推进。 + assert existing.review_status == 'parse_review' assert existing.pending_human_reason == 'low_confidence' assert 'process_field_gate' not in (existing.step_payload_json or {}) assert existing.error_message is None @@ -1281,7 +1389,11 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): assert result['pending_count'] == 1 assert 'blocking_conflict' in result['pending_orders'][0]['reasons'] candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() - assert any(item['reason'] == 'cross_source_conflict' for item in candidate.conflicts_json) + # 当前裁决以受信表格/PDF 值为准;仍必须作为关键字段冲突阻断 STP。 + assert any( + item['field'] == 'reservation_id' and item['reason'] == 'pdf_preferred' + for item in candidate.conflicts_json + ) adjudication = candidate.structured_result_json['extraction']['field_adjudication'] reservation_observations = [ item for item in adjudication['observations'] diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index d610f7be..d3e03450 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -19,37 +19,10 @@ from app.services.shipping_notice.query_service import ( resolve_task_from_payload, serialize_task, task_export_error_message, - task_sort_key, ) from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT -def test_chat_match_result_payload_uses_unified_actions_only(): - """Chat 匹配结果不得再把旧 action_buttons 作为按钮来源。""" - from app.services.shipping_notice.chat_action_handlers import _match_result_payload - - payload = _match_result_payload( - "SN-ACTIONS-ONLY", - { - "data": { - "match_status": "shortage", - "line_results": [], - "shortage": {"lines": []}, - }, - "action_buttons": [{"id": "legacy_retry"}], - "ui_state": { - "actions": { - "primary": {"code": "open_shortage_review", "enabled": True}, - "secondary": [], - }, - }, - }, - ) - - assert payload["actions"]["primary"]["code"] == "open_shortage_review" - assert "action_buttons" not in payload - - def test_get_task_by_ref_supports_task_no_and_numeric_id(app): """task_no 与数字主键均应能解析到同一任务。""" with app.app_context(): @@ -434,7 +407,7 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app): assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench' assert hit['ui_state']['lifecycle_stage'] == 'order_review' assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [ - 'available', 'current', 'unavailable', 'unavailable', + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', ] counts = count_my_todos(user.id) diff --git a/backend/tests/test_shipping_notice_stp_acceptance.py b/backend/tests/test_shipping_notice_stp_acceptance.py index 399f8b69..75138bef 100644 --- a/backend/tests/test_shipping_notice_stp_acceptance.py +++ b/backend/tests/test_shipping_notice_stp_acceptance.py @@ -290,28 +290,6 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon }) -def test_export_ready_ui_state_entry_is_task_workbench(app) -> None: - """场景:Excel 待人工上传登记待办深链入口为任务处理工作台。""" - with app.app_context(): - task = ShippingNotice( - task_no="SN-STP-ENTRY", - source_type="manual", - export_file_path="/tmp/x.xlsx", - export_file_name="x.xlsx", - ) - state = build_task_ui_state(task) - assert state["checkpoint"]["kind"] == "wait_manual_upload" - assert state["summary"]["entry_surface"] == "task_workbench" - button_ids = [ - item.get("code") - for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] - if item - ] - assert "mark_manual_uploaded" in button_ids - assert "download_excel" in button_ids - assert "action_buttons" not in state - - def test_my_todos_owner_can_handle_admin_view_only(app) -> None: """场景:跨会话待办 + 权限 — 创建者 can_handle,管理员看他人任务只读。""" with app.app_context(): diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index e51b98f0..63725e0f 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -703,79 +703,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa assert len(list(trigger.glob("inventory_export_*.json"))) == 1 -@pytest.mark.auto_rpa -def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path, monkeypatch): - from datetime import datetime, timedelta - - from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING - - headers = _tool_headers(app) - trigger = tmp_path / "inventory_triggers" - trigger.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 - monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", - lambda: None, - ) - - create_res = client.post( - "/api/shipping-notice/tools/create_batch", - headers=headers, - json={"conversation_id": "conv-rpa-batch-retry"}, - ) - batch_no = create_res.get_json()["batch_no"] - task_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={ - "batch_no": batch_no, - "conversation_id": "conv-rpa-batch-retry", - "source_type": "manual", - }, - ) - task_id = task_res.get_json()["task_id"] - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) - task.pending_human_reason = PH_RPA_PENDING - task.step_payload_json = { - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", - "entry_url": "https://s360.dbschenker.com/", - "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, - } - } - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.add( - ShippingTaskEvent( - task_id=task.id, - event_type="inventory_rpa_triggered", - detail_json={"attempt": 1}, - created_at=datetime.utcnow() - timedelta(seconds=5), - ) - ) - db.session.commit() - - with app.app_context(): - result = retry_batch_pending_tasks(batch_no) - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - assert result["started"] == 1 - assert result["skipped"] == 0 - assert task.pending_human_reason == PH_RPA_EXHAUSTED - assert task.pending_human_reason == PH_RPA_EXHAUSTED - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1 - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1 - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1 - assert len(list(trigger.glob("inventory_export_*.json"))) == 0 - - def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client): headers = _tool_headers(app) diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index 7337d045..bf85defe 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -121,8 +121,8 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: assert "stage_context" in detailed_state -def test_build_task_ui_state_exposes_five_business_stages_and_unified_actions(app) -> None: - """没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。""" +def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: + """旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-STAGE-ACTIONS", @@ -131,15 +131,15 @@ def test_build_task_ui_state_exposes_five_business_stages_and_unified_actions(ap source_type="manual", ) state = build_task_ui_state(task) - assert state["stage"]["code"] == "order_review" - assert state["stage"]["index"] == 2 + assert state["stage"]["code"] == "unclassified" + assert state["stage"]["index"] == 0 assert state["stage"]["total"] == 5 assert state["actions"]["primary"] is None assert state["actions"]["secondary"] == [] -def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None: - """正式工作台的五个入口必须由后端下发,页面不能按阶段顺序自行生成。""" +def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None: + """正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-LIFECYCLE-ENTRIES", @@ -148,14 +148,8 @@ def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> Non source_type="manual", ) state = build_task_ui_state(task) - assert state["lifecycle_stage"] == "order_review" - assert state["lifecycle_entries"] == [ - {"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"}, - {"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"}, - {"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, - {"code": "freight_upload", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, - {"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, - ] + assert state["lifecycle_stage"] == "unclassified" + assert state["lifecycle_entries"] == [] def test_task_ui_state_ignores_superseded_process_execution(app) -> None: @@ -209,7 +203,7 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None: assert state['stage']['code'] == 'fulfillment_prep' assert state['current_step']['code'] == 'fulfillment_prep' assert [entry['state'] for entry in state['lifecycle_entries']] == [ - 'available', 'available', 'current', 'unavailable', + 'available', 'available', 'current', 'unavailable', 'unavailable', ] @@ -244,8 +238,8 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No ] -def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None: - """库存匹配与无证据历史上传分别映射通知准备和货代上传。""" +def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None: + """库存和上传历史字段不能再替代正式 Gate 生成生命周期。""" with app.app_context(): fulfillment = ShippingNotice( task_no="SN-UI-FULFILLMENT", @@ -258,11 +252,11 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages( source_type="manual", upload_status="uploaded", ) - assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep" + assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified" upload_state = build_task_ui_state(upload, include_stage_context=True) - assert upload_state["stage"]["code"] == "freight_upload" + assert upload_state["stage"]["code"] == "unclassified" # 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。 - assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual" + assert upload_state["stage_context"]["upload"]["outcome"] == "not_started" def test_entry_surface_parse_review_is_review_workbench(app) -> None: diff --git a/backend/tests/test_shipping_order_auto_freeze_execution.py b/backend/tests/test_shipping_order_auto_freeze_execution.py deleted file mode 100644 index 2eacd8ec..00000000 --- a/backend/tests/test_shipping_order_auto_freeze_execution.py +++ /dev/null @@ -1,55 +0,0 @@ -""" -tests/test_shipping_order_auto_freeze_execution.py - -用途:锁定自动冻结候选范围不得扩大到 Run 内其它已消费任务。 -依赖:order_auto_freeze_execution._freeze_created_tasks。 -逻辑:未传入本轮 eligible candidate_nos 时不得扫描全 Run consumed 集合。 -""" - -from __future__ import annotations - -from types import SimpleNamespace -from unittest.mock import MagicMock, patch - -from app.services.shipping_notice.order_auto_freeze_execution import _freeze_created_tasks - - -def test_freeze_created_tasks_requires_eligible_candidate_nos(): - """空 eligible 集合必须直接返回,禁止扩大冻结范围。""" - run = SimpleNamespace(id=1) - with patch( - 'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate' - ) as candidate_model: - frozen, blocked = _freeze_created_tasks(run=run, policy={'enabled': True}, candidate_nos=[]) - assert frozen == [] - assert blocked == [] - candidate_model.query.filter_by.assert_not_called() - - -def test_freeze_created_tasks_filters_accepted_selected_and_eligible_nos(): - """冻结查询必须约束 accepted + selected 且限定本轮 candidate_nos。""" - run = SimpleNamespace(id=42) - query = MagicMock() - query.filter_by.return_value = query - query.filter.return_value = query - query.order_by.return_value = query - query.all.return_value = [] - - with patch( - 'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate' - ) as candidate_model: - candidate_model.query = query - frozen, blocked = _freeze_created_tasks( - run=run, - policy={'enabled': True}, - candidate_nos=['CAND-A', 'CAND-B'], - ) - assert frozen == [] - assert blocked == [] - query.filter_by.assert_called_once_with( - order_extraction_run_id=42, - is_current_version=True, - candidate_status='accepted', - selected=True, - ) - assert query.filter.call_count == 2 diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index d08894cf..b1596abd 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -626,10 +626,16 @@ def test_template_sample_status_accepts_materialized_document_with_failed_layout status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id) # 上传成功只取决于样本文档已物化;失败 Layout 留到预览复核阶段按需恢复或报错。 - assert status == { - 'intake_no': 'SNI-LAYOUT-STATUS', 'parse_status': 'parsed', 'document_count': 1, - 'document_ids': [document.id], 'error_code': None, - } + assert status['intake_no'] == 'SNI-LAYOUT-STATUS' + assert status['parse_status'] == 'parsed' + assert status['document_count'] == 1 + assert status['document_ids'] == [document.id] + assert status['error_code'] is None + # 文档物化成功与 Layout 失败分开呈现,前端不可把上传成功误当成可自动标注。 + assert status['layout_status'] == 'failed' + assert status['evidence_status'] == 'pending' + assert status['automark_ready'] is False + assert status['sample_readiness'] == [] def test_template_sample_status_accepts_materialized_document_without_modeling_table(app): @@ -663,10 +669,15 @@ def test_template_sample_status_accepts_materialized_document_without_modeling_t status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id) # Layout 预热结果不是上传门禁,不能把可读 PDF 误报为上传失败。 - assert status == { - 'intake_no': 'SNI-EMPTY-TABLE-STATUS', 'parse_status': 'parsed', 'document_count': 1, - 'document_ids': [document.id], 'error_code': None, - } + assert status['intake_no'] == 'SNI-EMPTY-TABLE-STATUS' + assert status['parse_status'] == 'parsed' + assert status['document_count'] == 1 + assert status['document_ids'] == [document.id] + assert status['error_code'] is None + assert status['layout_status'] == 'ready' + assert status['evidence_status'] == 'pending' + assert status['automark_ready'] is False + assert status['sample_readiness'] == [] def test_template_sample_status_keeps_file_materialization_failure_fail_closed(app): @@ -691,10 +702,91 @@ def test_template_sample_status_keeps_file_materialization_failure_fail_closed(a status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id) # 文件本身未能物化时必须保持失败,不能借上传/Layout 解耦绕过。 - assert status == { - 'intake_no': 'SNI-MATERIALIZATION-FAILED', 'parse_status': 'failed', 'document_count': 0, - 'document_ids': [], 'error_code': 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED', - } + assert status['intake_no'] == 'SNI-MATERIALIZATION-FAILED' + assert status['parse_status'] == 'failed' + assert status['document_count'] == 0 + assert status['document_ids'] == [] + assert status['error_code'] == 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED' + assert status['layout_status'] == 'pending' + assert status['evidence_status'] == 'pending' + assert status['automark_ready'] is False + assert status['sample_readiness'] == [] + + +def test_refresh_profile_sample_readiness_freezes_ready_annotation_evidence(app): + """ready Layout 与唯一主表齐备时,统一服务必须回填样本的完整冻结身份。""" + with app.app_context(): + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation') + profile = db.session.get(ShippingOrderDocumentProfile, draft['id']) + + state = service.refresh_profile_sample_readiness(profile=profile, sample=sample) + db.session.commit() + frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id) + + # 同一服务既供轮询使用也供入队使用,冻结后的 Job 必须取得当前 Layout 的完整身份。 + assert state['automark_ready'] is True + assert state['evidence_status'] == 'frozen' + assert frozen.layout_version_id is not None + assert frozen.layout_payload_checksum is not None + assert frozen.source_content_hash == 's' * 64 + assert frozen.evidence_frozen_at is not None + + +def test_profile_sample_readiness_rejects_current_layout_content_identity_mismatch(app): + """当前 Layout 的来源内容身份异常时不得冻结或入队,避免旧坐标混入新样本。""" + with app.app_context(): + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation') + profile = db.session.get(ShippingOrderDocumentProfile, draft['id']) + document = db.session.get(ShippingOrderDocument, sample.document_id) + version = db.session.get(ShippingDocumentLayoutVersion, document.current_layout_version_id) + version.source_content_hash = 'x' * 64 + db.session.flush() + + state = service.refresh_profile_sample_readiness(profile=profile, sample=sample) + with pytest.raises(Exception) as caught: + service.require_profile_sample_automark_ready(profile=profile, sample=sample) + + # 关键断言:Layout 可见并不足够,Document 与 Layout 的不可变内容身份不一致必须失败关闭。 + assert state['automark_ready'] is False + assert state['evidence_status'] == 'stale' + assert state['reason_code'] == 'layout_content_hash_mismatch' + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE' + + +def test_profile_sample_readiness_requires_manual_main_table_selection_for_multiple_tables(app): + """未绑定主表而 Layout 存在多个表时不得猜测第一张表,必须返回人工选择门禁。""" + with app.app_context(): + from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload + + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation') + profile = db.session.get(ShippingOrderDocumentProfile, draft['id']) + document = db.session.get(ShippingOrderDocument, sample.document_id) + version = db.session.get(ShippingDocumentLayoutVersion, document.current_layout_version_id) + payload = dict(version.payload_json) + tables = [dict(item) for item in payload['tables']] + tables.append({**tables[0], 'table_id': 'second-table'}) + payload['tables'] = tables + checksum, _ = canonical_layout_payload(payload) + version.payload_json = payload + version.payload_checksum = checksum + sample.table_id = None + db.session.flush() + + state = service.refresh_profile_sample_readiness(profile=profile, sample=sample) + with pytest.raises(Exception) as caught: + service.require_profile_sample_automark_ready(profile=profile, sample=sample) + + # 关键断言:多表选择不是自动标注的可推断信息,禁止以位置或顺序猜测。 + assert state['automark_ready'] is False + assert state['main_table_status'] == 'ambiguous' + assert state['reason_code'] == 'main_table_ambiguous' + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS' def test_draft_unbound_order_field_layout_does_not_require_schema_scope(app): diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index a8c96b01..1cee35c8 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -14,6 +14,7 @@ from decimal import Decimal from unittest.mock import patch import pytest +from sqlalchemy import event from sqlalchemy.orm.attributes import flag_modified from app import db @@ -935,9 +936,13 @@ def test_run_v3_freezes_layout_schema_candidate_and_policy_versions(app): ) frozen_document = run.input_snapshot_json['intakes'][0]['documents'][0] candidates = frozen_document['layout_schema_candidates'] + parse_plan = frozen_document['generic_parse_plan'] assert run.input_snapshot_json['snapshot_version'] == 3 assert candidates[0]['mapping_status'] == 'candidate' assert candidates[0]['rows'][0]['fields'][0]['cell_id'] + assert parse_plan['status'] == 'qualified' + assert parse_plan['schema_checksum'] == run.input_snapshot_json['schema']['checksum'] + assert parse_plan['candidate_checksum'] assert 'layout_table_not_accepted' in candidates[0]['issues'] # 关键断言:策略版本写入快照,且不再暴露 Dify Workflow 清单。 assert run.input_snapshot_json['policy_versions']['route_strategy_version'] == ROUTE_STRATEGY_VERSION @@ -1106,7 +1111,6 @@ def test_second_pdf_unit_can_persist_after_first_unit_consumes_shared_intake(app db.session.refresh(intake) assert intake.parse_status == 'consumed' assert intake.consumed_task_id is None - assert intake.consumed_batch_id is None result = submit_order_extraction_unit_result(run=run, unit=second_unit, orders=[]) @@ -1905,6 +1909,75 @@ def test_run_api_create_get_list_and_user_isolation(app, client): assert hidden.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND' +def test_run_list_returns_lightweight_summaries_without_full_workspace_projection(app, client, monkeypatch): + """会话恢复列表不得为每个 Run 构建文档、Case、Gate 等完整工作台投影。""" + with app.app_context(): + owner, agent, session, intake, _document = _seed_run_input(suffix='LIGHT-LIST') + run, _ = create_order_extraction_run( + user=owner, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + token = issue_local_access_token(owner) + run_no = run.run_no + conversation_id = session.session_id + + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run', + lambda _run: (_ for _ in ()).throw(AssertionError('list must not build workspace projection')), + ) + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20', + headers={'Authorization': f'Bearer {token}'}, + ) + + assert response.status_code == 200 + item = next(row for row in response.get_json()['data']['items'] if row['run_no'] == run_no) + assert item['status'] == 'queued' + assert item['summary']['total_documents'] == 0 + for forbidden in ('documents', 'handling_items', 'available_actions', 'result', 'selection_plan'): + assert forbidden not in item + + +def test_run_list_does_not_select_large_input_snapshots(app, client): + """会话恢复列表只读摘要列,不能因 upload_batch_id 再取冻结输入快照。""" + with app.app_context(): + owner, agent, session, intake, _document = _seed_run_input(suffix='LIST-SCALAR') + run, _ = create_order_extraction_run( + user=owner, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + snapshot = dict(run.input_snapshot_json) + snapshot['large_regression_payload'] = 'x' * 1_000_000 + run.input_snapshot_json = snapshot + db.session.commit() + token = issue_local_access_token(owner) + conversation_id = session.session_id + + statements: list[str] = [] + + def capture_statement(_conn, _cursor, statement, _parameters, _context, _executemany): + if 'shipping_order_processing_runs' in statement: + statements.append(statement.lower()) + + with app.app_context(): + event.listen(db.engine, 'before_cursor_execute', capture_statement) + try: + response = client.get( + f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20', + headers={'Authorization': f'Bearer {token}'}, + ) + finally: + event.remove(db.engine, 'before_cursor_execute', capture_statement) + + assert response.status_code == 200 + assert statements + assert all('input_snapshot_json' not in statement for statement in statements) + + def test_run_api_requires_upload_batch_id(app, client): """发送端缺少服务端上传批次时必须拒绝,不能回退为全会话 Intake 选择。""" with app.app_context(): @@ -2171,6 +2244,9 @@ def test_run_documents_and_summary_keep_partial_success_isolated_per_pdf(app, cl headers={'Authorization': f'Bearer {owner_token}'}, ) assert run_response.status_code == 200 + # 关键断言:重型 Run 投影必须返回可与浏览器 HAR 对齐的分段耗时,便于定位慢查询。 + assert 'run_lookup' in run_response.headers.get('Server-Timing', '') + assert 'workspace_projection' in run_response.headers.get('Server-Timing', '') run_payload = run_response.get_json()['data'] assert run_payload['summary'] == { 'total_documents': 3, @@ -2443,46 +2519,6 @@ def test_run_seen_api_keeps_cross_user_isolation(app, client): assert hidden.status_code == 404 -def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app): - """侧栏只聚合同用户同Agent的新提醒,并把失败优先级提升到 error。""" - from app.api.chat import _order_extraction_attention_by_conversation - - with app.app_context(): - owner, agent, session, intake, _document = _seed_run_input(suffix='SESSION-ATTENTION') - ignored_agent = Agent( - name='Other owner', agent_code='generic', runtime_provider='dify', dify_app_id='other-owner', - dify_api_key='key', is_active=True, - ) - db.session.add(ignored_agent) - db.session.flush() - run, _ = create_order_extraction_run( - user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - transition_order_extraction_run(run, target_status='processing') - transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable') - historical = ShippingOrderProcessingRun( - run_no='SNER-HISTORICAL-SESSION', user_id=owner.id, owner_agent_id=agent.id, - conversation_id=session.session_id, schema_version_id=run.schema_version_id, - input_snapshot_hash='e' * 64, input_snapshot_json={}, idempotency_key='f' * 64, - status='completed', phase='completed', finished_at=datetime.utcnow(), - ) - other_owner_run = ShippingOrderProcessingRun( - run_no='SNER-OTHER-OWNER', user_id=owner.id, owner_agent_id=ignored_agent.id, - conversation_id=session.session_id, schema_version_id=run.schema_version_id, - input_snapshot_hash='g' * 64, input_snapshot_json={}, idempotency_key='h' * 64, - status='completed', phase='completed', finished_at=datetime.utcnow(), attention_generated_at=datetime.utcnow(), - ) - db.session.add_all([historical, other_owner_run]) - db.session.commit() - aggregate = _order_extraction_attention_by_conversation( - user_id=owner.id, - agent_id=agent.id, - conversation_ids={session.session_id}, - ) - - assert aggregate == {session.session_id: (1, 'error')} - - def test_final_order_extraction_job_failure_marks_queued_run_failed(app): """Job 重试耗尽时必须收口 Run,避免聊天页永久显示处理中。""" with app.app_context(): @@ -2678,114 +2714,6 @@ def test_terminal_transition_updates_persisted_chat_state(app): ] -def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client): - """终态后晚到的旧卡必须在历史 GET 时按 Run 事实纠正,不能永久显示运行中。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-HISTORY') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') - transition_order_extraction_run( - run, - target_status='failed', - error_code='TEST.FAILED', - error_message='failed before card persisted', - ) - db.session.add(ChatLog( - user_id=user.id, - agent_id=agent.id, - session_id=session.session_id, - conversation_id=session.session_id, - query='', - answer='', - message_type='text', - payload={ - 'formId': f'shipping-order-extraction-run:{run.run_no}', - 'order_extraction_run_no': run.run_no, - 'shipping_order_extraction_state': {'status': 'extracting', 'terminal': False}, - }, - )) - db.session.commit() - token = issue_local_access_token(user) - session_id = session.session_id - agent_id = agent.id - - response = client.get( - f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}', - headers={'Authorization': f'Bearer {token}'}, - ) - - assert response.status_code == 200 - state = response.get_json()[-1]['payload']['shipping_order_extraction_state'] - assert state['status'] == 'failed' - assert state['terminal'] is True - assert state['availableActions'] == [ - 'view_details', 'refresh_status', 'retry_failed_attachments', - ] - assert 'failed before card persisted' not in str(response.get_json()) - - -def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(app, client): - """同一 Run 的上传记录与状态记录共存时,历史回放只能出现一张助手状态卡。""" - with app.app_context(): - user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-DEDUPLICATE') - run, _ = create_order_extraction_run( - user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], - ) - transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing') - transition_order_extraction_run(run, target_status='failed', error_message='failed once') - db.session.add_all([ - ChatLog( - user_id=user.id, - agent_id=agent.id, - session_id=session.session_id, - conversation_id=session.session_id, - query='上传附件', - answer='', - message_type='text', - payload={ - 'formId': f'shipping-order-extraction-user:{run.run_no}', - 'order_extraction_run_no': run.run_no, - }, - ), - ChatLog( - user_id=user.id, - agent_id=agent.id, - session_id=session.session_id, - conversation_id=session.session_id, - query='', - answer='', - message_type='text', - payload={ - 'formId': f'shipping-order-extraction-run:{run.run_no}', - 'order_extraction_run_no': run.run_no, - }, - ), - ]) - db.session.commit() - token = issue_local_access_token(user) - run_no = run.run_no - session_id = session.session_id - agent_id = agent.id - - response = client.get( - f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}', - headers={'Authorization': f'Bearer {token}'}, - ) - - assert response.status_code == 200 - messages = response.get_json() - state_cards = [ - item for item in messages - if item['role'] == 'assistant' - and item.get('payload', {}).get('order_extraction_run_no') == run_no - ] - assert len(state_cards) == 1 - assert state_cards[0]['payload']['shipping_order_extraction_state']['status'] == 'failed' - assert [item['role'] for item in messages] == ['user', 'assistant'] - - def test_failed_run_retry_api_returns_queued_run(app, client): """用户点击重新识别后 API 返回 202,并原位恢复同一 Run。""" with app.app_context(): @@ -2861,7 +2789,6 @@ def test_terminal_run_reparse_reuses_orphaned_consumed_intake(app, client): transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() - intake.consumed_batch_id = None intake.consumed_task_id = None db.session.commit() token = issue_local_access_token(user) @@ -2887,7 +2814,6 @@ def test_reparse_submission_accepts_orphaned_consumed_intake(app): transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() - intake.consumed_batch_id = None intake.consumed_task_id = None db.session.commit() replacement, _ = reparse_order_extraction_run( @@ -2910,7 +2836,6 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app): transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1}) intake.parse_status = 'consumed' intake.consumed_at = datetime.utcnow() - intake.consumed_batch_id = None intake.consumed_task_id = None db.session.commit() replacement, _ = reparse_order_extraction_run( @@ -3433,26 +3358,6 @@ def test_failed_reparse_restores_source_candidate_version(app): assert source.superseded_by_run_id is None -def test_only_current_version_candidate_can_be_consumed(app): - """旧版本 Candidate 即使被直接提交,也必须被建单入口拒绝。""" - from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates - - with app.app_context(): - user, _agent, _session, intake, document = _seed_run_input(suffix='SUPERSEDED') - candidate = ShippingOrderCandidate( - candidate_no='SNC-SUPERSEDED', intake_id=intake.id, primary_document_id=document.id, - candidate_key='old-version', selected=True, is_current_version=False, validation_status='ready', - ) - db.session.add(candidate) - db.session.commit() - with pytest.raises(ValidationError) as caught: - create_shipping_batch_from_candidates( - user_id=user.id, intake_nos=[intake.intake_no], candidate_nos=[candidate.candidate_no], - create_idempotency_key='test-current-version-gate', conversation_id=None, - ) - assert caught.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_FOUND' - - def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app): """管理员健康汇总应识别积压/失败并只返回安全运行元数据。""" from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health diff --git a/backend/tests/test_shipping_order_field_extraction.py b/backend/tests/test_shipping_order_field_extraction.py index 97393150..5f14313e 100644 --- a/backend/tests/test_shipping_order_field_extraction.py +++ b/backend/tests/test_shipping_order_field_extraction.py @@ -161,6 +161,34 @@ def test_anchor_frame_transform_moves_order_number_anchor_and_value_together(): assert result.value == '45001' +def test_coordinate_transform_applies_affine_matrix_to_order_header_regions(): + """订单头必须与订单行共享 matcher 已验证的仿射矩阵,而非只读取旧平移键。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'po', 'text': 'PO NO', + 'region': {'x0': .10, 'y0': .10, 'x1': .30, 'y1': .14}, + 'position_locked': True, + }, + 'absolute_value_region': {'x0': .20, 'y0': .10, 'x1': .80, 'y1': .14}, + 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 30, 40))}), + coordinate_transform={ + 'status': 'applied', + 'matrix': [1.0, 0.0, .05, 0.0, 1.0, .10], + 'anchor_ids': ['po'], + 'reason_codes': [], + }, + )[0] + + # 关键断言:仅 matrix 存在时也必须与共同 matcher 的坐标系一致。 + assert result.status == 'confirmed' + assert result.value == '45001' + + def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower(): """值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。""" profile = _profile(layout={ diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 6657fb5d..ab1ddfa9 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -1,6 +1,10 @@ """验证订单坐标模板匹配:版面签名、七维评分与解析校验门禁。""" -from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles +from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile +from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _resolve_coordinate_transform, + match_frozen_coordinate_profiles, +) from app.services.shipping_notice.document_layout.order_profile_signature import ( MATCHER_POLICY_ID, build_layout_signature, @@ -151,6 +155,69 @@ def test_anchor_frame_matches_bounded_vertical_translation_without_changing_lega assert legacy_result.candidates[0].coordinate_transform is None +def test_affine_anchor_frame_requires_explicit_opt_in_and_three_stable_anchors(): + """仿射只允许显式治理的多锚点 Profile 使用,默认平移模板不改变行为。""" + definition = _anchor_frame_profile()['definition'] + definition['coordinate_model'].update({ + 'transform_mode': 'affine', + 'anchors': [ + {'anchor_id': 'a', 'text': 'A', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .10, 'x1': .14, 'y1': .14}}, + {'anchor_id': 'b', 'text': 'B', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .10, 'x1': .64, 'y1': .14}}, + {'anchor_id': 'c', 'text': 'C', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .60, 'x1': .14, 'y1': .64}}, + ], + 'max_scale_delta': .05, + 'max_rotation_degrees': 3.0, + 'max_residual': .005, + }) + profile = OrderCoordinateProfile.model_validate(definition) + pages = {'1': {'width': 1000, 'height': 1000}} + # x 轴放大 2%,y 轴放大 1%,并整体右移 1%、下移 2%。 + glyphs = {'1': [ + {'text': 'A', 'bbox': {'x0': 122.4, 'y0': 131.2, 'x1': 142.4, 'y1': 151.2}}, + {'text': 'B', 'bbox': {'x0': 632.4, 'y0': 131.2, 'x1': 652.4, 'y1': 151.2}}, + {'text': 'C', 'bbox': {'x0': 122.4, 'y0': 636.2, 'x1': 142.4, 'y1': 656.2}}, + ]} + + transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs) + + # 关键断言:仿射矩阵仅由三个唯一锚点证明,且带可审计残差。 + assert reasons == [] + assert transform['matrix'] == [1.02, 0.0, .01, 0.0, 1.01, .02] + assert transform['anchor_ids'] == ['a', 'b', 'c'] + assert transform['residual'] == 0.0 + + +def test_affine_anchor_frame_rejects_degenerate_or_high_residual_evidence(): + """共线锚点和超残差锚点不允许形成看似可信的仿射坐标系。""" + definition = _anchor_frame_profile()['definition'] + definition['coordinate_model'].update({ + 'transform_mode': 'affine', + 'anchors': [ + {'anchor_id': 'a', 'text': 'A', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .10, 'x1': .14, 'y1': .14}}, + {'anchor_id': 'b', 'text': 'B', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .10, 'x1': .64, 'y1': .14}}, + {'anchor_id': 'c', 'text': 'C', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .60, 'x1': .14, 'y1': .64}}, + {'anchor_id': 'd', 'text': 'D', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .60, 'x1': .64, 'y1': .64}}, + ], + 'max_scale_delta': .05, + 'max_rotation_degrees': 3.0, + 'max_residual': .003, + }) + profile = OrderCoordinateProfile.model_validate(definition) + pages = {'1': {'width': 1000, 'height': 1000}} + # A/B/C 都符合平移;D 额外偏离 2%,残差必须阻断而不是被最小二乘掩盖。 + glyphs = {'1': [ + {'text': 'A', 'bbox': {'x0': 110, 'y0': 120, 'x1': 130, 'y1': 140}}, + {'text': 'B', 'bbox': {'x0': 610, 'y0': 120, 'x1': 630, 'y1': 140}}, + {'text': 'C', 'bbox': {'x0': 110, 'y0': 620, 'x1': 130, 'y1': 640}}, + {'text': 'D', 'bbox': {'x0': 630, 'y0': 620, 'x1': 650, 'y1': 640}}, + ]} + + transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs) + + assert transform is None + assert reasons == ['profile_anchor_frame_affine_residual_out_of_range'] + + def test_anchor_frame_fails_closed_when_anchor_is_missing_ambiguous_or_out_of_range(): """锚点框架不得因缺锚、重锚或超界平移降级猜测,均须成为模板硬失败。""" baseline = _layout_with_frame_anchor() @@ -248,14 +315,16 @@ def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_com 'tables': complete_layout['tables'], 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, 'matching_features': { - 'version': 'shipping-layout-matching-features.v1', + 'version': 'v1', 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, 'tables': [{ 'table_id': 'table-1', 'page_no': 1, 'bbox': [0.05, 0.25, 0.95, 0.95], - 'header_tokens': ['item', 'no', 'qty'], - 'column_centers': [0.1225, 0.2825, 0.4225], - 'column_width_ratios': [0.1611, 0.0722, 0.1167], + 'header_candidates': [{ + 'header_tokens': ['item', 'no', 'qty'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }], }], 'static_text_centers': {}, }, @@ -269,6 +338,81 @@ def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_com assert candidate.dimension_states['column_topology'] == 'matched' +def test_profile_matcher_selects_semantic_header_candidate_not_data_row_from_compacted_projection(): + """压缩投影含数据行候选时,必须用语义与列几何选真实表头,不能只比列数。""" + complete_layout = _layout() + profile = _profile('PO_A') + profile['definition']['document_match']['required_anchors'] = [] + profile = _with_signature(profile, complete_layout) + compacted_layout = { + 'tables': complete_layout['tables'], + 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, + 'matching_features': { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{ + 'bbox': [0.05, 0.25, 0.95, 0.95], + 'header_candidates': [ + { + 'header_tokens': ['ab-100', 'ea', '10'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }, + { + 'header_tokens': ['item', 'no', 'qty'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }, + ], + }], + }, + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout) + + assert result.status == 'unique_match' + assert result.candidates[0].dimension_states['header_semantic_position'] == 'matched' + + +def test_profile_matcher_rejects_incomplete_compacted_projection_as_evidence_insufficient(): + """没有候选表头事实的压缩投影不得仅凭页面和表框自动命中。""" + complete_layout = _layout() + profile = _profile('PO_A') + profile['definition']['document_match']['required_anchors'] = [] + profile = _with_signature(profile, complete_layout) + compacted_layout = { + 'tables': complete_layout['tables'], + 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, + 'matching_features': { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{'bbox': [0.05, 0.25, 0.95, 0.95]}], + }, + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout) + + assert result.status == 'evidence_insufficient' + + +def test_profile_matcher_prefers_current_glyphs_to_persisted_projection(): + """当前 Layout 有完整 glyph 时,错误持久化投影不得覆盖实时证据。""" + layout = _layout() + profile = _with_signature(_profile('PO_A'), layout) + layout['matching_features'] = { + 'version': 'v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{'bbox': [0.05, 0.25, 0.95, 0.95], 'header_candidates': [{ + 'header_tokens': ['unrelated'], 'column_centers': [.8], 'column_width_ratios': [.1], + }]}], + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout) + + assert result.status == 'unique_match' + assert result.candidates[0].dimension_states['column_topology'] == 'matched' + + def test_profile_matcher_reports_only_missing_anchor_identifiers(): """缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。""" profile = _profile('PO_A') diff --git a/backend/tests/test_shipping_order_review_field_conflict.py b/backend/tests/test_shipping_order_review_field_conflict.py index 3e9b357b..d51a97e5 100644 --- a/backend/tests/test_shipping_order_review_field_conflict.py +++ b/backend/tests/test_shipping_order_review_field_conflict.py @@ -11,6 +11,8 @@ from __future__ import annotations from types import SimpleNamespace from unittest.mock import patch +import pytest + from app.services.shipping_notice.order_review_field_conflict_service import ( project_review_case_evidence_issues, project_review_case_field_conflicts, @@ -94,6 +96,111 @@ def test_project_review_case_field_conflicts_empty_without_candidate(): assert project_review_case_field_conflicts(case) == [] +@pytest.mark.pure_unit +def test_project_review_case_field_conflicts_uses_complete_finding_source_evidence(): + """正文补充真冲突必须直接展示 PDF/邮件值与来源,不能因缺 Observation 而消失。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'line_index': 0, + 'scope': 'line', + 'severity': 'blocking', + 'reason': 'supplement_field_conflict', + 'resolution_status': 'unresolved', + 'values': ['1731.60', '1732.00'], + 'sources': [ + {'source_type': 'pdf', 'raw_value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1}}, + {'source_type': 'email_body', 'raw_value': '1732.00', 'document_id': 304, 'evidence_ref': {'row_index': 5}}, + ], + }], + structured_result_json={}, + ) + case = SimpleNamespace( + candidate_id=1, + current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]), + ) + + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + items = project_review_case_field_conflicts(case) + finally: + svc._candidate_for_case = original + + assert len(items) == 1 + assert items[0]['conflict_key'] == '0:unit_price' + assert [option['display_value'] for option in items[0]['options']] == ['1731.60', '1732.00'] + assert [option['evidence_role'] for option in items[0]['options']] == ['primary_pdf', 'context'] + assert [option['document_id'] for option in items[0]['options']] == [305, 304] + + +@pytest.mark.pure_unit +def test_project_review_case_finding_with_pdf_source_is_marked_primary_pdf(): + """补充合并的 PDF 来源未附原始 source_type 时,面板仍须标识其为主 PDF。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '0:unit_price', 'field': 'unit_price', 'line_index': 0, + 'severity': 'blocking', 'reason': 'supplement_field_conflict', + 'values': ['1', '2'], + 'sources': [ + {'source_type': 'pdf', 'raw_value': '1', 'document_id': 305, 'evidence_ref': {}}, + {'source_type': 'email_body', 'raw_value': '2', 'document_id': 304, 'evidence_ref': {}}, + ], + }], + structured_result_json={}, + ) + case = SimpleNamespace( + candidate_id=1, + current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]), + ) + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + items = project_review_case_field_conflicts(case) + finally: + svc._candidate_for_case = original + + assert items[0]['options'][0]['evidence_role'] == 'primary_pdf' + + +@pytest.mark.pure_unit +def test_project_review_case_legacy_supplement_evidence_gap_is_visible_not_a_blank_panel(): + """历史补充冲突证据不足必须投影为可见证据问题,不能静默阻断资格。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '-1:unit_price', + 'field': 'unit_price', + 'severity': 'blocking', + 'reason': 'supplement_conflict_evidence_insufficient', + 'resolution_status': 'unresolved', + 'scope': 'unscoped', + 'recovery_action': 'reparse_current_pdf', + }], + structured_result_json={}, + ) + case = SimpleNamespace(current_draft=None) + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + conflicts, evidence_issues = svc._project_review_case_candidate_findings(case) + finally: + svc._candidate_for_case = original + assert conflicts == [] + assert evidence_issues == [{ + 'conflict_key': '-1:unit_price', 'field_code': 'unit_price', 'line_index': None, + 'line_key': None, 'scope': 'unscoped', 'severity': 'blocking', + 'reason': 'supplement_conflict_evidence_insufficient', 'options': [], + 'observation_ids': [], 'recovery_action': 'reparse_current_pdf', + }] + + def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_value_conflicts(): """同键证据缺失只能保留一项,并与多值字段冲突分区展示。""" candidate = SimpleNamespace( @@ -155,6 +262,34 @@ def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_ assert [item['scope'] for item in evidence_issues] == ['unscoped', 'line'] +def test_project_review_findings_omits_optional_line_no_evidence_gap(): + """line_no 非必填且可派生时,历史证据缺失不得继续显示为待确认。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'field': 'line_no', + 'severity': 'blocking', + 'reason': 'evidence_missing', + 'owning_gate_code': 'field_completeness', + }], + structured_result_json={ + 'extraction': {'field_adjudication': { + 'blocked_fields': [], + 'decisions': [{'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived'}], + }}, + }, + ) + case = SimpleNamespace(candidate_id=1, current_draft=SimpleNamespace(lines_json=[])) + + from app.services.shipping_notice import order_review_field_conflict_service as svc + + original = svc._candidate_for_case + svc._candidate_for_case = lambda _case: candidate + try: + assert project_review_case_evidence_issues(case) == [] + finally: + svc._candidate_for_case = original + + def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict(): """草稿字段已齐全时,Gate 必须通过完整性并把最新证据冲突归属到字段冲突门禁。""" case = SimpleNamespace( diff --git a/backend/tests/test_shipping_order_review_resume_service.py b/backend/tests/test_shipping_order_review_resume_service.py index 61dbe894..56ac2cf2 100644 --- a/backend/tests/test_shipping_order_review_resume_service.py +++ b/backend/tests/test_shipping_order_review_resume_service.py @@ -103,6 +103,38 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch): assert case.status == 'ready' +@pytest.mark.pure_unit +def test_resume_enqueues_auto_create_when_draft_validation_is_eligible(monkeypatch): + """保存并校验在所有 Gate 通过时必须入队 STP,而非停在 ready。""" + case = _case(can_build=True, can_auto_create=True, validation_status='ready') + monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case) + monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None) + monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: []) + monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **_kw: None) + monkeypatch.setattr(svc.db.session, 'flush', lambda: None) + monkeypatch.setattr(svc.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_projection.serialize_review_case', + lambda _c: {'case_no': case.case_no, 'status': case.status}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', + lambda **_kw: {'status': 'queued', 'job_id': 91, 'idempotency_key': 'stp-91'}, + ) + + result = svc.resume_after_review_change( + user_id=7, + case_no=case.case_no, + trigger='draft_validated', + skip_validate=True, + allow_auto_create=True, + ) + + assert result['outcome'] == 'auto_create_enqueued' + assert result['auto_gate_allowed'] is True + assert result['stp_enqueue'] == {'status': 'queued', 'job_id': 91, 'idempotency_key': 'stp-91'} + + def test_resume_auto_confirms_unique_customer_before_validating(monkeypatch): """保存校验时必须先确认唯一客户候选,再执行 Draft 校验。""" case = _case(can_build=True, can_auto_create=False, validation_status='ready') diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index 7afba6b2..c01a1ab5 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -24,13 +24,17 @@ from app.models import ( ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderCandidate, + ShippingOrderCustomerMatch, + ShippingOrderExtraction, ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingOrderReviewStream, ShippingOrderReviewCaseEvent, ShippingOrderReviewConfirmedRevision, ShippingOrderReviewWaveLine, + ShippingOrderSchemaVersion, ShippingNotice, + ShippingCustomer, User, ) from app.services.shipping_notice.order_review_projection import ( @@ -294,7 +298,7 @@ def test_review_queue_projects_each_case_po_and_lifecycle_stage(app): assert item['po_number'] == 'PO-QUEUE-001' assert item['lifecycle_stage'] == 'order_review' assert [entry['state'] for entry in item['lifecycle_entries']] == [ - 'available', 'current', 'unavailable', 'unavailable', + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', ] @@ -334,7 +338,7 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app): assert item['po_number'] == 'PO-QUEUE-002' assert item['lifecycle_stage'] == 'fulfillment_prep' assert [entry['state'] for entry in item['lifecycle_entries']] == [ - 'available', 'available', 'current', 'unavailable', + 'available', 'available', 'current', 'unavailable', 'unavailable', ] @@ -445,6 +449,51 @@ def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'res db.session.commit() +def _seed_confirmed_bill_to_for_candidate(*, candidate, run, intake, user) -> None: + """ + 为机器 Candidate 补齐可继承的 Bill-to 确认事实。 + + 核心逻辑:确认服务只从 Candidate 关联的来源 Extraction 复制已确认客户;不能以 + Candidate 摘要中的状态替代冻结所需的可审计客户事实。 + """ + customer = ShippingCustomer( + standard_name='Review Test Customer', + short_code='REV', + ) + db.session.add(customer) + db.session.flush() + extraction = ShippingOrderExtraction( + run_id=int(run.id), + intake_id=int(intake.id), + schema_version_id=int(run.schema_version_id), + input_snapshot_hash=str(run.input_snapshot_hash or ''), + input_snapshot_json={'source': 'review_test_customer_confirmation'}, + status='accepted', + normalized_result_json={}, + validation_result_json={}, + created_by_id=int(user.id), + ) + db.session.add(extraction) + db.session.flush() + candidate.order_extraction_id = int(extraction.id) + db.session.add(ShippingOrderCustomerMatch( + extraction_id=int(extraction.id), + role='bill_to', + raw_name=customer.standard_name, + normalized_name='REVIEW TEST CUSTOMER', + status='confirmed', + customer_id=int(customer.id), + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + identity_fingerprint='f' * 64, + identity_rule_version='order-customer-fingerprint.v1', + identity_components_json={'role': 'bill_to'}, + resolution_method='manual', + confirmation_reason='测试确认', + confirmed_by_id=int(user.id), + )) + + def test_reservation_summary_reads_current_draft_value_before_async_validation(): """合法预约号已保存但校验 Job 未落投影时,右栏不得误报缺失。""" case = SimpleNamespace( @@ -660,7 +709,7 @@ def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app): gate_code='document_materialization', trigger_type='system_requeue', actor_type='system', actor_id='test', idempotency_key='candidate-supersedes-active-attempt', - input_snapshot={'action_code': 'retry_with_latest_rules'}, + input_snapshot={'action_code': 'rematerialize_document'}, ) mark_attempt_running(attempt_id=attempt.id, worker_id='test') from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case @@ -2008,6 +2057,8 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-CONFIRM'}]}], 'lines': [{'fields': [ {'field_id': 'part-id', 'observations': [{'value': 'A001'}]}, @@ -2024,6 +2075,12 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app): }, ) db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] # 确认建单要求 Candidate 已绑定 OT(BE-01);测试显式物化。 @@ -2099,17 +2156,26 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [ {'field_id': 'part-id', 'observations': [{'value': 'A002'}]}, {'field_id': 'qty-id', 'observations': [{'value': '3'}]}, {'field_id': 'reservation-id', 'observations': [{'value': '3000092918'}]}, ]}]}]} - db.session.add(ShippingOrderCandidate( + machine = ShippingOrderCandidate( candidate_no='CAND-REVIEW-CONFIRM-REPLAY', intake_id=intake.id, primary_document_id=document.id, candidate_key='machine-confirm-replay', order_extraction_run_id=run.id, structured_result_json={'customer': {'resolution_status': 'confirmed'}}, - )) + ) + db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() @@ -2395,6 +2461,8 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] # 行 A 完整;行 B 缺 qty → 整单 needs_review,但 A 应可先行。 unit.result_json = {'orders': [{'header_fields': [], 'lines': [ @@ -2408,11 +2476,18 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app): {'field_id': 'reservation-id', 'observations': [{'value': '3000092902'}]}, ]}, ]}]} - db.session.add(ShippingOrderCandidate( + machine = ShippingOrderCandidate( candidate_no='CAND-REVIEW-MULTI-WAVE', intake_id=intake.id, primary_document_id=document.id, candidate_key='machine-multi-wave', order_extraction_run_id=run.id, structured_result_json={'customer': {'resolution_status': 'confirmed'}}, - )) + ) + db.session.add(machine) + _seed_confirmed_bill_to_for_candidate( + candidate=machine, + run=run, + intake=intake, + user=user, + ) db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py index 6b8497d6..41a5e576 100644 --- a/backend/tests/test_shipping_order_schema_runtime.py +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -1279,6 +1279,85 @@ def test_optional_non_key_field_evidence_missing_is_diagnostic_only(app): assert diagnostic[0].get('user_visible') is False +def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app): + """表格诊断命中可选列时,只能保留诊断,不能把它写入 blocked_fields。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + line_no = service.save_field({'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + line_no_cfg = _config(line_no['id'], '行号', value_type='string') + line_no_cfg.update({'required': False, 'auto_create_key_field': False}) + published = _save_and_publish(draft, [ + line_no_cfg, + _config(part['id'], '内部料号', value_type='string'), + ]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'Part No: ABC-123' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [{'field_id': part['id'], 'observations': [{ + 'value': 'ABC-123', 'document_id': document.id, 'quote': 'Part No: ABC-123', + }]}]}], + }, + intake_id=intake_id, snapshot_hash='q' * 64, documents=documents, actor_id=actor_id, + layout_candidates_by_document={ + int(document.id): [{'reason': 'layout_table_needs_review', 'field_codes': ['line_no']}], + }, + ) + + # 关键断言:可选行号的坐标问题不影响自动建单资格,但审计诊断必须保留。 + assert 'line_no' not in (result.get('blocked_fields') or []) + finding = next(item for item in result['findings'] if item.get('field_code') == 'line_no') + assert finding['severity'] == 'diagnostic' + assert finding['blocks_current_action'] is False + + +def test_accepted_key_field_is_not_blocked_by_unaccepted_table_mapping(app): + """关键字段已有当前可验证证据时,整表坐标诊断不能覆盖字段事实。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + unit_price = service.save_field({'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + price_cfg = _config(unit_price['id'], '单价', value_type='decimal') + price_cfg.update({'auto_create_key_field': True, 'minimum_confidence': 0.9}) + published = _save_and_publish(draft, [price_cfg]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'Unit Price 898.72' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [{'field_id': unit_price['id'], 'observations': [{ + 'value': '898.72', 'document_id': document.id, + 'quote': 'Unit Price 898.72', 'confidence': 1.0, + }]}]}], + }, + intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id, + layout_candidates_by_document={ + int(document.id): [{ + 'mapping_status': 'candidate', + 'rows': [{'role': 'data', 'fields': [{ + 'field_id': unit_price['id'], 'value': '898.72', + 'cell_id': 'price-cell', 'evidence_ref': 'layout:price-cell', + }]}], + }], + }, + ) + + # 关键断言:表格映射未被接受仍保留诊断,但已接受的单价证据不得被重新阻断。 + assert 'unit_price' not in (result.get('blocked_fields') or []) + finding = next(item for item in result['findings'] if item.get('field_code') == 'unit_price') + assert finding['severity'] == 'diagnostic' + assert finding['blocks_current_action'] is False + + def test_key_field_quality_issue_still_blocks(app): """auto_create_key_field 字段证据不足必须进入 blocked_fields(即使 required=false)。""" with app.app_context(): diff --git a/backend/tests/test_shipping_pdf_automark.py b/backend/tests/test_shipping_pdf_automark.py index 1137592a..72613973 100644 --- a/backend/tests/test_shipping_pdf_automark.py +++ b/backend/tests/test_shipping_pdf_automark.py @@ -105,7 +105,7 @@ def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_change from app.services.shipping_notice import order_document_profile_pdf_automark_service as service profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'}) - annotation = SimpleNamespace(table_id='table-1', layout_version_id=88, layout_payload_checksum='a' * 64) + annotation = SimpleNamespace(id=71, document_id=77, table_id='table-1') document = SimpleNamespace( id=77, current_layout_version_id=88, @@ -125,12 +125,22 @@ def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_change 'get', lambda model, _ident: document if model is service.ShippingOrderDocument else None, ) + from app.services.shipping_notice import order_document_profile_service as profile_service + monkeypatch.setattr( + profile_service, + 'require_profile_sample_automark_ready', + lambda **_kwargs: (_ for _ in ()).throw(ValidationError( + 'Profile sample layout is stale', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE', + )), + ) monkeypatch.setattr(service, 'enqueue', lambda *_args, **_kwargs: 9001) with pytest.raises(ValidationError) as caught: enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1) - assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' + # Layout 身份不一致必须使用可操作的 stale 错误码,不能退化为泛化配置错误。 + assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE' def test_execute_automark_rejects_job_after_document_layout_reparse(monkeypatch): diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py index 0d7249e2..ccf2b1d3 100644 --- a/backend/tests/test_shipping_process_gate_contract.py +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -187,61 +187,6 @@ def test_field_quality_block_eligibility(): assert field_quality_may_block(required=False, auto_create_key_field=False) is False -def test_projection_marks_apx_gate_as_readonly_without_executable_actions(app, monkeypatch): - """APX 历史 Gate 只可审计展示,不能再投影为可恢复业务 Gate。""" - from types import SimpleNamespace - from app.services.shipping_notice import process_gate_projection as projection - - gate = SimpleNamespace( - id=1, gate_code='inventory_candidates_calculated', sequence_no=1, - status='pending', evaluation_version=1, input_fingerprint=None, - blocking_reason_code=None, blocking_reason_json=None, - recommendation_json=None, effective_result_json={}, findings_json=None, - next_action_code=None, passed_at=None, invalidated_at=None, - latest_attempt_id=None, - ) - monkeypatch.setattr( - projection.ShippingProcessGateAttempt.query, - 'get', - lambda _id: None, - raising=False, - ) - payload = projection.serialize_process_gate(gate, include_diagnostics=False) - assert payload['gate_code'] == 'inventory_candidates_calculated' - assert payload['legacy_readonly'] is True - assert payload['allowed_actions'] == [] - assert payload['recovery_targets'] == [] - assert len(PROCESS_GATE_DEFINITIONS) == 20 - - -def test_user_gate_summary_marks_apx_execution_readonly(app, monkeypatch): - """APX Execution 不能向用户下发主动作或恢复目标。""" - from types import SimpleNamespace - from app.services.shipping_notice import process_gate_projection as projection - - execution = SimpleNamespace( - id=1, execution_no='APX-1', status='blocked', current_gate_code='inventory_candidates_calculated', - last_passed_gate_code=None, primary_next_action_code=None, responsible_party='system', - lock_version=1, review_case_id=None, task_id=1, updated_at=None, - ) - gate = SimpleNamespace( - id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='blocked_retryable', - evaluation_version=1, input_fingerprint=None, blocking_reason_code='inventory_candidates_required', - blocking_reason_json=None, recommendation_json=None, effective_result_json={}, - next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None, - ) - query = projection.ShippingProcessGate.query - monkeypatch.setattr(query, 'filter_by', lambda **_kwargs: query) - monkeypatch.setattr(query, 'order_by', lambda *_args: query) - monkeypatch.setattr(query, 'all', lambda: [gate]) - monkeypatch.setattr(projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False) - summary = projection.project_user_gate_summary(execution) - assert summary['status'] == 'legacy_readonly' - assert summary['legacy_readonly'] is True - assert summary['next_action_code'] is None - assert summary['allowed_actions'] == [] - - def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technical(app, monkeypatch): """库存匹配技术重试被隐藏时,跨阶段 RecoveryPlan 仍必须保留人工复核入口。""" from types import SimpleNamespace diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 5ef1baf3..6cbbc911 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -998,41 +998,6 @@ def test_legacy_workspace_forwarding_audit_is_structured(app): } -def test_apx_runtime_audit_is_read_only_and_counts_active_states(app): - """APX 清点只读统计运行中记录,不修改历史 Execution/Job。""" - from app import db - from app.models import Job, ShippingNotice, ShippingProcessExecution - from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state - - task = ShippingNotice(task_no='SN-APX-AUDIT') - db.session.add(task) - db.session.flush() - active = ShippingProcessExecution( - execution_no='APX-20260811-ACTIVE', task_id=task.id, status='active', - current_gate_code='inventory_snapshots_ready', - ) - historical = ShippingProcessExecution( - execution_no='APX-20260811-HIST', task_id=task.id, status='completed', - current_gate_code='inventory_matched', - ) - db.session.add_all([active, historical]) - db.session.flush() - job = Job( - domain='shipping_notice', job_type='shipping_auto_progress', task_id=task.id, - execution_id=active.id, status='queued', business_ref='APX-20260811-ACTIVE', - ) - db.session.add(job) - db.session.commit() - - result = audit_apx_runtime_state() - - assert result['execution']['active_count'] == 1 - assert result['execution']['historical_count'] == 1 - assert result['job']['active_count'] == 1 - assert ShippingProcessExecution.query.filter_by(id=active.id).one().status == 'active' - assert Job.query.filter_by(id=job.id).one().status == 'queued' - - def test_inventory_mapping_is_versioned_and_immutable_by_shape(): """Mapping 必须按文件+版本唯一,旧版本通过 superseded_by_id 留谱系。""" assert 'uq_shipping_inventory_mapping_file_version' in _unique_names(ShippingInventoryMapping) diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index 0d50e070..4ce0ce9d 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -108,7 +108,7 @@ def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason(): def test_normalize_unknown_action_codes(): """未知 / 别名动作码映射到契约或丢弃。""" - assert normalize_action_code('retry_failed_documents') == 'retry' + assert normalize_action_code('retry_failed_documents') == 'retry_failed_documents' assert normalize_action_code('open_fulfillment') == 'view_result' assert normalize_action_code('not_a_real_action') is None @@ -165,7 +165,10 @@ def test_download_excel_requires_excel_ready_fact(): with_ready = derive_available_actions( status='blocked', stage='freight_uploading', - gate={'next_action_code': 'wait_manual_upload'}, + gate={ + 'gate_code': 'manual_upload_handoff', + 'next_action_code': 'wait_manual_upload', + }, excel_ready=True, ) assert 'download_excel' in with_ready @@ -256,8 +259,8 @@ def test_map_notice_unknown_status_fail_closed(): assert map_notice_to_processing_status_stage(unknown) == ('blocked', 'waiting_review') -def test_derive_available_actions_blocked_without_retry_gate(): - """BE-04: business blocked without retry Gate must not append retry.""" +def test_derive_available_actions_without_gate_fails_closed(): + """BE-04: no Gate and no object authorization must not invent an action.""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) @@ -272,12 +275,11 @@ def test_derive_available_actions_blocked_without_retry_gate(): }, excel_ready=False, ) - assert 'retry' not in actions - assert 'open_inventory_source_review' in actions + assert actions == [] -def test_derive_available_actions_failed_adds_retry(): - """BE-04: technical failed should allow retry by default.""" +def test_derive_available_actions_failed_without_gate_does_not_add_retry(): + """BE-04: failed status alone cannot authorize a generic retry.""" from app.services.shipping_notice.processing_projection_invariants import ( derive_available_actions, ) @@ -288,7 +290,7 @@ def test_derive_available_actions_failed_adds_retry(): gate=None, excel_ready=False, ) - assert 'retry' in actions + assert actions == ['view_result'] def test_retryable_projection_uses_technical_failure_reason_mapping(): @@ -477,8 +479,8 @@ def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action(): assert payload['available_actions'] == ['retry_inventory_preparation'] -def test_waiting_human_reconcile_action_uses_projected_available_actions(): - """人工阻断存在统一对账动作时,主动作必须从当前投影动作列表中安全选取。""" +def test_waiting_human_reconcile_action_uses_gate_action(): + """人工阻断的统一对账动作必须由正式 Gate 明确下发。""" payload = apply_user_projection_fields({ 'status': 'waiting_review', 'stage': 'inventory_matching', @@ -486,11 +488,12 @@ def test_waiting_human_reconcile_action_uses_projected_available_actions(): 'gate_code': 'inventory_candidates_calculated', 'status': 'blocked', 'blocking_reason_code': 'inventory_candidates_required', + 'next_action_code': 'reconcile_and_progress', }, - 'available_actions': ['reconcile_and_progress', 'view_details'], + 'available_actions': ['view_details'], }) - # 关键断言:该分支不得因未定义局部变量返回 500,且必须选中统一恢复入口。 + # 关键断言:只能选中 Gate 明示的统一恢复入口。 assert payload['user_status'] == 'waiting_human' assert payload['primary_action']['code'] == 'reconcile_and_progress' diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index a8ff5fbe..02ff2c1d 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -27,6 +27,10 @@ from app.models import ( ShippingOrderCandidate, ShippingOrderProcessingUnit, ShippingOrderSubmission, + ShippingOrderTask, + ShippingNotice, + ShippingProcessExecution, + ShippingProcessGate, User, ) from app.services.file_assets.service import upload_file_asset @@ -34,10 +38,13 @@ from app.services.shipping_notice.intake_service import create_shipping_notice_i from app.services.shipping_notice.progress_audit_contract import ( DIRECT_PDF_ALLOWED_STAGES, ) +from app.services.shipping_notice.reconciliation_projector import ( + project_case_primary_action, +) from app.services.shipping_notice.shipping_processing_projection import ( _aggregate_eml_order_task_work_items, _batch_file_counts, - _batch_four_stage_nodes, + _batch_lifecycle_nodes, _batch_ui_state_from_items, _conversation_processing_from_work_items, _display_work_items_from_current_files, @@ -45,6 +52,7 @@ from app.services.shipping_notice.shipping_processing_projection import ( _processing_ui_state_from_item, _project_order_task_work_item, map_run_status_to_processing_status, + project_conversation_processing_summary, map_run_to_processing_stage, project_conversation_processing_items, project_intake_work_item, @@ -94,28 +102,58 @@ def test_map_run_status_to_processing_status() -> None: assert map_run_status_to_processing_status('unknown') == 'processing' +def test_waiting_human_case_promotes_authorized_create_draft_as_primary_action() -> None: + """待人工的无草稿文件必须下发创建草稿,作为文件行唯一业务入口。""" + action = project_case_primary_action( + 'waiting_human', + {'code': None, 'i18n_key': None, 'details': None}, + ['view', 'create_draft', 'validate'], + 'order_review', + ) + + # 已授权的下一项业务操作不能被裁决为空,否则文件行没有可执行入口。 + assert action == { + 'code': 'create_draft', + 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft', + } + + +def test_waiting_human_case_promotes_authorized_edit_draft_as_primary_action() -> None: + """待人工的已有草稿文件必须下发编辑草稿,而不是重复阶段导航。""" + action = project_case_primary_action( + 'waiting_human', + {'code': None, 'i18n_key': None, 'details': None}, + ['view', 'edit_draft', 'validate'], + 'order_review', + ) + + # 编辑草稿是当前文件的业务入口,validate 仍留在工作台底栏执行。 + assert action == { + 'code': 'edit_draft', + 'variant': 'primary', + 'label_key': 'shipping.actions.edit_draft', + } + + @pytest.mark.parametrize( - ('stage', 'expected_lifecycle_stage'), + ('gate_code', 'expected_lifecycle_stage'), [ ('inventory_preparation', 'fulfillment_prep'), - ('inventory_candidates_calculated', 'fulfillment_prep'), - ('inventory_candidates_frozen', 'fulfillment_prep'), - ('inventory_snapshots_ready', 'fulfillment_prep'), - ('inventory_matched', 'fulfillment_prep'), - ('excel_generated', 'fulfillment_prep'), - ('upload_receipt_recorded', 'freight_upload'), + ('inventory_matching', 'fulfillment_prep'), + ('artifact_generation', 'fulfillment_prep'), + ('freight_upload_rpa', 'freight_upload'), ], ) -def test_batch_lifecycle_nodes_maps_auto_progress_gate_stages( - stage: str, +def test_batch_lifecycle_nodes_maps_formal_gate_stages( + gate_code: str, expected_lifecycle_stage: str, ) -> None: - """自动推进 Gate 的真实阶段码必须归入对应五阶段,不能回退到接收解析。""" - nodes = _batch_four_stage_nodes([{ - 'stage': stage, - 'user_stage': stage, + """正式 Gate 必须归入对应五阶段,不能依赖历史技术阶段码。""" + nodes = _batch_lifecycle_nodes([{ 'status': 'running', 'user_status': 'running', + 'current_gate': {'gate_code': gate_code}, }]) summaries = {node['code']: node['summary']['total'] for node in nodes} @@ -126,28 +164,19 @@ def test_batch_lifecycle_nodes_maps_auto_progress_gate_stages( @pytest.mark.parametrize( ('item', 'expected_lifecycle_stage'), [ - ({'user_stage': 'inventory_match'}, 'fulfillment_prep'), - ({'user_stage': 'freight_upload'}, 'freight_upload'), - ({'user_stage': 'customer_resolving'}, 'order_review'), - ({'user_stage': 'duplicate_checking'}, 'order_review'), - ({'user_stage': 'waiting_human_review'}, 'order_review'), - # Case bundle 已归一化为业务阶段时,批次摘要与生命周期入口必须直接识别, - # 不能错误落入 unclassified 并禁用订单复核入口。 - ({'user_stage': 'order_review'}, 'order_review'), # 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。 ({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'), - ({'stage': 'document_parsing', 'user_current_gate_code': 'inventory_matching'}, 'fulfillment_prep'), # 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。 ({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'), ({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'), ], ) -def test_batch_lifecycle_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases( +def test_batch_lifecycle_nodes_uses_formal_gate_or_owning_reason( item: dict[str, object], expected_lifecycle_stage: str, ) -> None: """批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" - nodes = _batch_four_stage_nodes([{ + nodes = _batch_lifecycle_nodes([{ **item, 'status': 'waiting_human', 'user_status': 'waiting_human', @@ -158,6 +187,42 @@ def test_batch_lifecycle_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0) +def test_batch_lifecycle_nodes_without_formal_fact_is_unclassified() -> None: + """未知旧阶段保持未分类,不能凭空映射到某个业务工作面。""" + nodes = _batch_lifecycle_nodes([{ + 'status': 'waiting_human', + 'user_status': 'waiting_human', + 'user_stage': 'inventory_match', + }]) + + assert all(node['summary']['total'] == 0 for node in nodes) + + +@pytest.mark.parametrize( + ('user_stage', 'expected_lifecycle_stage'), + [ + ('candidate_creating', 'intake_parse'), + ('waiting_review', 'order_review'), + ('inventory_preparation', 'fulfillment_prep'), + ('manual_upload_handoff', 'freight_upload'), + ], +) +def test_batch_lifecycle_nodes_maps_persisted_processing_stages( + user_stage: str, + expected_lifecycle_stage: str, +) -> None: + """无 Gate 的当前文件仍须按已写入阶段完整归入五阶段,不能静默丢失。""" + nodes = _batch_lifecycle_nodes([{ + 'status': 'waiting_human', + 'user_status': 'waiting_human', + 'user_stage': user_stage, + }]) + + summaries = {node['code']: node['summary']['total'] for node in nodes} + assert summaries[expected_lifecycle_stage] == 1 + assert sum(summaries.values()) == 1 + + def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> None: """通知准备未完成时通知完成必须由后端裁决为不可进入,不能由前端自行限制。""" fulfillment_state = _processing_ui_state_from_item({ @@ -202,41 +267,6 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N 'target_lifecycle_stage': 'fulfillment_prep', }] - legacy_view_state = _processing_ui_state_from_item({ - 'user_status': 'waiting_human', - 'user_stage': 'waiting_review', - 'source_summary': {'candidate_count': 1}, - 'run_no': 'SNER-LIFECYCLE-VIEW', - 'case_no': 'SNRC-LIFECYCLE-VIEW', - 'root_order_task_no': 'OT-LIFECYCLE-VIEW', - # 历史 Review 投影仍可能下发 view;它与 view_result 一样只是后端已授权的查看入口。 - 'available_actions': ['view'], - }) - assert legacy_view_state['secondary_actions'] == [{ - 'code': 'view', - 'enabled': True, - 'execution_mode': 'navigate', - 'target_surface': 'order_lifecycle_workbench', - 'target_lifecycle_stage': 'order_review', - }] - - review_state = _processing_ui_state_from_item({ - 'user_status': 'waiting_human', - 'user_stage': 'waiting_review', - 'source_summary': {'candidate_count': 1}, - 'run_no': 'SNER-REVIEW', - 'case_no': 'SNRC-REVIEW', - 'root_order_task_no': 'OT-REVIEW', - 'available_actions': [], - }) - assert review_state['lifecycle_entries'] == [ - {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, - {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, - ] - def test_processing_ui_state_exposes_shared_gate_authority() -> None: """批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。""" @@ -360,6 +390,33 @@ def test_failed_run_overrides_stale_unit_review_stage_for_eml_leaf(app) -> None: assert leaves[0]['primary_action'] is None +def test_eml_leaf_preserves_case_business_action_instead_of_replacing_it_with_navigation(app) -> None: + """EML 文件行必须保留 Case 裁决的真实动作,五阶段入口已单独承担导航。""" + from tests.test_shipping_order_extraction_runs import _seed_run_input + + with app.app_context(): + _user, _agent, _session, intake, document = _seed_run_input(suffix='EML-KEEP-ACTION') + + leaves = _eml_aggregate_document_children( + intake=intake, + order_task_children=[{ + 'work_item_type': 'order_task', + 'work_item_no': 'DOCUMENT:KEEP-ACTION', + 'case_no': 'SORC-KEEP-ACTION', + 'current_gate': {'gate_code': 'order_review_build'}, + 'primary_action': { + 'code': 'create_draft', + 'variant': 'primary', + 'label_key': 'shipping.actions.create_draft', + }, + 'available_actions': ['create_draft'], + 'source_summary': {'document_id': document.id}, + }], + ) + + assert leaves[0]['primary_action']['code'] == 'create_draft' + + def test_intake_candidate_context_ignores_superseded_candidate(app) -> None: """历史 Candidate 只能审计,不能重新打开当前文件的生命周期入口。""" with app.app_context(): @@ -483,67 +540,44 @@ def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_s """五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。""" projection = _conversation_processing_from_work_items([ { - 'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW', - 'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf', - 'source_summary': {'document_id': 1, 'filename': 'review.pdf'}, - 'user_status': 'waiting_human', 'user_stage': 'waiting_review', + 'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW', + 'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf', + 'source_summary': {'document_id': 1, 'filename': 'review.pdf'}, + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'order_review', + 'current_gate': {'gate_code': 'field_completeness', 'status': 'blocked'}, 'blocking_reason': {'code': 'order_review_required'}, 'available_actions': [], }, { 'work_item_type': 'order_task', 'work_item_no': 'OT-UNKNOWN', - 'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf', - 'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'}, - 'user_status': 'running', 'user_stage': 'unmapped_legacy_stage', + 'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf', + 'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'}, + 'user_group': 'unclassified', + 'user_status': 'running', 'user_stage': 'unmapped_legacy_stage', 'available_actions': [], }, ]) - nodes = {node['code']: node for node in projection['four_stage_nodes']} + nodes = {node['code']: node for node in projection['lifecycle_nodes']} assert nodes['order_review']['status'] == 'blocked' assert nodes['intake_parse']['status'] == 'pending' assert projection['unclassified_summary'] == {'count': 1} -def test_batch_payload_exposes_five_nodes_and_unverified_legacy_completion_stays_freight_upload(app) -> None: - """新字段固定五节点,兼容字段同值,旧 technical completed 不得计作通知完成。""" - with app.app_context(): - projection = _conversation_processing_from_work_items([{ - 'work_item_type': 'order_task', 'work_item_no': 'OT-LEGACY-UPLOADED', - 'root_order_task_no': 'OT-LEGACY-UPLOADED', 'source_type': 'direct_pdf', - 'shipping_notice_no': 'SN-LEGACY-UPLOADED', 'has_formal_ot': True, - 'source_summary': {'document_id': 601, 'filename': 'legacy.pdf'}, - 'status': 'completed', 'stage': 'completed', - 'user_status': 'completed', 'user_stage': 'completed', - 'verified_upload_success': False, - 'available_actions': [], 'facts': {'upload_state': 'succeeded'}, - }]) - - assert [node['code'] for node in projection['lifecycle_nodes']] == [ - 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', - ] - assert projection['four_stage_nodes'] == projection['lifecycle_nodes'] - freight = next(node for node in projection['lifecycle_nodes'] if node['code'] == 'freight_upload') - assert freight['summary']['needs_action'] == 1 - assert freight['summary']['completed'] == 0 - assert projection['summary']['completed'] == 0 - assert projection['status_groups']['completed'] == [] - assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [ - 'OT-LEGACY-UPLOADED', - ] - - -def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None: +def test_batch_lifecycle_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None: """同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。""" - nodes = _batch_four_stage_nodes([{ + nodes = _batch_lifecycle_nodes([{ 'work_item_type': 'order_task', 'work_item_no': 'INTAKE:SNI-DOUBLE', 'source_type': 'eml', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'aggregate_children': [ { 'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-1', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'current_gate': {'gate_code': 'field_completeness'}, 'blocking_reason': {'code': 'required_field_missing'}, @@ -551,6 +585,7 @@ def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_roo }, { 'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-2', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'current_gate': {'gate_code': 'field_completeness'}, 'blocking_reason': {'code': 'required_field_missing'}, @@ -565,19 +600,21 @@ def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_roo assert order_review['summary']['needs_action'] == 2 -def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection() -> None: +def test_batch_lifecycle_nodes_deduplicates_a_document_to_its_latest_projection() -> None: """同一 PDF 的历史失败投影不能与当前通知准备投影重复计数或覆盖当前阶段。""" - nodes = _batch_four_stage_nodes([ - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', - 'user_status': 'failed', 'user_stage': 'document_parsing', + nodes = _batch_lifecycle_nodes([ + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'blocking_reason': {'code': 'intake_parse_failed'}, 'source_summary': {'document_id': 401, 'filename': 'same.pdf'}, }, - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', - 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', 'last_activity_at': '2026-08-15T10:00:00Z', 'blocking_reason': {'code': 'inventory_match_failed'}, 'source_summary': {'document_id': 401, 'filename': 'same.pdf'}, @@ -595,15 +632,17 @@ def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection def test_batch_file_counts_uses_the_same_current_file_representative_as_stage_summary() -> None: """同一 PDF 的历史失败项不能同时计入失败和当前处理中的文件数量。""" work_items = [ - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', - 'user_status': 'failed', 'user_stage': 'document_parsing', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-OLD', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'source_summary': {'document_id': 501, 'filename': 'same.pdf'}, }, - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', - 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'inventory_matching', 'last_activity_at': '2026-08-15T10:00:00Z', 'source_summary': {'document_id': 501, 'filename': 'same.pdf'}, }, @@ -623,15 +662,16 @@ def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None: work_items = [{ 'work_item_type': 'order_task', 'work_item_no': 'OT-GROUP-OVERRIDES-STATUS', - 'user_group': 'waiting_human', - 'user_status': 'running', - 'user_stage': 'inventory_matching', + 'user_group': 'waiting_human', + 'user_status': 'running', + 'user_stage': 'inventory_matching', + 'current_gate': {'gate_code': 'inventory_matching', 'status': 'blocked'}, 'source_summary': {'document_id': 502, 'filename': 'waiting.pdf'}, }] assert _batch_file_counts(work_items)['waiting_human_files'] == 1 fulfillment = next( - node for node in _batch_four_stage_nodes(work_items) + node for node in _batch_lifecycle_nodes(work_items) if node['code'] == 'fulfillment_prep' ) assert fulfillment['summary']['needs_action'] == 1 @@ -671,10 +711,10 @@ def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metri with app.app_context(): work_items = [{ 'work_item_type': 'order_task', - 'work_item_no': f'OT-{terminal_status.upper()}', - 'user_status': terminal_status, + 'work_item_no': f'OT-{terminal_status.upper()}', + 'user_group': terminal_status, + 'user_status': terminal_status, 'user_stage': 'freight_uploading', - # 覆盖历史兼容载荷尚未写入 user_group 的回退路径。 'status': terminal_status, 'stage': terminal_status, 'source_summary': {'document_id': 570, 'filename': 'history.pdf'}, @@ -684,10 +724,7 @@ def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metri assert projection['summary']['history'] == 1 assert projection['summary']['total_files'] == 0 assert projection['summary']['completed_files'] == 0 - assert projection['completed'] == [] - assert [row['user_task_no'] for row in projection['history']] == [ - f'OT-{terminal_status.upper()}', - ] + assert projection['status_groups']['completed'] == [] assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [ f'OT-{terminal_status.upper()}', ] @@ -729,17 +766,19 @@ def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> def test_batch_file_counts_deduplicates_reparse_versions_by_content_hash() -> None: """重解析产生新 document_id 时,内容哈希相同的 PDF 仍只计当前一项。""" work_items = [ - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-V1', - 'user_status': 'failed', 'user_stage': 'document_parsing', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-V1', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'source_summary': { 'document_id': 601, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64, }, }, - { - 'work_item_type': 'order_task', 'work_item_no': 'OT-V2', - 'user_status': 'waiting_human', 'user_stage': 'order_review', + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-V2', + 'user_group': 'waiting_human', + 'user_status': 'waiting_human', 'user_stage': 'order_review', 'last_activity_at': '2026-08-15T10:00:00Z', 'source_summary': { 'document_id': 602, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64, @@ -756,6 +795,7 @@ def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids work_items = [ { 'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V1', + 'user_group': 'failed', 'user_status': 'failed', 'user_stage': 'document_parsing', 'last_activity_at': '2026-08-15T09:00:00Z', 'source_summary': { @@ -765,6 +805,7 @@ def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids }, { 'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V2', + 'user_group': 'waiting_human', 'user_status': 'waiting_human', 'user_stage': 'order_review', 'last_activity_at': '2026-08-15T10:00:00Z', 'source_summary': { @@ -1059,8 +1100,139 @@ def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_task assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children']) +def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_counts(app) -> None: + """未知支撑附件没有 Candidate、Case、OT 时不得进入五阶段或业务文件统计。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, primary_document = _seed_run_input( + suffix='SUMMARY-SUPPORTING-ATTACHMENT', + ) + intake.source_type = 'eml' + supporting_document = ShippingOrderDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='po-info.xlsx', + filename='PO_INFO.xlsx', + content_hash='s' * 64, + classification='unknown', + parse_status='empty', + order_extraction_status='completed', + ) + db.session.add(supporting_document) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + leaves = [ + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + ] + + # 关键断言:仅验证支撑附件已被排除;主业务文档的当前阶段可随解析状态演进。 + assert int(primary_document.id) in { + int(child['source_summary']['document_id']) for child in leaves + } + assert int(supporting_document.id) not in { + int(child['source_summary']['document_id']) for child in leaves + } + + +def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app) -> None: + """首屏摘要必须下发四个文件状态数,避免概览总数与状态数来自不同合同。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-FILE-STATUS-COUNTS', + ) + intake.source_type = 'eml' + document.order_extraction_status = 'failed' + document.order_extraction_error_code = 'processing_failed' + db.session.commit() + + summary = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + )['conversation_processing']['summary'] + + # 关键断言:总文件与四个互斥状态数同源,批次概览不能因缺字段降为全 0。 + assert summary['total_files'] == 1 + assert summary['failed_files'] == 1 + assert summary['waiting_human_files'] == 0 + assert summary['processing_files'] == 0 + assert summary['completed_files'] == 0 + + +def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: + """摘要必须以正式库存 Gate 覆盖旧 OT completed,不能误显示为货代上传。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-FORMAL-GATE-OVERRIDE', + ) + candidate = ShippingOrderCandidate( + candidate_no='CAND-SUMMARY-GATE', intake_id=intake.id, + primary_document_id=document.id, candidate_key='summary-gate', + candidate_status='accepted', po_number='PO-SUMMARY-GATE', + ) + db.session.add(candidate) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-SUMMARY-GATE', user_id=user.id, conversation_id=session.session_id, + intake_id=intake.id, candidate_id=candidate.id, status='completed', stage='completed', + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-SUMMARY-GATE', user_id=user.id, conversation_id=session.session_id, + order_task_id=order_task.id, + ) + db.session.add(notice) + db.session.flush() + order_task.shipping_notice_id = notice.id + execution = ShippingProcessExecution( + execution_no='SPE-SUMMARY-GATE', task_id=notice.id, status='blocked', + current_gate_code='inventory_preparation', lock_version=1, + ) + db.session.add(execution) + db.session.flush() + notice.active_process_execution_id = execution.id + db.session.add(ShippingProcessGate( + execution_id=execution.id, gate_code='inventory_preparation', sequence_no=11, + status='blocked_manual', evaluation_version=1, lock_version=1, + blocking_reason_code='inventory_rpa_timeout', + next_action_code='retry_inventory_preparation', + )) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + leaves = [ + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + ] + leaf = next(child for child in leaves if child['source_summary']['document_id'] == document.id) + + # 关键断言:正式 Gate 是阶段与用户状态真相,旧 OT completed 只能作为兼容字段。 + assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert leaf['user_status'] == 'waiting_human' + assert leaf['blocking_reason']['code'] == 'inventory_rpa_timeout' + # 摘要批次状态必须复用同一待人工叶子裁决,聊天卡不得显示成系统处理中。 + assert payload['conversation_processing']['ui_state']['status'] == 'waiting_human' + + def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None: - """待人工附件已有 Review Case 时,叶子 ui_state 必须给出进入订单处理动作。""" + """接收解析 Case 在详情与首屏摘要中均以重解析作为文件主动作。""" with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import _materialized_run @@ -1098,6 +1270,108 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) - ] assert leaf['intake_parse_authorized'] is True + summary_payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + summary_leaf = next( + child + for rows in summary_payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == unit.document_id + ) + + # 首屏摘要不得把阶段导航 open_order_review 冒充为业务主动作; + # 否则前端隐藏导航后,用户将失去真实的重解析入口。 + assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse' + + +def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> None: + """首屏摘要有有效 Candidate 的当前 Case 必须保留复核业务动作。""" + with app.app_context(): + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-CANDIDATE-EDIT-DRAFT', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + candidate = ShippingOrderCandidate( + candidate_no='CAND-SUMMARY-EDIT-DRAFT', intake_id=intake.id, + primary_document_id=document.id, candidate_key='summary-edit-draft', + order_extraction_run_id=run.id, is_current_version=True, + candidate_status='accepted', po_number='PO-SUMMARY-EDIT-DRAFT', + ) + db.session.add(candidate) + db.session.flush() + review_case = ensure_run_review_cases(run=run)[0] + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + summary_leaf = next( + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == document.id + ) + + assert summary_leaf['case_no'] == review_case.case_no + # Draft 已存在时,文件行只能暴露当前订单复核的业务动作,不能回退成接收解析重试。 + assert summary_leaf['ui_state']['primary_action']['code'] == 'edit_draft' + assert 'edit_draft' in summary_leaf['available_actions'] + assert 'reparse' not in summary_leaf['available_actions'] + + +def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None: + """摘要投影的接收解析深链必须把同一 Case 的 Run 一并下发。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-CASE-RUN-ANCHOR', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + unit = run.extraction_plan.units[0] + unit.status = 'review_required' + unit.reason_code = 'coordinate_evidence_unavailable' + run.status = 'review_required' + run.phase = 'review_required' + review_case = ensure_review_case_for_unit(run=run, unit=unit) + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + rows = [ + row + for group in payload['conversation_processing']['status_groups'].values() + for row in group + ] + task = next(row for row in rows if row['user_task_no'] == f'INTAKE:{intake.intake_no}') + leaf = next( + child for child in task['aggregate_children'] + if child['source_summary']['document_id'] == document.id + ) + + assert leaf['case_no'] == review_case.case_no + assert leaf['run_no'] == run.run_no + assert leaf['ui_state']['lifecycle_entries'][0] == { + 'code': 'intake_parse', + 'state': 'current', + 'target_surface': 'order_lifecycle_workbench', + } + def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: """同一 Run 的失败 PDF 只能影响自身;两个待复核 PDF 仍必须保留后端裁决的入口。""" @@ -1246,10 +1520,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No 'source_summary': { 'document_id': 101, 'document_count': 1, 'filename': 'a.pdf', 'email_subject': 'FWD: Shanghai shipping notice', - }, - 'status': 'failed', 'stage': 'waiting_review', - 'user_status': 'failed', 'user_stage': 'waiting_review', - 'available_actions': ['retry_parse'], + }, + 'status': 'failed', 'stage': 'waiting_review', + 'user_group': 'failed', + 'user_status': 'failed', 'user_stage': 'waiting_review', + 'current_gate': {'gate_code': 'field_completeness'}, + 'available_actions': ['retry_parse'], 'primary_action': {'code': 'retry_parse'}, 'blocking_reason': {'code': 'intake_parse_failed'}, 'facts': {'upload_state': 'not_created'}, @@ -1262,10 +1538,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No 'source_summary': { 'document_id': 102, 'document_count': 1, 'filename': 'b.pdf', 'email_subject': 'FWD: Shanghai shipping notice', - }, - 'status': 'processing', 'stage': 'document_parsing', - 'user_status': 'running', 'user_stage': 'document_parsing', - 'available_actions': [], 'facts': {'upload_state': 'not_created'}, + }, + 'status': 'processing', 'stage': 'document_parsing', + 'user_group': 'processing', + 'user_status': 'running', 'user_stage': 'document_parsing', + 'current_gate': {'gate_code': 'document_parsing'}, + 'available_actions': [], 'facts': {'upload_state': 'not_created'}, }, ]) @@ -1279,7 +1557,7 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['summary']['total_files'] == 2 - assert projection['four_stage_nodes'][1] == { + assert projection['lifecycle_nodes'][1] == { 'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked', 'summary': { 'total': 1, @@ -1323,7 +1601,8 @@ def test_eml_aggregate_action_uses_the_same_priority_as_its_status(app) -> None: 'last_activity_at': '2026-08-14T00:00:00Z', 'source_summary': {'document_id': 201, 'document_count': 1, 'filename': 'waiting.pdf'}, 'status': 'waiting_human', 'stage': 'waiting_review', - 'user_status': 'waiting_human', 'user_stage': 'waiting_review', + 'user_status': 'waiting_human', 'user_stage': 'order_review', + 'current_gate': {'gate_code': 'order_review', 'status': 'blocked'}, 'blocking_reason': {'code': 'customer_confirmation_required'}, 'primary_action': {'code': 'confirm_customer'}, 'available_actions': ['confirm_customer'], 'facts': {'upload_state': 'not_created'}, @@ -1660,6 +1939,66 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s ) +def test_conversation_projection_prefetches_eml_attachments_once(app, shipping_user): + """同一会话多个 EML 应一次加载附件集合,避免按邮件重复查询 Document。""" + with app.app_context(): + conversation_id = f'conv-stage4-eml-prefetch-{uuid.uuid4().hex[:8]}' + intakes = [] + with patch('app.services.shipping_notice.intake_service.enqueue', return_value=9404): + for index in range(2): + created = create_shipping_notice_intake( + user_id=shipping_user.id, + asset_no=_upload_ready_asset( + shipping_user.id, + filename=f'mail-{index}.eml', + content=b'From: a@b.c\nSubject: PO\n\nbody', + ), + upload_batch_id=str(uuid.uuid4()), + conversation_id=conversation_id, + ) + intake = ShippingOrderIntake.query.filter_by( + intake_no=created['intake_no'], + ).one() + intake.source_type = 'eml' + intake.parse_status = 'consumed' + intake.order_extraction_status = 'partially_completed' + intakes.append(intake) + for index, intake in enumerate(intakes): + db.session.add_all([ + ShippingOrderDocument( + intake_id=int(intake.id), document_type='email_body', + attachment_key='__email_body__', filename=f'mail-{index}.eml', + content_hash=f'body-{index}', classification='email_context', + parse_status='parsed', + ), + ShippingOrderDocument( + intake_id=int(intake.id), document_type='attachment', + attachment_key=f'po-{index}.pdf', filename=f'po-{index}.pdf', + content_hash=f'attachment-{index}', classification='order', + parse_status='parsed', order_extraction_status='not_started', + ), + ]) + db.session.commit() + + document_selects: list[str] = [] + + def _capture_document_selects(_conn, _cursor, statement, _parameters, _context, _executemany): + if re.search(r'\bfrom\s+shipping_order_documents\b', statement, re.IGNORECASE): + document_selects.append(statement) + + event.listen(db.engine, 'before_cursor_execute', _capture_document_selects) + try: + payload = project_conversation_processing_items( + user_id=shipping_user.id, + conversation_id=conversation_id, + ) + finally: + event.remove(db.engine, 'before_cursor_execute', _capture_document_selects) + + assert payload['conversation_processing']['summary']['total_files'] == 2 + assert len(document_selects) <= 1 + + def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, shipping_user): """ order_task 投影须填充 current_gate / candidate_count / po_number,禁止全空摘要。 @@ -1745,6 +2084,7 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship assert item['source_summary']['filename'] == document.filename + def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user): """同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。""" del shipping_user @@ -1879,6 +2219,47 @@ def test_eml_aggregate_keeps_run_authorized_batch_reparse_action(app, shipping_u assert 'reparse_batch' in displayed[0]['available_actions'] +def test_conversation_projection_reparseability_read_path_does_not_lock(app, shipping_user): + """会话 GET 判断批次动作时只能读,不得发出 FOR UPDATE。""" + del shipping_user + with app.app_context(): + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, _agent, session, intake, _document = _seed_run_input(suffix='EML-BATCH-READ-ONLY') + run = _materialized_run(user=user, agent=_agent, session=session, intake=intake) + ensure_run_review_cases(run=run) + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='review_required', result={}) + db.session.commit() + + statements: list[str] = [] + + def _capture(_conn, _cursor, statement, _parameters, _context, _executemany): + statements.append(statement) + + event.listen(db.engine, 'before_cursor_execute', _capture) + try: + with patch( + 'app.services.shipping_notice.order_review_disposition_service.select_current_batch_reparse_cases', + side_effect=AssertionError('GET projection must not enter the locked write selector'), + ): + _aggregate_eml_order_task_work_items([{ + 'work_item_type': 'order_task', 'work_item_no': 'OT-EML-READ-ONLY', + 'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no, + 'status': 'review_required', 'stage': 'order_review', 'user_status': 'waiting_human', + 'user_stage': 'order_review', 'user_group': 'waiting_human', 'last_activity_at': '', + 'available_actions': ['open_order_review'], 'facts': {'upload_state': 'not_created'}, + 'source_summary': {'document_id': None, 'filename': 'mail.eml'}, + }]) + finally: + event.remove(db.engine, 'before_cursor_execute', _capture) + + assert not any('FOR UPDATE' in statement.upper() for statement in statements) + + def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user): """ BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。 diff --git a/backend/tests/test_shipping_review_confirm_auto_progress.py b/backend/tests/test_shipping_review_confirm_auto_progress.py index fb77a23a..baf98cf8 100644 --- a/backend/tests/test_shipping_review_confirm_auto_progress.py +++ b/backend/tests/test_shipping_review_confirm_auto_progress.py @@ -71,11 +71,12 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk summary = projection._project_post_confirm_auto_progress(case) - # 关键断言:刷新后可据此恢复琥珀色重试入口,且保留成功 Job 身份。 + # 关键断言:刷新后保留失败事实,但不恢复已下线的泛化 retry 入口; + # 用户必须回到当前 Gate 选择具体业务动作。 assert summary is not None assert summary['task_no'] == 'SN-STUCK-1' - assert summary['needs_retry'] is True - assert summary['status'] == 'needs_retry' + assert summary['needs_retry'] is False + assert summary['status'] == 'failed' assert summary['job_id'] == 55 assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced' diff --git a/backend/tests/test_shipping_review_line_fulfillment_decision.py b/backend/tests/test_shipping_review_line_fulfillment_decision.py index 368a644d..6891dae9 100644 --- a/backend/tests/test_shipping_review_line_fulfillment_decision.py +++ b/backend/tests/test_shipping_review_line_fulfillment_decision.py @@ -554,70 +554,6 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch): assert result['decision']['id'] == 42 -def test_create_wave_revalidates_inventory(app, monkeypatch): - """建波次前 validate_draft 后仍库存不足则拒绝。""" - from types import SimpleNamespace - - from app.services.shipping_notice import order_review_fulfillment_decision_service as svc - - draft = SimpleNamespace( - draft_version=2, - lines_json=[{ - 'line_key': 'L1', - 'qty': '10', - 'reservation_id': 'R1', - 'part_number': 'PN1', - }], - validation_result_json={ - 'line_projections': [{ - 'line_key': 'L1', - 'available_qty': '1', - 'effective_reservation_id': 'R1', - }], - }, - ) - case = SimpleNamespace( - id=1, - case_no='CASE-1', - status='ready', - current_draft=draft, - run=SimpleNamespace(run_no='RUN-1'), - ) - decision = SimpleNamespace( - decision_code=DECISION_FULFILL, - line_status='ready_to_fulfill', - required_qty='10', - is_active=True, - ) - - monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case) - monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case) - monkeypatch.setattr(svc, '_active_decision', lambda *a, **k: decision) - - called = {'validate': False} - - def _fake_validate(**kwargs): - called['validate'] = True - return {'status': 'ready'} - - monkeypatch.setattr( - 'app.services.shipping_notice.order_review_draft_service.validate_draft', - _fake_validate, - ) - - with app.app_context(): - with pytest.raises(ConflictError) as exc: - svc.create_fulfillment_wave( - user_id=1, - case_no='CASE-1', - line_keys=['L1'], - expected_draft_version=2, - idempotency_key='wave-1', - ) - assert called['validate'] is True - assert exc.value.code == 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY' - - def test_project_empty_case_without_draft(app): """无草稿行时投影应返回空列表。""" from types import SimpleNamespace diff --git a/backend/tests/test_shipping_stp_auto_create_enqueue.py b/backend/tests/test_shipping_stp_auto_create_enqueue.py index 4a10776c..9eae82d1 100644 --- a/backend/tests/test_shipping_stp_auto_create_enqueue.py +++ b/backend/tests/test_shipping_stp_auto_create_enqueue.py @@ -244,17 +244,23 @@ def test_stp_handler_accepts_worker_contract_and_finishes_owned_attempt(app): payload={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3, 'job_id': 906}, job_id=906, ) - finish_mock.assert_called_once_with( - 906, - result={'ok': True, 'message': 'done', 'task_no': 'SN-1'}, - message='done', - owned_attempt=2, - ) + finish_mock.assert_called_once() + args, kwargs = finish_mock.call_args + assert args == (906,) + assert kwargs['message'] == 'done' + assert kwargs['owned_attempt'] == 2 + assert kwargs['result'] == { + 'ok': True, + 'message': 'done', + 'task_no': 'SN-1', + 'contract_version': 'shipping-recovery-v1-phase1', + 'status': 'ok', + } fail_mock.assert_not_called() -def test_stp_handler_uses_fail_job_contract_for_business_failure(app): - """业务失败必须使用 fail_job(error/result/retryable/owned_attempt),不得传旧参数名。""" +def test_stp_handler_marks_business_failure_blocked_manual(app): + """业务失败必须停止自动重试并提供人工复核入口。""" from app.jobs.context import JobContext from app.jobs.handlers import shipping_stp_auto_create as handler @@ -279,13 +285,15 @@ def test_stp_handler_uses_fail_job_contract_for_business_failure(app): ) as fail_mock: handler.handle_shipping_stp_auto_create(ctx, {'job_id': 907}) - fail_mock.assert_called_once_with( - 907, - error='not eligible', - result=result, - retryable=True, - owned_attempt=1, - ) + fail_mock.assert_called_once() + args, kwargs = fail_mock.call_args + assert args == (907,) + assert kwargs['error'] == 'not eligible' + assert kwargs['retryable'] is False + assert kwargs['owned_attempt'] == 1 + assert kwargs['result']['blocking_reason'] == 'SHIPPING.STP_NOT_ELIGIBLE' + assert kwargs['result']['next_action'] == 'open_order_review' + assert kwargs['result']['contract_version'] == 'shipping-recovery-v1-phase1' finish_mock.assert_not_called() diff --git a/backend/tests/test_shipping_stp_match_completed_gate.py b/backend/tests/test_shipping_stp_match_completed_gate.py index 782108d5..122fd621 100644 --- a/backend/tests/test_shipping_stp_match_completed_gate.py +++ b/backend/tests/test_shipping_stp_match_completed_gate.py @@ -8,35 +8,54 @@ tests/test_shipping_stp_match_completed_gate.py from __future__ import annotations -from types import SimpleNamespace - +from app import db +from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch from app.services.shipping_notice.fulfillment_workflow import match_completed -def test_match_completed_rejects_partial(): +def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingNotice: + """写入正式行匹配事实,供 Excel 门禁读取。""" + task = ShippingNotice(task_no=task_no, source_type='manual') + db.session.add(task) + db.session.flush() + db.session.add_all([ + ShippingNoticeLineInventoryMatch( + task_id=task.id, + line_key=f'L{index}', + match_result=row['match_result'], + inventory_status='ready', + shortage_qty=row.get('shortage_qty', '0'), + is_current=True, + ) + for index, row in enumerate(rows, start=1) + ]) + db.session.flush() + return task + + +def test_match_completed_rejects_partial(app): """partial 即使存在 ok 行也不得进入 Excel。""" - task = SimpleNamespace( - match_status='partial', - line_results_json=[ - {'line_status': 'ok'}, - {'line_status': 'shortage'}, - ], - ) - assert match_completed(task) is False + with app.app_context(): + task = _task_with_current_matches( + task_no='SN-MATCH-PARTIAL', + rows=[{'match_result': 'matched'}, {'match_result': 'not_found', 'shortage_qty': '1'}], + ) + assert match_completed(task) is False -def test_match_completed_requires_all_ok_fulfillable(): +def test_match_completed_requires_all_ok_fulfillable(app): """fulfillable 且全部 ok 才允许制单。""" - ok = SimpleNamespace( - match_status='fulfillable', - line_results_json=[{'line_status': 'ok'}, {'disposition': 'ok'}], - ) - mixed = SimpleNamespace( - match_status='fulfillable', - line_results_json=[{'line_status': 'ok'}, {'line_status': 'not_found'}], - ) - assert match_completed(ok) is True - assert match_completed(mixed) is False + with app.app_context(): + ok = _task_with_current_matches( + task_no='SN-MATCH-OK', + rows=[{'match_result': 'matched'}, {'match_result': 'matched'}], + ) + mixed = _task_with_current_matches( + task_no='SN-MATCH-MIXED', + rows=[{'match_result': 'matched'}, {'match_result': 'not_found'}], + ) + assert match_completed(ok) is True + assert match_completed(mixed) is False def test_match_step_progress_partial_is_needs_human_not_100(): diff --git a/backend/tests/test_shipping_stp_phase3_auto_create.py b/backend/tests/test_shipping_stp_phase3_auto_create.py index 0c777d92..b80f7cf5 100644 --- a/backend/tests/test_shipping_stp_phase3_auto_create.py +++ b/backend/tests/test_shipping_stp_phase3_auto_create.py @@ -10,6 +10,8 @@ from __future__ import annotations from types import SimpleNamespace +from app import db +from app.models import ShippingNotice from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits from app.services.shipping_notice.stp_inventory_freeze import ( @@ -86,38 +88,25 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch): }, ) - task = SimpleNamespace( - inventory_source_status=None, - inventory_source_code=None, - inventory_connector_type=None, - inventory_warehouse_id=None, - inventory_source_method=None, - inventory_source_config_version=None, - inventory_routing_fingerprint=None, - step_payload_json={}, - destination_code=None, - destination_city=None, - destination_country=None, - warehouse_hint=None, - inventory_source_confirmed_by=None, - inventory_source_confirmed_at=None, - current_order_extraction_id=None, - ) - result = freeze_stp_inventory_candidates_on_task( - task, - line_projections=[{ - 'line_key': 'L1', - 'candidate_inventory_source_codes': ['DBS_DUB'], - 'selection_mode': 'rule', - 'routing_status': 'resolved', - 'matched_rule_ids': [1], - }], - ) - assert result.status == 'resolved' - assert task.inventory_source_status == 'resolved' - assert task.inventory_source_code == 'DBS_DUB' - assert task_frozen_inventory_source_codes(task) == ['DBS_DUB'] - assert is_inventory_source_stable(task) is True + with app.app_context(): + task = ShippingNotice(task_no='SN-STP-FREEZE-ONE', source_type='manual') + db.session.add(task) + db.session.flush() + result = freeze_stp_inventory_candidates_on_task( + task, + line_projections=[{ + 'line_key': 'L1', + 'candidate_inventory_source_codes': ['DBS_DUB'], + 'selection_mode': 'rule', + 'routing_status': 'resolved', + 'matched_rule_ids': [1], + }], + ) + assert result.status == 'resolved' + assert task.inventory_source_status == 'resolved' + assert task.inventory_source_code == 'DBS_DUB' + assert task_frozen_inventory_source_codes(task) == ['DBS_DUB'] + assert is_inventory_source_stable(task) is True def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch): @@ -143,35 +132,22 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch monkeypatch.setattr(gate_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v2') monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source) - task = SimpleNamespace( - inventory_source_status=None, - inventory_source_code=None, - inventory_connector_type=None, - inventory_warehouse_id=None, - inventory_source_method=None, - inventory_source_config_version=None, - inventory_routing_fingerprint=None, - step_payload_json={}, - destination_code=None, - destination_city=None, - destination_country=None, - warehouse_hint=None, - inventory_source_confirmed_by=None, - inventory_source_confirmed_at=None, - current_order_extraction_id=None, - ) - result = freeze_stp_inventory_candidates_on_task( - task, - line_projections=[{ - 'line_key': 'L1', - 'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'], - 'selection_mode': 'rule', - 'routing_status': 'ambiguous', - 'matched_rule_ids': [9], - }], - ) - assert result.status == 'candidates_frozen' - assert task.inventory_source_status == 'candidates_frozen' - assert not task.inventory_source_code - assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert is_inventory_source_stable(task) is True + with app.app_context(): + task = ShippingNotice(task_no='SN-STP-FREEZE-MANY', source_type='manual') + db.session.add(task) + db.session.flush() + result = freeze_stp_inventory_candidates_on_task( + task, + line_projections=[{ + 'line_key': 'L1', + 'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'], + 'selection_mode': 'rule', + 'routing_status': 'ambiguous', + 'matched_rule_ids': [9], + }], + ) + assert result.status == 'candidates_frozen' + assert task.inventory_source_status == 'candidates_frozen' + assert not task.inventory_source_code + assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] + assert is_inventory_source_stable(task) is True diff --git a/backend/tests/test_shipping_workbench_action_contract.py b/backend/tests/test_shipping_workbench_action_contract.py index a92e35b0..61918544 100644 --- a/backend/tests/test_shipping_workbench_action_contract.py +++ b/backend/tests/test_shipping_workbench_action_contract.py @@ -31,7 +31,6 @@ _TABLE: list[tuple[str, str, str, str]] = [ ('confirm_customer', 'confirm_customer', 'pre_create', 'open_customer_dialog'), ('resolve_field_conflicts', 'resolve_field_conflicts', 'pre_create', 'focus_field_conflicts'), ('adjudicate_duplicate', 'adjudicate_duplicate', 'pre_create', 'focus_duplicate_panel'), - ('open_inventory_source_review', 'open_inventory_source_review', 'pre_create', 'open_inventory_candidates'), ('confirm_inventory_source', 'open_inventory_source_review', 'post_create', 'todo'), ('match_inventory', 'open_inventory_match_review', 'post_create', 'todo'), ('rematch', 'open_inventory_match_review', 'post_create', 'todo'), @@ -42,8 +41,7 @@ _TABLE: list[tuple[str, str, str, str]] = [ ('download_excel', 'download_excel', 'post_create', 'download'), ('mark_manual_uploaded', 'open_manual_upload', 'post_create', 'todo'), ('open_manual_upload', 'open_manual_upload', 'post_create', 'todo'), - ('retry', 'retry', 'any', 'retry'), - ('retry_parse', 'retry', 'pre_create', 'retry'), + ('retry_parse', 'retry_parse', 'pre_create', 'retry'), ('refresh', 'refresh', 'any', 'refresh_strip'), ('view_result', 'view_result', 'terminal', 'view_result'), ('open_fulfillment', 'view_result', 'terminal', 'view_result'), @@ -101,13 +99,13 @@ def test_post_create_projection_keeps_fulfillment_write_chain(): status='blocked', stage='inventory_matching', gate={ - 'gate_code': 'inventory_match', + 'gate_code': 'inventory_matching', 'status': 'blocked', 'next_action_code': 'match_inventory', 'blocking_reason_code': 'inventory_shortage', 'attempt_no': 1, }, - legacy_actions=['download_excel'], + authorized_actions=['download_excel'], excel_ready=True, shipping_notice_no='SN-100', ) @@ -175,7 +173,7 @@ def test_pre_create_keeps_inventory_source_review_but_strips_match(): 'blocking_reason_code': 'require_manual_review', 'attempt_no': 1, }, - legacy_actions=['match_inventory', 'generate_excel'], + authorized_actions=['match_inventory', 'generate_excel'], excel_ready=False, shipping_notice_no=None, ) diff --git a/backend/tests/test_shipping_workspace_legacy_audit.py b/backend/tests/test_shipping_workspace_legacy_audit.py deleted file mode 100644 index 91d82c61..00000000 --- a/backend/tests/test_shipping_workspace_legacy_audit.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -tests/test_shipping_workspace_legacy_audit.py - -用途:证明旧工作台写入口(retry / confirm-inventory-source)具备审计四要素。 -依赖:Flask app/client fixture、ShippingTaskEvent、ShippingAuditEvent。 -逻辑:模拟工作台 JWT 用户调用旧路由,断言操作人、时间、内容与前后快照均落库。 -""" -from __future__ import annotations - -from app import db -from app.core.auth.jwt import issue_local_access_token -from app.models import ( - ShippingAuditEvent, - ShippingCase, - ShippingCustomer, - ShippingNotice, - ShippingTaskEvent, - User, -) - - -def _workspace_headers(app, username: str = 'legacy-audit-user') -> tuple[dict[str, str], int]: - """签发工作台用户头,并返回 headers 与 user_id。""" - with app.app_context(): - user = User.query.filter_by(username=username).first() - if user is None: - user = User(username=username, email=f'{username}@example.com', role='user') - db.session.add(user) - db.session.commit() - token = issue_local_access_token(user) - return { - 'Authorization': f'Bearer {token}', - 'Content-Type': 'application/json', - }, int(user.id) - - -def test_workspace_retry_records_actor_and_snapshots(app, client): - """retry 须写入 TaskEvent + ShippingAuditEvent,含操作人与前后快照。""" - headers, user_id = _workspace_headers(app, 'legacy-audit-retry') - with app.app_context(): - customer = ShippingCustomer(standard_name='Legacy Audit Co', short_code='LGA', status='active') - case = ShippingCase(case_no='SC-LEGACY-AUDIT-RETRY', customer=customer) - task = ShippingNotice( - task_no='SN-LEGACY-AUDIT-RETRY', - user_id=user_id, - shipping_case=case, - source_type='manual', - review_status='parse_review', - pending_human_reason='low_confidence', - error_message='timeout', - customer_resolution_status='confirmed', - raw_content='客户:ACME\nA001 x 1', - ) - db.session.add_all([customer, case, task]) - db.session.commit() - - res = client.post( - '/api/workspace/shipping-tasks/SN-LEGACY-AUDIT-RETRY/retry', - headers=headers, - json={'comment': '人工重试'}, - ) - assert res.status_code == 200 - envelope = res.get_json() - assert envelope['success'] is True - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no='SN-LEGACY-AUDIT-RETRY').one() - event = ( - ShippingTaskEvent.query.filter_by(task_id=task.id, event_type='task_retry_requested') - .order_by(ShippingTaskEvent.id.desc()) - .first() - ) - # 关键断言:旧 retry 入口不再匿名,且前后状态可对比。 - assert event is not None - assert event.actor_id == user_id - assert event.created_at is not None - assert event.before_json.get('status') == 'failed' - assert event.after_json.get('status') in {'created', 'parsed'} - audit = ( - ShippingAuditEvent.query.filter_by( - aggregate_type='shipping_task', - aggregate_id='SN-LEGACY-AUDIT-RETRY', - action='retry_task', - ) - .order_by(ShippingAuditEvent.id.desc()) - .first() - ) - assert audit is not None - assert int(audit.actor_id or 0) == user_id - assert audit.before_snapshot_json is not None - assert audit.after_snapshot_json is not None - assert audit.created_at is not None diff --git a/backend/tests/test_shipping_xfa_formal_extraction_route.py b/backend/tests/test_shipping_xfa_formal_extraction_route.py index 19d24a2e..f4a6ded0 100644 --- a/backend/tests/test_shipping_xfa_formal_extraction_route.py +++ b/backend/tests/test_shipping_xfa_formal_extraction_route.py @@ -553,6 +553,12 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes): assert str(values['price_unit']) == expected['lines'][0]['price_unit'] assert Decimal(str(values['amount'])) == Decimal(expected['lines'][0]['amount']) assert str(values['delivery_date']) == expected['lines'][0]['delivery_date'] + # XFA 仍以 datasets 为正式值源,并把冻结字段 evidence 暴露为统一 Observation 引用。 + material_observation = route.orders[0]['lines'][0]['fields'][0]['observations'][0] + assert material_observation['value_source'] == 'xfa_dataset' + assert isinstance(material_observation['evidence_ref'], dict) + assert material_observation['evidence_ref']['source'] == 'xfa_dataset' + assert 'transform_ref' not in material_observation blob = json.dumps(route.decision, ensure_ascii=False, default=str) assert '' not in blob assert 'datasets_xml' not in blob diff --git a/backend/tests/test_task_retry_decision_service.py b/backend/tests/test_task_retry_decision_service.py deleted file mode 100644 index ce5d8074..00000000 --- a/backend/tests/test_task_retry_decision_service.py +++ /dev/null @@ -1,292 +0,0 @@ -""" -tests/test_task_retry_decision_service.py - -用途:锁定统一重试决策树的只读分支(noop / fetch)与行级 retryable。 -依赖:task_retry_decision_service、line_inventory_match_projection。 -逻辑:不启全量 Flask;验证决策优先级。 -""" - -from __future__ import annotations - -from types import SimpleNamespace - -from app.services.shipping_notice.line_inventory_match_projection import project_line_retryable -from app.services.shipping_notice.task_retry_decision_service import ( - ACTION_FETCH_INVENTORY, - ACTION_NOOP, - ACTION_REMATCH, - ACTION_AUTO_PROGRESS, - ACTION_FAILED, - _execute, - decide_retry_action_only, - _is_inventory_rpa_active, -) - - -def _task(**kwargs): - defaults = { - 'task_no': 'OT-1', - 'id': 1, - 'upload_status': None, - 'pending_human_reason': None, - 'inventory_lines_json': None, - 'inventory_snapshot_id': None, - 'inventory_source_status': 'resolved', - 'inventory_source_code': 'DSB_SLC', - 'inventory_source_confirmed_by': None, - 'order_data_version': 3, - } - defaults.update(kwargs) - return SimpleNamespace(**defaults) - - -def test_project_line_retryable_hides_shortage_and_running(): - assert project_line_retryable( - inventory_allowed_actions=['retry_inventory_preparation'], - user_line_status='shortage', - ) is False - assert project_line_retryable( - inventory_allowed_actions=['retry_inventory_preparation'], - user_line_status='inventory_file_missing', - inventory_rpa_running=True, - ) is False - assert project_line_retryable( - inventory_allowed_actions=['retry_inventory_preparation'], - user_line_status='inventory_file_missing', - ) is True - - -def test_decide_completed_is_noop(): - task = _task(upload_status='uploaded') - decided = decide_retry_action_only(task, scope='task') - assert decided['action'] == ACTION_NOOP - assert decided['reason_code'] == 'already_completed' - - -def test_decide_missing_snapshot_fetch(monkeypatch): - task = _task(inventory_snapshot_id=None, inventory_lines_json=None) - monkeypatch.setattr( - 'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable', - lambda _t: True, - ) - decided = decide_retry_action_only(task, scope='task') - assert decided['action'] == ACTION_FETCH_INVENTORY - - -def test_decide_rpa_pending_already_running(): - task = _task(pending_human_reason='rpa_pending') - decided = decide_retry_action_only(task, scope='task') - assert decided['action'] == ACTION_NOOP - assert decided['reason_code'] == 'already_running' - - -def test_fulfillable_task_without_excel_continues_auto_progress(monkeypatch): - """库存已完全匹配但 Excel 尚未生成时,任务级重试必须推进后续 Gate。""" - task = _task( - inventory_snapshot_id=7, - inventory_lines_json=[{'part_number': 'PN-1'}], - ) - monkeypatch.setattr( - 'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable', - lambda _t: True, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service._task_match_hint', - lambda _t: {}, - ) - - decided = decide_retry_action_only(task, scope='task') - - assert decided['action'] == ACTION_AUTO_PROGRESS - - -def test_structured_failed_attempt_overrides_stale_rpa_pending(monkeypatch): - """逐源 Attempt 已失败时,旧 rpa_pending 摘要不得阻止用户手动重试。""" - task = _task(task_no='OT-FAILED', pending_human_reason='rpa_pending') - - class _Query: - calls = 0 - - def filter(self, *_args): - return self - - def order_by(self, *_args): - return self - - def first(self): - self.calls += 1 - if self.calls == 1: - return None - return SimpleNamespace(status='failed') - - monkeypatch.setattr( - 'app.models.ShippingTaskInventoryRpaAttempt.query', - _Query(), - raising=False, - ) - assert _is_inventory_rpa_active(task) is False - - -def test_structured_running_attempt_blocks_duplicate_retry(monkeypatch): - """逐源 Attempt 仍在运行时,必须拦截重复派发。""" - task = _task(task_no='OT-RUNNING', pending_human_reason=None) - - class _Query: - def filter(self, *_args): - return self - - def order_by(self, *_args): - return self - - def first(self): - return SimpleNamespace(status='running') - - monkeypatch.setattr( - 'app.models.ShippingTaskInventoryRpaAttempt.query', - _Query(), - raising=False, - ) - assert _is_inventory_rpa_active(task) is True - - -def test_execute_rolls_back_before_returning_unexpected_failure(monkeypatch): - """下游数据库失败后,返回失败结果前必须清理 Session,供审计链继续写入。""" - task = _task(task_no='OT-ROLLBACK') - rollback_calls = [] - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service.db.session.rollback', - lambda: rollback_calls.append(True), - ) - monkeypatch.setattr( - 'app.services.shipping_notice.tools.auto_progress', - lambda _payload: (_ for _ in ()).throw(RuntimeError('database write failed')), - ) - - result = _execute( - task=task, - user_id=7, - decided={'action': ACTION_AUTO_PROGRESS}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='auto-progress:OT-ROLLBACK:v3', - line_key=None, - ) - - # 关键断言:审计在 _execute 返回后才写,故必须已恢复可用事务。 - assert rollback_calls == [True] - assert result['action'] == ACTION_FAILED - assert result['status'] == 'failed' - - -def test_execute_fetch_retry_rpa_submits_formal_gate_action(monkeypatch): - """正式 retry_rpa 必须提交正式 Gate Action。""" - task = _task(task_no='OT-TRIGGER-DIRECT', inventory_snapshot_id=None, inventory_lines_json=None) - captured: dict[str, object] = {} - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running'}, - ) - - result = _execute( - task=task, - user_id=7, - decided={'action': ACTION_FETCH_INVENTORY}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='inventory-fetch:OT-TRIGGER-DIRECT:DSB_SLC:v3', - line_key=None, - trigger='conversation_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_preparation' - - -def test_execute_rematch_submits_formal_gate_action(monkeypatch): - """库存匹配节点重试必须提交正式 Gate Action。""" - task = _task(task_no='OT-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[]) - captured: dict[str, object] = {} - monkeypatch.setattr( - 'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running'}, - ) - - result = _execute( - task=task, - user_id=7, - decided={'action': ACTION_REMATCH}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='inventory-rematch:OT-REMATCH:v3', - line_key=None, - trigger='user_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_from_matching' - - -def test_execute_fetch_uses_formal_gate_action_instead_of_legacy_inventory(monkeypatch): - """外部 retry_rpa 必须提交正式 Gate Action,不能直接执行旧库存函数。""" - task = _task(task_no='OT-FORMAL-RETRY', inventory_snapshot_id=None, inventory_lines_json=None) - captured: dict[str, object] = {} - - import app.services.shipping_notice.task_retry_decision_service as service - import app.services.shipping_notice.inventory_workflow as inventory_workflow - - monkeypatch.setattr(inventory_workflow, 'ensure_inventory', lambda _payload: (_ for _ in ()).throw( - AssertionError('legacy inventory workflow must not be called by external retry') - )) - monkeypatch.setattr( - service, - '_request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'fetch_inventory'}, - raising=False, - ) - - result = service._execute( - task=task, - user_id=7, - decided={'action': ACTION_FETCH_INVENTORY}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='formal-retry:OT-FORMAL-RETRY:v3', - line_key=None, - trigger='user_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_preparation' - - -def test_execute_rematch_uses_formal_gate_action_instead_of_legacy_match(monkeypatch): - """外部 rematch 必须提交正式 Gate Action,不能直接执行旧匹配函数。""" - task = _task(task_no='OT-FORMAL-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[]) - captured: dict[str, object] = {} - - import app.services.shipping_notice.task_retry_decision_service as service - import app.services.shipping_notice.tools as shipping_tools - - monkeypatch.setattr(shipping_tools, 'match_inventory', lambda _payload: (_ for _ in ()).throw( - AssertionError('legacy match workflow must not be called by external retry') - )) - monkeypatch.setattr( - service, - '_request_formal_gate_action', - lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'rematch'}, - raising=False, - ) - - result = service._execute( - task=task, - user_id=7, - decided={'action': ACTION_REMATCH}, - continue_auto_progress=False, - decision_version=3, - idempotency_key='formal-rematch:OT-FORMAL-REMATCH:v3', - line_key=None, - trigger='user_retry', - ) - - assert result['status'] == 'running' - assert captured['action_code'] == 'retry_inventory_from_matching' diff --git a/docs/demand.md b/docs/demand.md index 337a3907..370942ce 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -283,6 +283,8 @@ - 历史口径曾写“一封 EML = 一个 Intake”;该语义保留为 EML Intake 规则,并扩展直接 PDF Intake。上传阶段只做快览:读取邮件头、正文白名单 HTML 表格快照和附件目录,不抽取附件全文、不创建附件 Document/派生资产、不调度 MinerU/OCR。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run/投影状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。 - 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。EML 多 PDF 时每个 PDF 独立 Candidate,禁止跨 PDF 拼行。 - 正文与附件由 HXOPS 的确定性关系规则关联并统一裁决;**有主 PDF 时当前值按 PDF 优先**(见上节);`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。订单抽取主链不调用 Dify。 +- 邮件正文补充字段冲突必须可解释并可恢复:新 Finding 固定携带字段/行、双方原值与规范化值、文档/证据引用、严重度和处理状态;金额等字段按 Schema 语义比较,明细按精确 `PO + MPN` 对齐。历史无双方证据的旧冲突不得按空 Case 投影放行,管理员重评估冻结输入后仅清除格式等价假冲突;无法恢复证据时保持阻断并引导重新识别当前 PDF。 +- Draft「保存并校验」必须由后端统一恢复协调器完成资格、Gate 和幂等自动建单入队;前端只显示 `resume_outcome`,不自行推导流程。入队/已排队/运行中均须明确提示,Worker 实际状态以后端处理投影为准。 - 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。 - 迁移前高置信 Candidate 可自动创建 Batch/Task;订单人工复核目标态切换后,任何 PDF 均必须由对应 Review Case 使用指定草稿版本确认,才可创建 Task。Reservation ID 缺失仍是硬门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。 - 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。 @@ -290,6 +292,7 @@ - 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。 - **XFA 客户采购订单(PO)统一解析(2026-08-18)**:普通 PDF 与 XFA 共用同一编辑、自动标注、保存、验证、发布和运行时解析主链。`/XFA datasets + 拆分规则`是 XFA 的首选正式值源;datasets 缺失、受限、Profile/结构不匹配、规则或对账失败时,必须继续进入普通 PDF 共用的 PDFium 原生坐标/OCR 证据链。AcroForm Widget 同时作为统一画布的视觉绑定和自动标注证据。每个 observation 记录 `value_source` 与坐标/引文证据;PDF 证据不得伪装为 datasets。回退结果可创建候选供人工复核,但固定 `needs_review`、禁止 CQ/STP 自动建单;低置信、证据不足或冲突同样不得静默建单。Dify 不参与解析主链。 - **XFA 统一视觉标注、字段拆分与精确解析**:页面画框、自动标注 Job、保存、验证、发布与普通 PDF 使用同一入口和 DTO;服务端仅按已持久化 Profile 能力选择 datasets 或 PDF 证据适配器。XFA `value_binding.type=xfa_dataset` 保持为首选配置,不把 OCR 固化成主映射;确认后的 `visual_binding` 用于定位、复核和审计。拆分优先级固定 `prefix > regex > position > unmatched`,冲突进入 `needs_review`;正则优先 RE2。 +- **PDF 订单解析证据链收口(2026-08-21)**:原 PDF 是不可变事实;固定 `matching_features.v1` 仅提供稳定版式匹配输入,坐标统一按当前 Layout、快照补缺、原 PDF、OCR 的顺序按需恢复。Profile 只负责版式,Schema 是唯一字段契约,订单头/订单行共用受限几何变换和字段证据。关键证据缺失、模板歧义/漂移、变换异常、XFA/OCR 冲突均必须进入 Review;自动标注仅辅助 Draft,生产通用解析必须冻结 Parse Plan,Dify 不参与主链或自动建单。 - **XFA 字段拆分映射(历史增量,已由统一方案接管)**:早期曾落地多阶段 `stages[]` 流水线与独立 XFA 映射页。统一方案冻结后,拆分语义以 `prefix > regex > position > unmatched` 为准,工作台并入统一画框编辑器;历史契约文档 [xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md) 仅作迁移对照,不再作为新开发权威。 - 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。 - Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。 diff --git a/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html b/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html index 52c83252..2988fb46 100644 --- a/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html +++ b/docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html @@ -12,14 +12,18 @@ @@ -33,11 +37,18 @@ +
+
评审对话走查(演示)
+ + + + +
仓
仓库管理人员在途仓调拨 Agent
-
AI
在途仓自动调拨Chat 首页 · 仅展示摘要与入口
/chat/:agentId
+
AI
在途仓自动调拨Chat 首页 · 仅展示摘要与入口
调拨中心
@@ -45,7 +56,7 @@ - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index 2a580000..cb9dd59b 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -29,6 +29,7 @@ import { enqueueOrderProfilePdfAutomark, generateOrderProfileOcrCoordinateEvidence, getOrderProfilePdfAutomarkJob, + getOrderProfileSampleStatus, getOrderProfileSampleTables, listOrderProfileValidationRuns, listOrderProfileBoundSamples, @@ -55,6 +56,7 @@ import type { OrderFieldLayoutSuggestion, OrderProfileRowReconstructionMode, ShippingOrderDocumentProfile, + OrderProfileSampleIntake, OrderProfileValidationRun, } from "@/features/admin/types/shipping-order-document-profile.types"; import { @@ -85,14 +87,18 @@ import { buildOrderProfileRecognitionResults, selectCurrentDatasetsValidationEvidence, groupUniqueOrderProfileLineFields, + restoreFormalBindingFieldCodes, normalizeOrderProfileRelativeRegion, buildAutomarkSuggestedRegions, normalizeAutomarkFieldCandidates, + preferredAutomarkTableSource, selectAutomarkReconstruction, summarizeAutomarkTableCandidates, toOrderProfileHeaderFieldRegion, resolveCoordinateFieldScope, isOrderProfileVisualFieldEligible, + buildAutomarkSuggestionSummary, + type AutomarkSuggestionContext, } from "./orderProfileForm.utils"; const { t } = useI18n(); @@ -118,6 +124,8 @@ const samples = ref< const schemas = ref([]); const active = ref(null); const boundSamples = ref([]); +/** 自动标注前必须由服务端确认当前 annotation 样本的 Layout/主表/证据三项均已就绪。 */ +const automarkSampleReadiness = ref(null); /** 坐标 PDF 与 XFA 共用原 PDF + PDF.js 画布;PDFium 页图仅留给后端证据生成。 */ const pdfPreviewGrant = ref<{ document_id: number; preview_token: string; expires_in_seconds: number } | null>(null); const pdfPageCount = ref(1); @@ -153,7 +161,14 @@ const headerSuggestions = ref< }> >([]); const orderFieldSuggestions = ref([]); -const pendingSuggestion = ref<{ id: string; checksum: string; summary: Record; regions: OrderProfileCanvasRegion[] } | null>(null); +/** 待确认候选冻结任务身份;翻页只能改变画布视图,不能改变接受请求的审计身份。 */ +const pendingSuggestion = ref<{ + id: string; + checksum: string; + context: AutomarkSuggestionContext; + summary: Record; + regions: OrderProfileCanvasRegion[]; +} | null>(null); const automarkTableCandidates = ref>([]); const automarkTableCandidateSummaries = ref>([]); const selectedAutomarkTableSource = ref(''); @@ -175,6 +190,12 @@ const leaveConfirmOpen = ref(false); let resolveRouteLeave: ((allowed: boolean) => void) | null = null; const suggestingRegions = ref(false); const suggestionProgress = ref(""); +type AutomarkStage = 'idle' | 'checking' | 'queued' | 'analyzing' | 'building' | 'review' | 'failed' | 'complete'; +const automarkStage = ref('idle'); +const automarkStagePercent: Record = { + idle: 0, checking: 15, queued: 30, analyzing: 55, building: 75, review: 100, failed: 100, complete: 100, +}; +const automarkProgressPercent = computed(() => automarkStagePercent[automarkStage.value]); const creationKind = ref(null); const pendingDocumentAnchorLabel = ref(null); const pendingOrderFieldAnchor = ref(null); @@ -256,6 +277,10 @@ const xfaConfigReadonly = computed(() => ( * XFA 后台仍可走 automark Job,但 UI 不再使用专用 OCR 底栏。 */ async function onDeskCanvasSuggest(): Promise { + if (!automarkSampleReadiness.value?.automark_ready) { + message.warning(automarkReadinessMessage(automarkSampleReadiness.value?.automark_reason_code)); + return; + } void suggestRegions(); } @@ -592,10 +617,55 @@ const draftSaveAdapter = computed(() => ( const deskCanvasDocumentReady = computed(() => visualCanvas.value.documentReady); const deskCanvasPreview = computed(() => visualCanvas.value.preview); const deskCanvasPreviewPagePath = computed(() => visualCanvas.value.previewPagePath); -const deskCanvasRegions = computed(() => visualCanvas.value.regions); +/** + * 把待确认候选投影为只读预览层;正式 regions 始终保持不变,接受建议后才落盘。 + * 同 ID 的旧自动区域由候选替换,避免用户同时看到两套重叠框。 + */ +const deskCanvasRegions = computed(() => { + const current = visualCanvas.value.regions; + const pending = pendingSuggestion.value; + if (!pending) return current; + const pendingIds = new Set(pending.regions.map((region) => region.id)); + const previewRegions = pending.regions + .filter((region) => region.pageNo === pageNo.value) + .map((region) => ({ ...region, isPreview: true })); + return [ + ...current.filter((region) => !pendingIds.has(region.id)), + ...previewRegions, + ]; +}); const deskSelectedRegionId = computed(() => visualCanvas.value.selectedRegionId); const deskCreationKind = computed(() => visualCanvas.value.creationKind); -const deskAutoSuggestDisabled = computed(() => visualCanvas.value.autoSuggestDisabled); +const automarkReadinessMessage = (reasonCode?: string | null): string => { + const keyByReason: Record = { + layout_not_ready: 'autoSuggestLayoutNotReady', + main_table_missing: 'autoSuggestMainTableRequired', + main_table_ambiguous: 'autoSuggestMainTableAmbiguous', + layout_content_hash_mismatch: 'autoSuggestLayoutStale', + layout_checksum_mismatch: 'autoSuggestLayoutStale', + document_missing: 'autoSuggestSampleMissing', + }; + return t(`admin.shippingOrderProfiles.workbench.${keyByReason[reasonCode || ''] || 'autoSuggestEvidencePending'}`); +}; +/** 刷新当前 annotation 文档对应 Intake;服务端会在此处幂等补齐可安全冻结的证据。 */ +const refreshAutomarkSampleReadiness = async (): Promise => { + const intakeNo = samples.value.find((item) => item.document_id === form.documentId)?.intake_no; + if (!intakeNo) { + automarkSampleReadiness.value = null; + return null; + } + const status = await getOrderProfileSampleStatus(intakeNo); + const currentProfileState = status.sample_readiness?.find( + (item) => item.profile_id === active.value?.id && item.document_id === form.documentId, + ); + automarkSampleReadiness.value = currentProfileState + ? { ...status, ...currentProfileState, sample_readiness: [currentProfileState] } + : { ...status, automark_ready: false, automark_reason_code: 'document_missing' }; + return automarkSampleReadiness.value; +}; +const deskAutoSuggestDisabled = computed(() => ( + visualCanvas.value.autoSuggestDisabled || !automarkSampleReadiness.value?.automark_ready +)); const deskPageNo = computed(() => visualCanvas.value.pageNo); const deskPageCount = computed(() => visualCanvas.value.pageCount); const deskSaveDisabled = computed(() => visualCanvas.value.saveDisabled); @@ -629,6 +699,15 @@ const onDeskRejectSuggestion = () => visualCanvas.value.rejectSuggestion(); const deskPendingSuggestionCount = computed(() => ( pendingSuggestion.value?.regions.length || 0 )); +const pendingSuggestionPageNo = computed(() => pendingSuggestion.value?.context.pageNo || null); +const pendingSuggestionIsOffCanvasPage = computed(() => ( + pendingSuggestionPageNo.value !== null && pendingSuggestionPageNo.value !== pageNo.value +)); +/** 返回待确认候选的冻结页面;不限制管理员先浏览其他页面。 */ +const returnToPendingSuggestionPage = (): void => { + const targetPageNo = pendingSuggestionPageNo.value; + if (targetPageNo !== null) void selectPage(targetPageNo); +}; const hasAutomarkTableChoice = computed(() => automarkTableCandidates.value.length > 1); const automarkTableChoiceRequired = computed(() => hasAutomarkTableChoice.value && !selectedAutomarkTableSource.value); const automarkFieldChoiceRequired = computed(() => automarkFieldConflicts.value.some((item) => !selectedAutomarkFieldSources[item.field_id])); @@ -1595,6 +1674,8 @@ const save = async (automatic = false) => { autosaveFailures = 0; if (!automatic) message.success(t("admin.shippingOrderProfiles.updated")); profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item); + // 保存主表后后端会冻结当前 Layout 身份;立即同步门禁,避免管理员必须重开编辑页。 + await refreshAutomarkSampleReadiness(); await refreshOrderFieldSuggestionValues(); if (localChangeVersion !== savingChangeVersion) scheduleAutosave(); return true; @@ -1631,16 +1712,27 @@ const suggestRegions = async () => { if (suggestingRegions.value || !active.value) return; const { documentId, tableId, pageNo: targetPageNo } = deskAnnotationContext.value; if (!documentId) { + automarkStage.value = 'failed'; suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"); message.error(t("admin.shippingOrderProfiles.workbench.autoSuggestFailed")); return; } if (!tableId) return; suggestingRegions.value = true; + automarkStage.value = 'checking'; suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates", ); try { + // 入队前使用当前服务端状态:它会幂等补齐样本证据,不能相信进入编辑页时的旧快照。 + const readiness = await refreshAutomarkSampleReadiness(); + if (!readiness?.automark_ready) { + automarkStage.value = 'failed'; + suggestionProgress.value = automarkReadinessMessage(readiness?.automark_reason_code); + message.warning(suggestionProgress.value); + return; + } + automarkStage.value = 'queued'; suggestionProgress.value = t("admin.shippingOrderProfiles.workbench.autoSuggestAnalyzing"); const queued = await enqueueOrderProfilePdfAutomark(active.value.id, { document_id: documentId, @@ -1652,6 +1744,8 @@ const suggestRegions = async () => { let job; for (;;) { job = await getOrderProfilePdfAutomarkJob(active.value.id, queued.job_id); + if (String(job.status) === 'queued') automarkStage.value = 'queued'; + else if (['running', 'pending'].includes(String(job.status || ''))) automarkStage.value = 'analyzing'; if (!['queued', 'running', 'pending'].includes(String(job.status || ''))) break; await new Promise((resolve) => { window.setTimeout(resolve, 500); }); } @@ -1688,14 +1782,14 @@ const suggestRegions = async () => { .filter((item) => item.field_id && item.sources.length > 1) : []; for (const key of Object.keys(selectedAutomarkFieldSources)) delete selectedAutomarkFieldSources[key]; - selectedAutomarkTableSource.value = automarkTableCandidates.value.length === 1 - ? automarkTableCandidates.value[0]!.source : ''; + selectedAutomarkTableSource.value = preferredAutomarkTableSource(automarkTableCandidates.value); // 新一轮自动标记不能沿用上一轮已确认来源;单一路候选仍保留其来源以便 // 草稿版本可追溯,多路候选则必须等待用户选择。 - ensureTableRegionSetting(pageNo.value).visualEvidenceSource = selectedAutomarkTableSource.value + ensureTableRegionSetting(targetPageNo).visualEvidenceSource = selectedAutomarkTableSource.value ? selectedAutomarkTableSource.value as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry' : null; if (visualCanvas.value.applyAutomarkCandidates(candidates)) { + automarkStage.value = 'complete'; suggestionProgress.value = candidates.length ? t("admin.shippingOrderProfiles.workbench.autoSuggestComplete") : t("admin.shippingOrderProfiles.workbench.autoSuggestNoRows"); @@ -1723,6 +1817,7 @@ const suggestRegions = async () => { const orderFields = { order_field_candidates: normalizeAutomarkFieldCandidates(selectedFieldCandidates) }; orderFieldSuggestions.value = orderFields.order_field_candidates; if (!suggestion && !orderFields.order_field_candidates.length && !automarkFieldConflicts.value.length) { + automarkStage.value = 'complete'; suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestNoRows", ); @@ -1731,26 +1826,32 @@ const suggestRegions = async () => { suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestApplying", ); + automarkStage.value = 'building'; const suggestedRegions = buildAutomarkSuggestedRegions({ reconstruction: suggestion, orderFieldCandidates: orderFields.order_field_candidates, - pageNo: pageNo.value, + pageNo: targetPageNo, unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }), lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }), }); - const summary = { - algorithm_version: 'coordinate-suggest-v1', kind: 'page_regions', page_no: pageNo.value, - document_id: documentId, table_id: form.tableId, automark_job_id: job.job_id, - region_count: suggestedRegions.length, - region_kinds: suggestedRegions.map((item) => item.kind), - evidence_source_required: hasParallelTableCandidates, - selected_evidence_source: hasParallelTableCandidates ? null : (selectedAutomarkTableSource.value || null), - selected_field_evidence_sources: { ...selectedAutomarkFieldSources }, + const context: AutomarkSuggestionContext = { + documentId, + tableId, + pageNo: targetPageNo, + automarkJobId: job.job_id, }; + const summary = buildAutomarkSuggestionSummary(context, { + regionCount: suggestedRegions.length, + regionKinds: suggestedRegions.map((item) => item.kind), + evidenceSourceRequired: hasParallelTableCandidates, + // 多来源仍要求人工接受;预选 PDF 只避免下拉框显示已选但摘要为空。 + selectedEvidenceSource: selectedAutomarkTableSource.value || null, + selectedFieldEvidenceSources: { ...selectedAutomarkFieldSources }, + }); const serialized = canonicalSuggestionJson(summary); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized)); const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join(''); - pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions: suggestedRegions }; + pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context, summary, regions: suggestedRegions }; message.success( t("admin.shippingOrderProfiles.workbench.suggestionReadyForDecision"), ); @@ -1758,11 +1859,26 @@ const suggestRegions = async () => { suggestionProgress.value = hasParallelTableCandidates ? t("admin.shippingOrderProfiles.workbench.autoSuggestMultiEvidenceReview") : t("admin.shippingOrderProfiles.workbench.autoSuggestComplete"); + automarkStage.value = hasParallelTableCandidates ? 'review' : 'complete'; } catch (error) { - suggestionProgress.value = - error instanceof BusinessError - ? error.message - : t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"); + if (error instanceof BusinessError) { + const reasonByCode: Record = { + 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY': 'layout_not_ready', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED': 'main_table_missing', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS': 'main_table_ambiguous', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE': 'layout_checksum_mismatch', + 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND': 'document_missing', + }; + const reason = reasonByCode[error.code]; + if (reason) { + suggestionProgress.value = automarkReadinessMessage(reason); + message.warning(suggestionProgress.value); + return; + } + } + suggestionProgress.value = error instanceof BusinessError + ? error.message : t("admin.shippingOrderProfiles.workbench.autoSuggestFailed"); + automarkStage.value = 'failed'; fail(error); } finally { suggestingRegions.value = false; @@ -1772,28 +1888,31 @@ const suggestRegions = async () => { /** 用户选择 native/OCR 表格候选后,重新生成待确认建议并刷新其审计摘要。 */ const chooseAutomarkTableSource = async (source: string) => { selectedAutomarkTableSource.value = source; - ensureTableRegionSetting(pageNo.value).visualEvidenceSource = source as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry'; + const pending = pendingSuggestion.value; + if (!pending) return; + ensureTableRegionSetting(pending.context.pageNo).visualEvidenceSource = source as 'pdf_coordinate' | 'ocr_coordinate' | 'opencv_geometry' | 'acroform_widget_geometry'; const candidate = automarkTableCandidates.value.find((item) => item.source === source); - if (!candidate || !pendingSuggestion.value) return; + if (!candidate) return; const regions = buildAutomarkSuggestedRegions({ reconstruction: candidate.reconstruction, orderFieldCandidates: orderFieldSuggestions.value, - pageNo: pageNo.value, + pageNo: pending.context.pageNo, unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }), lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }), }); - const summary = { ...pendingSuggestion.value.summary, selected_evidence_source: source, region_count: regions.length, region_kinds: regions.map((item) => item.kind) }; + const summary = { ...pending.summary, selected_evidence_source: source, region_count: regions.length, region_kinds: regions.map((item) => item.kind) }; const serialized = canonicalSuggestionJson(summary); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized)); const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join(''); - pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions }; + pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context: pending.context, summary, regions }; schedulePreview(); }; /** 选择冲突字段的视觉来源;只将该来源的框加入待确认画布,不影响 XFA datasets 正式值源。 */ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => { selectedAutomarkFieldSources[fieldId] = source; - if (!pendingSuggestion.value) return; + const pending = pendingSuggestion.value; + if (!pending) return; const selectedCandidates = automarkCandidates.value.filter((item) => { if (item.candidate_kind !== 'field_binding' || !item.binding || typeof item.binding !== 'object') return true; const currentFieldId = String((item.binding as Record).field_id || ''); @@ -1809,12 +1928,12 @@ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => { const regions = buildAutomarkSuggestedRegions({ reconstruction: selectedTable, orderFieldCandidates: orderFieldSuggestions.value, - pageNo: pageNo.value, + pageNo: pending.context.pageNo, unboundColumnLabel: (count) => t("admin.shippingOrderProfiles.workbench.unboundColumn", { count }), lineLabel: (count) => t("admin.shippingOrderProfiles.workbench.regionLabels.line", { count }), }); const summary = { - ...pendingSuggestion.value.summary, + ...pending.summary, selected_field_evidence_sources: { ...selectedAutomarkFieldSources }, region_count: regions.length, region_kinds: regions.map((item) => item.kind), @@ -1822,7 +1941,7 @@ const chooseAutomarkFieldSource = async (fieldId: string, source: string) => { const serialized = canonicalSuggestionJson(summary); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized)); const checksum = Array.from(new Uint8Array(digest)).map((item) => item.toString(16).padStart(2, '0')).join(''); - pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, summary, regions }; + pendingSuggestion.value = { id: checksum.slice(0, 32), checksum, context: pending.context, summary, regions }; schedulePreview(); }; /** @@ -1859,6 +1978,9 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted suggestionPages.has(region.pageNo) && (region.id.startsWith(`header_${region.pageNo}_`) || region.id.startsWith(`line_${region.pageNo}_`)); + const replaceableAutoRegionIds = new Set( + regions.value.filter(isReplaceableAutoTableRegion).map((region) => region.id), + ); // A new suggestion is a complete table layout for its page. Replace its // previous generated header/line frames before appending it, otherwise a // changed suggestion ID leaves geometrically overlapping regions behind. @@ -1866,7 +1988,18 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted (region) => !isReplaceableAutoTableRegion(region), ); const existingIds = new Set(regions.value.map((region) => region.id)); - const acceptedRegions = item.regions.filter((region) => !existingIds.has(region.id)).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode })); + const formalBindingLayoutIds = new Set( + (valueAdapterDesk.definition?.bindings || []) + .filter((binding) => Boolean(binding.value_binding?.path_id?.trim())) + .map((binding) => String(binding.field_layout_id || '').trim()), + ); + const acceptedRegions = restoreFormalBindingFieldCodes( + regions.value, + item.regions.filter((region) => ( + !existingIds.has(region.id) || replaceableAutoRegionIds.has(region.id) + )), + formalBindingLayoutIds, + ).map((region) => ({ ...region, fieldCode: decision === 'accepted_adjusted' && region.id === firstSuggestedField?.id ? replacementFieldCode : region.fieldCode })); const suggestedLines = acceptedRegions.filter((region) => region.kind === 'line'); if (suggestedLines.length) { const fieldParentIds = new Set( @@ -1891,6 +2024,7 @@ const decidePendingSuggestion = async (decision: 'accepted' | 'accepted_adjusted selectedId.value = item.regions.find((region) => region.fieldCode)?.id || item.regions[0]?.id || null; } pendingSuggestion.value = null; + automarkStage.value = decision === 'rejected' ? 'idle' : 'complete'; suggestionAdjustmentField.value = ''; } catch (error) { fail(error); } }; @@ -2055,6 +2189,7 @@ const reprocessCurrentSampleLayout = async (): Promise => { await reparseOrderProfileSampleLayout(form.documentId); message.success(t('admin.shippingOrderProfiles.blindTest.layoutReparseStarted')); await loadSampleTables(); + await refreshAutomarkSampleReadiness(); await loadPages(); await refreshOrderFieldSuggestionValues(); } catch (error) { @@ -2443,6 +2578,7 @@ const edit = async (profile: ShippingOrderDocumentProfile) => { form.tableId = visualTableId; pageNo.value = sampleTables.value.find((item) => item.table_id === visualTableId)?.page_no || pageNo.value; } + await refreshAutomarkSampleReadiness(); await loadPages(); } catch (error) { fail(error); @@ -2568,6 +2704,7 @@ watch( canvasUnavailable.value = false; if (restoringProfile) return; void loadSampleTables(); + void refreshAutomarkSampleReadiness(); if (active.value) void loadPages(); }, ); @@ -2750,6 +2887,54 @@ onBeforeUnmount(() => { {{ t('admin.shippingOrderProfiles.blindTest.reprocessLayout') }} +
+
+
+ {{ pendingSuggestion ? t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') : t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') }} +

{{ suggestionProgress || t('admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates') }}

+
+ {{ pendingSuggestion.regions.length }} {{ t('admin.shippingOrderProfiles.workbench.suggestionPreviewBadge') }} +
+
+ +
+
+
+ {{ t('admin.shippingOrderProfiles.workbench.suggestionOnPage', { page: pendingSuggestionPageNo }) }} + +
+
+ +
+ + {{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateSummary', { source: summary.source, rows: summary.rowCount, columns: summary.columnCount }) }} + {{ t('admin.shippingOrderProfiles.workbench.autoSuggestCandidateConflict') }} + +
+
+
+ +
+
+ + + + +
+
+
{ @load-failed="onDeskCanvasLoadFailed" @retry="onDeskCanvasRetry" /> -
- {{ t('admin.shippingOrderProfiles.workbench.suggestionReadyForDecision') }} - {{ pendingSuggestion.regions.length }} - - - - -
@@ -3791,8 +3946,26 @@ onBeforeUnmount(() => { .editor-desk > main { min-height: 0; } .editor-workbench .config { max-height: calc(100vh - 5rem); overflow-y: auto; } .editor-bottom-drawer { max-width: none; border-top: 1px solid #334155; background: #f8fafc; } -.suggestion-decision { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; border-top: 1px solid #7dd3fc; background: #ecfeff; padding: .65rem .9rem; color: #155e75; } -.suggestion-decision span { border-radius: 999px; background: #bae6fd; padding: .15rem .4rem; font-size: .72rem; }.suggestion-decision button,.suggestion-decision .select-field { border: 1px solid #0891b2; border-radius: .35rem; background: #fff; padding: .35rem .55rem; color: #0e7490; font-size: .75rem; } +.automark-status-panel { position: sticky; top: .5rem; z-index: 6; display: grid; gap: .65rem; margin: 0 0 .75rem; border: 1px solid #7dd3fc; border-radius: .45rem; background: #f0f9ff; padding: .75rem .9rem; color: #164e63; box-shadow: 0 8px 20px rgb(14 116 144 / .12); } +.automark-status-panel__heading { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; } +.automark-status-panel__heading strong { display: block; color: #0c4a6e; font-size: .82rem; } +.automark-status-panel__heading p { margin: .2rem 0 0; color: #475569; font-size: .75rem; } +.automark-status-panel__count { flex: 0 0 auto; border-radius: 999px; background: #bae6fd; padding: .2rem .5rem; font-size: .7rem; font-weight: 700; } +.automark-progress { height: .35rem; overflow: hidden; border-radius: 999px; background: #dbeafe; } +.automark-progress span { display: block; height: 100%; border-radius: inherit; background: #0284c7; transition: width .25s ease; } +.automark-status-panel__body { display: grid; gap: .6rem; } +.automark-candidate-page-notice { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .45rem; border: 1px solid #bae6fd; border-radius: .35rem; background: #fff; padding: .45rem .55rem; color: #0c4a6e; font-size: .75rem; } +.automark-choice-block { display: grid; gap: .45rem; } +.automark-choice-block label { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; color: #334155; font-size: .74rem; font-weight: 700; } +.automark-choice-block--fields { grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr)); } +.automark-status-panel__actions { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; } +.automark-status-panel__actions .select-field { min-width: 12rem; } +@media (max-width: 640px) { + .automark-status-panel { top: 0; } + .automark-status-panel__actions { align-items: stretch; } + .automark-status-panel__actions > * { flex: 1 1 100%; } + .automark-status-panel__actions .select-field { min-width: 0; } +} .suggestion-evidence-summary { display: flex; flex-wrap: wrap; gap: .35rem; width: 100%; font-size: .72rem; } .suggestion-evidence-summary span { background: #e0f2fe; color: #075985; } .suggestion-evidence-summary span.is-conflict { background: #fee2e2; color: #991b1b; } diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue index c759d534..7b156d17 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue @@ -215,7 +215,7 @@ const move = (event: PointerEvent) => { const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => { event.preventDefault(); emit('select', region.id); - if (readonlyMode.value) return; + if (readonlyMode.value || region.isPreview) return; emit('start', region.id); activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } }; window.addEventListener('pointermove', move); @@ -330,8 +330,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL( {{ t('admin.shippingOrderProfiles.versionCenter.readonlyCanvasBadge') }} @@ -386,7 +385,7 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL( role="button" tabindex="0" class="region" - :class="[`region-${region.kind}`, { selected: selected.has(region.id) }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']" + :class="[`region-${region.kind}`, { selected: selected.has(region.id), 'region-preview': region.isPreview }, region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '']" :style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }" :aria-label="displayRegionLabel(region)" @pointerdown.stop="beginDrag($event, region, 'move')" @@ -394,10 +393,10 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL( @keydown.space.prevent="emit('select', region.id)" > {{ displayRegionLabel(region) }} -