From 1e5aedb9ed3c4038926d2ff1db9ac07b1d3b47b8 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 26 Aug 2026 02:47:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E6=BB=9A=E5=8A=A8=E5=B1=A5=E7=BA=A6=E5=8A=9F=E8=83=BD=EF=BC=8C?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=8F=91=E8=B4=A7=E9=80=9A=E7=9F=A5=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E4=B8=8E=E4=BB=A3=E7=A0=81=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。 --- .env.shared | 6 +- backend/app/api/chat/completions.py | 41 +- backend/app/api/workspace/shipping_notice.py | 311 +++++- .../shipping_post_ot_wave_progress.py | 3 +- backend/app/models/__init__.py | 2 - backend/app/models/shipping.py | 21 +- backend/app/models/shipping_customer.py | 39 +- backend/app/models/shipping_excel_template.py | 2 +- .../models/shipping_freight_cancellation.py | 2 +- backend/app/models/shipping_fulfillment.py | 3 +- .../models/shipping_order_review_wave_line.py | 2 +- .../shipping_customer_lifecycle_service.py | 4 +- .../admin/shipping_customer_service.py | 22 +- .../auto_progress_controller.py | 6 +- .../shipping_notice/business_case_service.py | 88 -- .../business_numbering_service.py | 74 +- .../candidate_qualification_contract.py | 6 - .../candidate_qualification_service.py | 95 +- .../customer_auto_resolution.py | 213 ++-- .../shipping_notice/customer_identity_gate.py | 106 +- .../customer_shadow_resolution.py | 2 +- .../coordinate_region_source_adapter.py | 231 ----- .../coordinate_table_reconstruction.py | 508 +++++++++- .../document_layout/lifecycle.py | 127 ++- .../document_layout/native_pdf.py | 173 ++-- .../document_layout/order_field_extraction.py | 112 ++- .../document_layout/order_profile.py | 14 +- .../document_layout/order_profile_matcher.py | 39 +- .../order_profile_parse_validation.py | 2 + .../profile_field_source_mapping_service.py | 456 --------- .../profile_vendor_comments_contract.py | 338 ------- .../reservation_format_policy_service.py | 152 --- .../reservation_relation_projection.py | 228 ----- .../document_layout/runtime_parse_strategy.py | 244 +++++ .../document_layout/source_merge_service.py | 342 ------- .../vc_source_candidate_conflicts.py | 195 ---- .../vc_source_evidence_integration.py | 230 ----- .../vc_source_gate_contract.py | 204 ---- .../xfa_split_rule_contract.py | 24 + .../document_layout/xfa_split_rule_engine.py | 53 +- .../document_profile_quality_service.py | 313 +++--- .../shipping_notice/duplicate_detection.py | 2 +- .../error_explainability_contract.py | 8 +- .../app/services/shipping_notice/export.py | 185 ++-- .../shipping_notice/export_archive.py | 40 +- .../freight_cancellation_service.py | 32 +- .../shipping_notice/fulfillment_workflow.py | 215 ++-- .../line_auto_fulfill_coordinator.py | 19 + .../shipping_notice/notice_line_service.py | 11 +- ...order_document_profile_creation_service.py | 2 + ...r_document_profile_pdf_automark_service.py | 72 +- .../order_document_profile_preview_service.py | 1 + ..._document_profile_publish_check_service.py | 48 +- .../order_document_profile_service.py | 252 ++++- ...der_document_profile_validation_service.py | 55 +- .../order_extraction_route_contract.py | 5 + .../order_extraction_run_service.py | 1 + .../order_extraction_workflow.py | 340 ++++++- .../order_extraction_workspace_projection.py | 187 +++- .../shipping_notice/order_field_purposes.py | 5 +- .../xfa_dataset.py | 46 +- .../order_review_confirmation_service.py | 6 +- .../order_review_evidence_view.py | 32 - .../order_review_field_conflict_service.py | 389 ++------ ...der_review_fulfillment_decision_service.py | 63 +- .../order_review_progress_bridge.py | 26 + .../order_review_projection.py | 4 + .../order_review_reservation_service.py | 27 +- .../order_schema/field_rules.py | 5 + .../order_stp_auto_create_service.py | 78 -- .../shipping_notice/order_task_service.py | 12 +- .../post_ot_fulfillment_wave_service.py | 112 ++- .../shipping_notice/process_gate_bridge.py | 6 +- .../shipping_notice/process_gate_contract.py | 17 +- .../process_gate_dependency.py | 3 +- .../shipping_notice/process_gate_executor.py | 98 +- .../process_gate_projection.py | 42 +- .../process_gate_recovery_service.py | 8 +- .../processing_projection_invariants.py | 2 +- .../shipping_notice/progress_workflow.py | 4 + .../services/shipping_notice/query_service.py | 261 +++-- .../services/shipping_notice/queue_service.py | 1 + .../recovery_invalidation_service.py | 2 +- .../shipping_notice/reservation_region.py | 160 +++ .../shipping_notice/reservation_service.py | 17 +- .../services/shipping_notice/state_machine.py | 4 +- .../task_disposition_service.py | 15 +- .../task_supersession_service.py | 2 +- .../services/shipping_notice/task_workflow.py | 20 +- .../app/services/shipping_notice/ui_state.py | 10 +- .../shipping_notice/upload_attempt_service.py | 46 +- ...hn7o8p9q0r1s_add_notice_business_number.py | 64 ++ .../ho8p9q0r1s2t_notice_customer_facts.py | 60 ++ .../hp9q0r1s2t3u_remove_shipping_case.py | 105 ++ backend/tests/conftest.py | 2 +- ...est_shipping_customer_lifecycle_service.py | 18 +- .../test_shipping_customer_merge_service.py | 16 +- .../admin/test_shipping_customer_service.py | 6 +- .../tests/test_admin_shipping_customers.py | 20 +- ...order_document_profile_creation_service.py | 23 + ..._document_profile_publish_check_service.py | 59 +- ...der_document_profile_validation_service.py | 65 ++ .../test_order_extraction_pdf_po_split.py | 111 ++- .../tests/test_post_ot_fulfillment_wave_p0.py | 128 ++- .../tests/test_shipping_business_numbering.py | 140 ++- ...hipping_coordinate_table_reconstruction.py | 320 ++++++ .../test_shipping_customer_auto_resolution.py | 86 +- .../test_shipping_customer_identity_gate.py | 91 +- .../test_shipping_customer_migrations.py | 110 +++ ...est_shipping_customer_shadow_resolution.py | 6 +- ...test_shipping_document_layout_lifecycle.py | 19 + ...est_shipping_document_layout_native_pdf.py | 85 ++ .../test_shipping_document_layout_runtime.py | 3 + .../test_shipping_document_profile_quality.py | 182 ++-- backend/tests/test_shipping_excel_template.py | 39 +- .../tests/test_shipping_generic_order_gate.py | 75 +- .../test_shipping_notice_business_case.py | 102 +- ..._shipping_notice_inventory_rpa_workflow.py | 42 +- .../test_shipping_notice_query_service.py | 119 ++- .../test_shipping_notice_reservation_id.py | 104 ++ .../test_shipping_notice_state_machine.py | 1 - backend/tests/test_shipping_notice_tools.py | 30 +- ...shipping_order_document_profile_service.py | 261 +++++ .../test_shipping_order_extraction_runs.py | 83 ++ .../test_shipping_order_field_extraction.py | 105 +- .../test_shipping_order_profile_matcher.py | 23 + ...st_shipping_order_review_field_conflict.py | 29 + .../test_shipping_order_review_service.py | 45 + ...test_shipping_order_task_progress_audit.py | 30 +- ..._shipping_order_task_status_consistency.py | 2 +- backend/tests/test_shipping_pdf_automark.py | 35 +- .../test_shipping_process_gate_contract.py | 63 +- ...g_process_gate_recovery_action_contract.py | 96 +- .../test_shipping_process_recovery_plan.py | 61 +- ...ipping_review_line_fulfillment_decision.py | 16 +- ...t_shipping_review_wave_line_concurrency.py | 12 +- ...hipping_review_workbench_stage_layering.py | 25 + .../test_shipping_rolling_fulfillment.py | 48 + .../test_shipping_runtime_parse_strategy.py | 165 ++++ .../tests/test_shipping_task_disposition.py | 21 +- .../tests/test_shipping_task_supersession.py | 10 +- backend/tests/test_shipping_upload_attempt.py | 197 +++- .../test_shipping_vendor_comments_phase2.py | 444 --------- ...ipping_xfa_publish_separation_of_duties.py | 22 +- .../test_shipping_xfa_split_rule_contract.py | 12 + .../test_shipping_xfa_split_rule_engine.py | 29 + backend/tests/test_tasks_0304_chat_fix.py | 60 +- backend/tests/test_worker_shipping.py | 16 + docs/demand.md | 19 +- ...-transit-transfer-source-instance-mvp.html | 103 +- docs/features/shipping-notice/business.md | 22 +- .../freight-shipping-agent-frontend-prd.md | 8 +- ...eview-workbench-file-switch-performance.md | 29 + docs/features/shipping-notice/technical.md | 63 +- docs/funclist.md | 19 +- ...ayed-notice-number-and-inventory-reload.md | 182 ++++ ...8-25-reservation-vendor-comments-anchor.md | 124 +++ ...fact-notice-and-inventory-reload-design.md | 80 ++ docs/tec.md | 16 +- .../shipping-order-document-profile.api.ts | 12 +- .../OrderProfileBlindTestPage.vue | 5 +- .../OrderProfileEditorPage.vue | 690 +++++++++---- .../canvasActions.utils.spec.ts | 62 ++ .../canvasActions.utils.ts | 55 +- .../OrderProfileDocumentCanvas.spec.ts | 48 + .../components/OrderProfileDocumentCanvas.vue | 32 +- .../components/OrderProfileSampleStep.vue | 6 +- .../components/VcMergePreviewTable.vue | 280 ------ .../components/VcNamedRegionBox.vue | 431 -------- .../components/VcSourceMappingPanel.vue | 544 ----------- .../components/VcSourceMappingSection.vue | 393 -------- .../components/VcSplitRuleEditor.vue | 921 ------------------ .../components/XfaSplitRulePanel.spec.ts | 89 ++ .../components/XfaSplitRulePanel.vue | 116 ++- .../useOrderProfileValueAdapter.spec.ts | 24 +- .../useOrderProfileValueAdapter.ts | 19 + .../orderProfileForm.utils.spec.ts | 124 +++ .../orderProfileForm.utils.ts | 212 +++- .../shipping-order-document-profile.types.ts | 17 +- ...hipping-order-document-profile.vc.types.ts | 365 ------- .../src/features/chat/api/shipping.api.ts | 44 +- .../ReviewCurrentProcessingCard.spec.ts | 14 + .../ReviewCurrentProcessingCard.vue | 13 +- .../ReviewFulfillmentDecisionPanel.vue | 281 +----- .../ReviewLifecycleStageNavigation.spec.ts | 11 +- .../ReviewLifecycleStageNavigation.vue | 15 +- .../ReviewProfileMatchPanel.spec.ts | 22 + .../ReviewProfileMatchPanel.vue | 15 + .../ReviewReservationPanel.spec.ts | 59 ++ .../ReviewReservationPanel.vue | 31 +- .../shipping-review/ReviewWorkbenchFooter.vue | 10 + .../ReviewWorkflowProgressPanel.spec.ts | 6 +- ...ping-order-review-workbench-layout.spec.ts | 3 +- .../chat/page/useChatPageSend.spec.ts | 1 + .../useShippingOrderReview.spec.ts | 155 +++ .../shipping-review/useShippingOrderReview.ts | 210 +++- .../chat/shipping/shippingDownload.ts | 31 + .../shipping/useShippingProcessingWorkItem.ts | 9 +- .../features/chat/types/shipping.api.types.ts | 75 +- .../views/ShippingOrderReviewView.spec.ts | 527 +++++++++- .../chat/views/ShippingOrderReviewView.vue | 890 +++++++++++++---- .../customers/ShippingCustomersPage.vue | 4 +- .../types/customer-master.types.ts | 4 +- .../ProcessGateRecoveryCard.spec.ts | 2 +- .../components/ProcessGateRecoveryCard.vue | 2 +- .../useShippingProcessGateRecovery.spec.ts | 95 ++ .../useShippingProcessGateRecovery.ts | 71 +- .../shipping-progress/actionPresentation.ts | 3 + .../workbenchActionRegistry.spec.ts | 19 + .../workbenchActionRegistry.ts | 15 + .../workspace/components/WorkspaceSidebar.vue | 18 +- .../ManualUploadEvidenceDialog.spec.ts | 34 +- .../ManualUploadEvidenceDialog.vue | 63 +- ...hippingTaskCenterPage.notice-batch.spec.ts | 204 ++++ .../ShippingTaskCenterPage.vue | 211 +++- .../ShippingTaskWorkbench.vue | 8 +- .../shipping-task-center/TaskTodoPanel.vue | 12 +- .../shippingTaskCenterPolling.spec.ts | 67 +- .../shippingTaskCenterPolling.ts | 7 +- frontend/src/locales/en/admin.json | 23 +- frontend/src/locales/en/chat.json | 50 +- frontend/src/locales/en/errors.json | 3 + frontend/src/locales/en/workspace.json | 39 +- frontend/src/locales/th/admin.json | 23 +- frontend/src/locales/th/chat.json | 48 +- frontend/src/locales/th/errors.json | 3 + frontend/src/locales/th/workspace.json | 39 +- frontend/src/locales/zh-CN/admin.json | 23 +- frontend/src/locales/zh-CN/chat.json | 52 +- frontend/src/locales/zh-CN/errors.json | 3 + frontend/src/locales/zh-CN/workspace.json | 41 +- frontend/src/locales/zh-TW/admin.json | 23 +- frontend/src/locales/zh-TW/chat.json | 50 +- frontend/src/locales/zh-TW/errors.json | 3 + frontend/src/locales/zh-TW/workspace.json | 41 +- 235 files changed, 11394 insertions(+), 9613 deletions(-) delete mode 100644 backend/app/services/shipping_notice/business_case_service.py delete mode 100644 backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py delete mode 100644 backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py delete mode 100644 backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py delete mode 100644 backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py delete mode 100644 backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py create mode 100644 backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py delete mode 100644 backend/app/services/shipping_notice/document_layout/source_merge_service.py delete mode 100644 backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py delete mode 100644 backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py delete mode 100644 backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py create mode 100644 backend/app/services/shipping_notice/reservation_region.py create mode 100644 backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py create mode 100644 backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py create mode 100644 backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py create mode 100644 backend/tests/test_shipping_runtime_parse_strategy.py delete mode 100644 backend/tests/test_shipping_vendor_comments_phase2.py create mode 100644 docs/superpowers/plans/2026-08-25-delayed-notice-number-and-inventory-reload.md create mode 100644 docs/superpowers/plans/2026-08-25-reservation-vendor-comments-anchor.md create mode 100644 docs/superpowers/specs/2026-08-25-shipping-artifact-notice-and-inventory-reload-design.md delete mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcMergePreviewTable.vue delete mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue delete mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue delete mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue delete mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue delete mode 100644 frontend/src/features/admin/types/shipping-order-document-profile.vc.types.ts create mode 100644 frontend/src/features/chat/components/shipping-review/ReviewReservationPanel.spec.ts create mode 100644 frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts create mode 100644 frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts diff --git a/.env.shared b/.env.shared index a3d46810..906d8ccd 100644 --- a/.env.shared +++ b/.env.shared @@ -185,9 +185,9 @@ FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈 # 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。 SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true # OT 后行级自动履约(默认关):关闭时只上线匹配事实契约/明细库存列;禁止自动决定与 wave。 -SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false +SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=true # 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。 -SHIPPING_NOTICE_WORKER_CONCURRENCY=2 +SHIPPING_NOTICE_WORKER_CONCURRENCY=10 # Layout Job 内整页 OCR 结果复用(PR-1);共享默认关,dev/test 环境文件覆盖为 true,prod 保持 false 灰度。 SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false # PDFium 字符预读复用与按需补图(PR-2);共享默认关,dev/test 开启,prod 灰度。 @@ -212,7 +212,7 @@ SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow # RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。 # 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。 -SHIPPING_NOTICE_RPA_CREDENTIAL_KEY= +SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= # 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。 SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300 # 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。 diff --git a/backend/app/api/chat/completions.py b/backend/app/api/chat/completions.py index a0af212a..10ee1ad6 100644 --- a/backend/app/api/chat/completions.py +++ b/backend/app/api/chat/completions.py @@ -127,6 +127,13 @@ def chat_completions(): else: session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running') + # [STEP 1] SSE 生成器可能在请求 scoped Session 清理后才开始迭代;提前快照会话标量, + # 避免流内事务提交使 ORM 实例过期后触发 DetachedInstanceError。 + local_session_id = str(session.session_id) + initial_session_status = str(session.status or 'running') + initial_external_conversation_id = str(external_conversation_id or '').strip() or None + stream_session = SimpleNamespace(session_id=local_session_id) + normalized_files: list[dict] | None = None if files is not None: if not isinstance(files, list): @@ -161,8 +168,8 @@ def chat_completions(): display_query=display_query, user=user_proxy, agent=agent_proxy, - session=session, - external_conversation_id=external_conversation_id, + session=stream_session, + external_conversation_id=initial_external_conversation_id, request_id=request_id, normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( @@ -182,8 +189,8 @@ def chat_completions(): agent=agent_proxy, query=query, agent_id=agent_id, - session_id=session.session_id, - external_conversation_id=external_conversation_id, + session_id=local_session_id, + external_conversation_id=initial_external_conversation_id, normalized_files=normalized_files, kb_type=kb_type, leave_supported=leave_supported, @@ -195,13 +202,13 @@ def chat_completions(): query, user_proxy.id, agent_proxy, - external_conversation_id, + initial_external_conversation_id, request_id=request_id, - session_id=session.session_id, + session_id=local_session_id, files=normalized_files, inputs=build_chat_dify_inputs( agent_proxy, - session_id=session.session_id, + session_id=local_session_id, request_id=request_id, trigger_source="frontend_chat", user_role=user_proxy.role, @@ -222,14 +229,14 @@ def chat_completions(): relay_first_chunk_at: float | None = None created_event = { 'event': 'session_created', - 'conversation_id': session.session_id, - 'provider_conversation_id': session.external_conversation_id, - 'session_status': session.status, + 'conversation_id': local_session_id, + 'provider_conversation_id': initial_external_conversation_id, + 'session_status': initial_session_status, } yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n" - known_provider_conversation_id = session.external_conversation_id - known_status = session.status + known_provider_conversation_id = initial_external_conversation_id + known_status = initial_session_status emitted_handler_state_keys: set[str] = set() from app.services.chat.stream_relay import ( @@ -272,7 +279,7 @@ def chat_completions(): updated_session = _update_chat_session( user_id, agent_id, - session.session_id, + local_session_id, status=known_status, external_conversation_id=known_provider_conversation_id, touch=True, @@ -281,7 +288,7 @@ def chat_completions(): known_status = updated_session.status event_data['provider_conversation_id'] = provider_conversation_id - event_data['conversation_id'] = session.session_id + event_data['conversation_id'] = local_session_id event_data['session_status'] = known_status if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'): relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None @@ -289,7 +296,7 @@ def chat_completions(): current_app.logger.info( '[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s', request_id, - session.session_id, + local_session_id, relay_first_ms, relay_total_ms, event_name, @@ -307,8 +314,8 @@ def chat_completions(): ): yield terminal_line except Exception as exc: - current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id) - payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'} + current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id) + payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'} yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" # 返回 SSE 响应,mimetype 设为 text/event-stream diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 8d879f95..3da2db10 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -5,7 +5,7 @@ backend/app/api/workspace/shipping_notice.py 依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service / tools / notice_upload / ui_state、shipping_processing_projection。 逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与 - 统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint; + 统一 AppError;人工上传仅确认唯一 Excel 已上传,不采集回执或凭据;Chat Turn 履约写路径已废弃,请改走本 Blueprint; `/shipping-processing/*` 为统一进度读源;历史 `/shipping-batches*` 已删除; Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。 """ @@ -586,6 +586,22 @@ def workspace_list_shipping_task_audit_timeline(task_no: str): return _ok(payload) +@workspace_shipping_notice_bp.route('/shipping-tasks//freight-notice-groups', methods=['GET']) +def workspace_shipping_task_freight_notice_groups(task_no: str): + """读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。""" + user = _require_user() + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + from app.services.shipping_notice.query_service import ( + get_task_visible_to_user, + list_freight_notice_groups_for_task, + ) + + task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin) + if not task: + raise NotFoundError('Not found') + return _ok(list_freight_notice_groups_for_task(task, user_id=int(user.id), is_admin=is_admin)) + + @workspace_shipping_notice_bp.route('/shipping-tasks//ui-state', methods=['GET']) def workspace_shipping_task_ui_state(task_no: str): """ @@ -638,7 +654,7 @@ def workspace_update_shipping_notice_fields(task_no: str): @workspace_shipping_notice_bp.route('/shipping-freight-cancellations//complete', methods=['POST']) def workspace_complete_shipping_freight_cancellation(cancellation_id: int): - """登记货代撤销回执并解除合法后继版本的履约阻断。""" + """登记已取得外部撤销确认并解除合法后继版本的履约阻断。""" user = _require_user() data = request.get_json(silent=True) or {} from app.models import ShippingFreightCancellation @@ -650,9 +666,7 @@ def workspace_complete_shipping_freight_cancellation(cancellation_id: int): raise NotFoundError('Not found') from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation row = complete_freight_cancellation( - cancellation_id=cancellation.id, actor_id=int(user.id), - freight_receipt_no=str(data.get('freight_receipt_no') or ''), - receipt_asset_id=data.get('receipt_asset_id'), note=str(data.get('note') or ''), + cancellation_id=cancellation.id, actor_id=int(user.id), note=str(data.get('note') or ''), ) db.session.commit() return _ok({'id': row.id, 'status': row.status, 'old_task_id': row.old_task_id, 'new_task_id': row.new_task_id}) @@ -834,9 +848,10 @@ def workspace_auto_progress_shipping_task(task_no: str): @workspace_shipping_notice_bp.route('/shipping-tasks//mark-manual-uploaded', methods=['POST']) def workspace_mark_manual_uploaded(task_no: str): """ - 登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。 + 兼容旧 task_no 的人工上传确认;不再提交或记录截图/PDF、货代回执号。 - 核心逻辑:委托 upload_to_freight(mode=manual_confirm);禁止 RPA。 + 核心逻辑:仅委托 upload_to_freight(mode=manual_confirm),新客户端必须改用 + business_no 的 `/shipping-notices//confirm-uploaded`。 """ user = _require_user() task = get_task_for_user(task_no, user.id) @@ -852,21 +867,232 @@ def workspace_mark_manual_uploaded(task_no: str): 'actor_id': user.id, '_trusted_user_id': user.id, 'event_source': 'workspace_api', - 'evidence_asset_no': data.get('evidence_asset_no'), - 'freight_ref_no': data.get('freight_ref_no'), 'artifact_id': data.get('artifact_id'), } result = shipping_tools.upload_to_freight(payload) if isinstance(result, dict) and str(result.get('status') or '') == 'ok': - # 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。 + # 人工确认已由服务原子登记;随后只推进最终上传 Gate。 from app.services.shipping_notice.progress_workflow import run_task_auto_progress run_task_auto_progress( - str(task.task_no), trigger='manual_upload_receipt_recorded', operator_id=int(user.id), + str(task.task_no), trigger='manual_upload_confirmed', operator_id=int(user.id), ) return _ok(result) +def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]: + """ + 按发货通知单号确认唯一 Excel 已上传;内部 task_no 仅用于既有状态机和审计追溯。 + + Args: + business_no: 对外发货通知单号,禁止调用方以 task_no 代替。 + user_id: 当前服务端会话用户。 + artifact_id: 可选唯一 Excel Artifact 主键;不传时由服务端解析。 + + Returns: + 包含 business_no 和既有上传结果的字典。 + + Raises: + NotFoundError: 通知单不存在或当前用户无写权限。 + """ + task = get_task_for_user(str(business_no).strip().upper(), user_id) + if task is None or str(task.business_no or '').upper() != str(business_no).strip().upper(): + raise NotFoundError('Shipping notice not found') + _assert_fulfillment_task_ownership(task, user_id) + from app.services.shipping_notice import tools as shipping_tools + + result = shipping_tools.upload_to_freight({ + 'task_id': task.task_no, + 'mode': 'manual_confirm', + 'operator_id': user_id, + 'actor_id': user_id, + '_trusted_user_id': user_id, + 'event_source': 'workspace_api', + 'artifact_id': artifact_id, + }) + if isinstance(result, dict) and str(result.get('status') or '') == 'ok': + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + + run_task_auto_progress( + str(task.task_no), trigger='manual_upload_confirmed', operator_id=user_id, + ) + return {'business_no': str(task.business_no), **dict(result or {})} + + +def _load_business_notice_for_user(*, business_no: str, user_id: int) -> ShippingNotice: + """ + 按精确发货通知单号加载当前用户可操作的 Notice。 + + 核心逻辑:先由既有用户归属查询过滤,再二次比较 Notice.business_no;禁止 task_no、 + 历史聚合编号或模糊引用进入新的货代操作入口。 + + Args: + business_no: 对外发货通知单号。 + user_id: 当前服务端会话用户主键。 + + Returns: + 当前用户拥有履约写权限的 ShippingNotice。 + + Raises: + NotFoundError: 编号不存在或用户不可访问。 + """ + normalized = str(business_no or '').strip().upper() + task = get_task_for_user(normalized, user_id) + if task is None or str(task.business_no or '').strip().upper() != normalized: + raise NotFoundError('Shipping notice not found') + _assert_fulfillment_task_ownership(task, user_id) + return task + + +def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]: + """按 business_no 发起单张通知的货代 RPA 上传或重试。""" + task = _load_business_notice_for_user(business_no=business_no, user_id=user_id) + from app.services.shipping_notice import tools as shipping_tools + + result = shipping_tools.upload_to_freight({ + 'task_id': task.task_no, + 'mode': 'retry_upload', + 'operator_id': user_id, + 'actor_id': user_id, + '_trusted_user_id': user_id, + 'event_source': 'workspace_api', + 'artifact_id': artifact_id, + }) + return {'business_no': str(task.business_no), **dict(result or {})} + + +@workspace_shipping_notice_bp.route('/shipping-notices//confirm-uploaded', methods=['POST']) +def workspace_confirm_shipping_notice_uploaded(business_no: str): + """确认一张发货通知单的唯一 Excel 已人工上传,不接收回执号或截图/PDF。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_artifact_id = data.get('artifact_id') + try: + artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None + except (TypeError, ValueError) as exc: + raise ValidationError('artifact_id must be an integer') from exc + return _ok(_confirm_notice_uploaded( + business_no=business_no, user_id=int(user.id), artifact_id=artifact_id, + )) + + +@workspace_shipping_notice_bp.route('/shipping-notices//rpa-upload', methods=['POST']) +def workspace_start_shipping_notice_rpa_upload(business_no: str): + """按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_artifact_id = data.get('artifact_id') + try: + artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None + except (TypeError, ValueError) as exc: + raise ValidationError('artifact_id must be an integer') from exc + return _ok(_start_notice_rpa_upload( + business_no=business_no, user_id=int(user.id), artifact_id=artifact_id, + ), status=202) + + +@workspace_shipping_notice_bp.route('/shipping-notices/batch/confirm-uploaded', methods=['POST']) +def workspace_batch_confirm_shipping_notices_uploaded(): + """批量确认多个通知单已上传;每张通知单独立事务裁决,单项失败不回滚其他单。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_values = data.get('business_nos') + if not isinstance(raw_values, list): + raise ValidationError('business_nos must be a non-empty list') + business_nos = list(dict.fromkeys( + str(value or '').strip().upper() for value in raw_values if str(value or '').strip() + )) + if not business_nos or len(business_nos) > 100: + raise ValidationError('business_nos must contain 1 to 100 business numbers') + results: list[dict[str, Any]] = [] + for business_no in business_nos: + try: + result = _confirm_notice_uploaded(business_no=business_no, user_id=int(user.id)) + db.session.commit() + results.append({'business_no': business_no, 'status': 'confirmed', 'result': result}) + except AppError as exc: + db.session.rollback() + results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message}) + except Exception: + db.session.rollback() + raise + return _ok({'results': results}) + + +@workspace_shipping_notice_bp.route('/shipping-notices/batch/rpa-upload', methods=['POST']) +def workspace_batch_start_shipping_notice_rpa_upload(): + """批量发起 RPA 上传;每个 business_no 独立提交,单项失败不影响其他通知单。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_values = data.get('business_nos') + if not isinstance(raw_values, list): + raise ValidationError('business_nos must be a non-empty list') + business_nos = list(dict.fromkeys( + str(value or '').strip().upper() for value in raw_values if str(value or '').strip() + )) + if not business_nos or len(business_nos) > 100: + raise ValidationError('business_nos must contain 1 to 100 business numbers') + results: list[dict[str, Any]] = [] + for business_no in business_nos: + try: + result = _start_notice_rpa_upload(business_no=business_no, user_id=int(user.id)) + db.session.commit() + result_status = 'accepted' if str(result.get('status') or '').lower() in {'ok', 'running'} else 'blocked' + results.append({'business_no': business_no, 'status': result_status, 'result': result}) + except AppError as exc: + db.session.rollback() + results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message}) + except Exception: + db.session.rollback() + raise + return _ok({'results': results}, status=202) + + +@workspace_shipping_notice_bp.route('/shipping-notices//export', methods=['GET']) +def workspace_shipping_notice_export(business_no: str): + """按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。""" + user = _require_user() + task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id)) + err_msg = task_export_error_message(task) + if err_msg: + raise NotFoundError(err_msg) + resolved = resolve_task_export_download(task) + assert resolved is not None + path, download_name = resolved + from app.services.shipping_notice.fulfillment_audit import record_access_audit + record_access_audit( + action='download_notice_excel', + aggregate_type='shipping_notice', + aggregate_id=str(task.business_no), + actor_id=user.id, + task_no=str(task.task_no), + reason_code='excel_downloaded', + metadata={'business_no': str(task.business_no), 'export': 'excel'}, + ) + return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE) + + +@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST']) +def workspace_shipping_notice_export_archive(): + """按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。""" + user = _require_user() + data = request.get_json(silent=True) or {} + raw_values = data.get('business_nos') + if not isinstance(raw_values, list): + raise ValidationError('business_nos must be a non-empty list') + business_nos = list(dict.fromkeys( + str(value or '').strip().upper() for value in raw_values if str(value or '').strip() + )) + if not business_nos or len(business_nos) > 100: + raise ValidationError('business_nos must contain 1 to 100 business numbers') + from app.services.shipping_notice.export_archive import build_export_archive + + stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos) + response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') + response.call_on_close(stream.close) + return response + + @workspace_shipping_notice_bp.route('/shipping-tasks//export', methods=['GET']) def workspace_shipping_task_export(task_no: str): """下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" @@ -1282,14 +1508,24 @@ def workspace_list_shipping_order_extraction_documents(run_no: str): @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//review', methods=['GET']) def workspace_get_shipping_order_review_run(run_no: str): - """读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。""" + """ + 读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。 + + 通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变 + JSON 响应契约或业务数据。 + """ user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.order_review_projection import serialize_review_run from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user - payload = serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin)) + lookup_started = perf_counter() + review_run = get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() + payload = serialize_review_run(review_run) + projection_ms = (perf_counter() - projection_started) * 1000 record_access_audit( action='view_order_review_run', aggregate_type='order_extraction_run', @@ -1297,20 +1533,34 @@ def workspace_get_shipping_order_review_run(run_no: str): actor_id=user.id, run_no=str(run_no), ) - return _ok(payload) + response = current_app.make_response(_ok(payload)) + response.headers['Server-Timing'] = ( + f'review_lookup;dur={lookup_ms:.1f}, ' + f'review_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/', methods=['GET']) def workspace_get_shipping_order_review_queue(run_no: str): - """读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。""" + """ + 读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。 + + 通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变 + JSON 响应契约或业务数据。 + """ user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.fulfillment_audit import record_access_audit from app.services.shipping_notice.order_review_projection import serialize_review_queue from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user + lookup_started = perf_counter() runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() payload = serialize_review_queue(runs) + projection_ms = (perf_counter() - projection_started) * 1000 record_access_audit( action='view_order_review_queue', aggregate_type='conversation', @@ -1320,12 +1570,22 @@ def workspace_get_shipping_order_review_queue(run_no: str): run_no=str(run_no), metadata={'item_count': len(payload.get('items') or [])}, ) - return _ok(payload) + response = current_app.make_response(_ok(payload)) + response.headers['Server-Timing'] = ( + f'queue_lookup;dur={lookup_ms:.1f}, ' + f'queue_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/', methods=['GET']) def workspace_get_shipping_order_review_case(case_no: str): - """读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。""" + """ + 读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。 + + 通过 Server-Timing 暴露查找与快照投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变 + JSON 响应契约或业务数据。 + """ user = _require_user() is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' from app.services.shipping_notice.fulfillment_audit import record_access_audit @@ -1335,10 +1595,12 @@ def workspace_get_shipping_order_review_case(case_no: str): from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user # 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。 - snapshot = build_order_review_case_snapshot( - get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin), - is_admin=is_admin, - ) + lookup_started = perf_counter() + review_case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin) + lookup_ms = (perf_counter() - lookup_started) * 1000 + projection_started = perf_counter() + snapshot = build_order_review_case_snapshot(review_case, is_admin=is_admin) + projection_ms = (perf_counter() - projection_started) * 1000 record_access_audit( action='view_order_review_case', aggregate_type='order_review_case', @@ -1351,7 +1613,12 @@ def workspace_get_shipping_order_review_case(case_no: str): else None ), ) - return _ok(snapshot) + response = current_app.make_response(_ok(snapshot)) + response.headers['Server-Timing'] = ( + f'case_lookup;dur={lookup_ms:.1f}, ' + f'case_projection;dur={projection_ms:.1f}' + ) + return response @workspace_shipping_notice_bp.route( diff --git a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py index 40e4882d..987f87e8 100644 --- a/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py +++ b/backend/app/jobs/handlers/shipping_post_ot_wave_progress.py @@ -63,12 +63,13 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non try: from app.services.shipping_notice.fulfillment_workflow import generate_excel - # [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。 + # [STEP] 为本次独立 Notice 生成 Excel,禁止捎带同 PO 的其他项次。 gen = generate_excel({ 'task_id': task.task_no, 'wave_no': wave_no, 'line_keys': list(frozen.get('line_keys') or []), 'post_ot_wave': True, + '_orchestrator_internal_dispatch': True, }) status = str((gen or {}).get('status') or '').strip().lower() if status in {'failed', 'error'}: diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 0098b220..cf357e86 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -151,7 +151,6 @@ from app.models.shipping_receipt_report import ( from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession from app.models.shipping_customer import ( ShippingBusinessSequence, - ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -290,7 +289,6 @@ __all__ = [ 'ShippingCustomerSiteIdentifier', 'ShippingCustomerImportBatch', 'ShippingCustomerImportRow', - 'ShippingCase', 'ShippingBusinessSequence', 'ShippingCustomerShadowResolution', 'ShippingCustomerShadowMatch', diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 072b4842..f658dbdc 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -25,6 +25,7 @@ from typing import List, Optional from sqlalchemy import ( Boolean, CheckConstraint, + Date, DateTime, Float, ForeignKey, @@ -54,6 +55,7 @@ class ShippingNotice(Base): Index('ix_shipping_notices_conversation', 'conversation_id'), Index('ix_shipping_notices_current_step', 'current_step'), Index('ix_shipping_notices_upload_status', 'upload_status'), + Index('ix_shipping_notices_business_no', 'business_no'), Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'), Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'), Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), @@ -70,11 +72,16 @@ class ShippingNotice(Base): id: Mapped[int] = mapped_column(primary_key=True) task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) - shipping_case_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_cases.id'), - index=True, - nullable=True, + customer_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_customers.id'), index=True, nullable=True, ) + customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) + # 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。 + business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) + business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True) + business_sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + business_numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) source_type: Mapped[str] = mapped_column(String(32), default='manual') @@ -234,11 +241,7 @@ class ShippingNotice(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - shipping_case: Mapped[Optional['ShippingCase']] = relationship( - 'ShippingCase', - back_populates='tasks', - lazy='joined', - ) + customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined') events: Mapped[List['ShippingTaskEvent']] = relationship( 'ShippingTaskEvent', back_populates='task', diff --git a/backend/app/models/shipping_customer.py b/backend/app/models/shipping_customer.py index 38d7dcdc..2828e693 100644 --- a/backend/app/models/shipping_customer.py +++ b/backend/app/models/shipping_customer.py @@ -1,9 +1,9 @@ """ backend/app/models/shipping_customer.py -用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。 +用途:货代标准客户、客户识别证据与业务编号流水模型。 依赖:models.base.Base、users、shipping_notices。 -逻辑:客户主数据提供稳定身份;ShippingCase 聚合 Notice 修订链;流水表供后续编号服务原子递增。 +逻辑:客户主数据提供稳定身份;发货通知自持履约事实;流水表供编号服务原子递增。 """ from __future__ import annotations @@ -55,7 +55,6 @@ class ShippingCustomer(Base): back_populates='customer', cascade='all, delete-orphan', ) - cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer') merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship( 'ShippingCustomer', remote_side='ShippingCustomer.id', @@ -189,40 +188,6 @@ class ShippingCustomerSiteIdentifier(Base): site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers') -class ShippingCase(Base): - """一票发货业务聚合;多个线性任务修订版本共享同一业务单。""" - - __tablename__ = 'shipping_cases' - __table_args__ = ( - Index('ix_shipping_cases_customer_created', 'customer_id', 'created_at'), - Index('ix_shipping_cases_status_created', 'status', 'created_at'), - UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - case_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) - customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True) - business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) - customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) - customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) - business_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) - sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - numbering_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') - status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open') - replaces_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_cases.id'), nullable=True) - created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) - updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - - customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases') - tasks: Mapped[List['ShippingNotice']] = relationship( - 'ShippingNotice', - back_populates='shipping_case', - lazy='selectin', - ) - - class ShippingBusinessSequence(Base): """按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。""" diff --git a/backend/app/models/shipping_excel_template.py b/backend/app/models/shipping_excel_template.py index 3320abcd..91a069cf 100644 --- a/backend/app/models/shipping_excel_template.py +++ b/backend/app/models/shipping_excel_template.py @@ -4,7 +4,7 @@ models/shipping_excel_template.py 用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。 依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。 逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和; - co8e9f0a1b2c 已删除 export artifact 的 batch_id 列。 + co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。 """ from __future__ import annotations diff --git a/backend/app/models/shipping_freight_cancellation.py b/backend/app/models/shipping_freight_cancellation.py index a0199351..a54c19e1 100644 --- a/backend/app/models/shipping_freight_cancellation.py +++ b/backend/app/models/shipping_freight_cancellation.py @@ -12,7 +12,7 @@ from app.models.base import Base class ShippingFreightCancellation(Base): - """已上传旧 Notice 的撤销申请与货代回执;成功前新版本不得履约。""" + """已上传旧 Notice 的撤销申请与外部撤销确认;成功前新版本不得履约。""" __tablename__ = 'shipping_notice_freight_cancellations' __table_args__ = ( diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index 9e6f7670..267371e2 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -155,8 +155,9 @@ class ShippingUploadAttempt(Base): finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + # 历史资产关联字段仅为兼容旧数据;新货代上传不写截图或文件证据。 evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True) - # [BE-05] RPA 成功时持久化绿色 DOM 证据(kind/selector/observed_at/filename 等)。 + # RPA 仅保存最小状态摘要(kind/selector/observed_at/filename 等),不保存截图或 DOM。 success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) diff --git a/backend/app/models/shipping_order_review_wave_line.py b/backend/app/models/shipping_order_review_wave_line.py index 940d703b..19b4427d 100644 --- a/backend/app/models/shipping_order_review_wave_line.py +++ b/backend/app/models/shipping_order_review_wave_line.py @@ -1,7 +1,7 @@ """ models/shipping_order_review_wave_line.py -用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一个 Task。 +用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。 依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。 逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入; (review_case_id, line_key) 数据库唯一约束防并发重复入波次。 diff --git a/backend/app/services/admin/shipping_customer_lifecycle_service.py b/backend/app/services/admin/shipping_customer_lifecycle_service.py index 42c3cf5d..6d123479 100644 --- a/backend/app/services/admin/shipping_customer_lifecycle_service.py +++ b/backend/app/services/admin/shipping_customer_lifecycle_service.py @@ -16,7 +16,6 @@ from sqlalchemy import select from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -27,6 +26,7 @@ from app.models import ( ShippingOrderCustomerMatch, ShippingCustomerShadowMatch, ShippingCustomerShadowResolution, + ShippingNotice, ) @@ -62,7 +62,7 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An } shadow_normalized = len(matched_resolution_ids) blockers = { - 'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(), + 'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(), 'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(), 'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(), 'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(), diff --git a/backend/app/services/admin/shipping_customer_service.py b/backend/app/services/admin/shipping_customer_service.py index 417ad456..2dce356e 100644 --- a/backend/app/services/admin/shipping_customer_service.py +++ b/backend/app/services/admin/shipping_customer_service.py @@ -17,7 +17,6 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( - ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -25,6 +24,7 @@ from app.models import ( ShippingCustomerSite, ShippingCustomerSiteIdentifier, ShippingIdentityEvidence, + ShippingNotice, ) from app.services.shipping_notice.customer_normalization import ( clean_text, @@ -117,7 +117,7 @@ def serialize_customer( record: ShippingCustomer, *, include_identifiers: bool = False, - case_count: int | None = None, + notice_count: int | None = None, identifier_count: int | None = None, identity_evidence_count: int | None = None, ) -> dict[str, Any]: @@ -127,7 +127,7 @@ def serialize_customer( Args: record: 标准客户 ORM 记录。 include_identifiers: 是否附带识别证据明细。 - case_count: 列表查询预聚合的业务单数量;为空时现场查询。 + notice_count: 列表查询预聚合的发货通知数量;为空时现场查询。 identifier_count: 历史固定类型证据数量,仅供存量审计显示。 identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。 Returns: @@ -144,7 +144,7 @@ def serialize_customer( 'updated_by_id': record.updated_by_id, 'created_at': record.created_at.isoformat() if record.created_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None, - 'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(), + 'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(), 'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(), 'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query( ShippingIdentityEvidence.id, @@ -173,9 +173,9 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: Returns: items、total、page、page_size、pages。 """ - case_counts = ( - db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count')) - .group_by(ShippingCase.customer_id) + notice_counts = ( + db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count')) + .group_by(ShippingNotice.customer_id) .subquery() ) identifier_counts = ( @@ -207,12 +207,12 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: query = ( db.session.query( ShippingCustomer, - func.coalesce(case_counts.c.case_count, 0), + func.coalesce(notice_counts.c.notice_count, 0), func.coalesce(identifier_counts.c.identifier_count, 0), func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0) + func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0), ) - .outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id) + .outerjoin(notice_counts, notice_counts.c.customer_id == ShippingCustomer.id) .outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id) .outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id) .outerjoin(site_identity_evidence_counts, site_identity_evidence_counts.c.customer_id == ShippingCustomer.id) @@ -244,10 +244,10 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]: return { 'items': [ serialize_customer( - customer, case_count=int(case_count), identifier_count=int(identifier_count), + customer, notice_count=int(notice_count), identifier_count=int(identifier_count), identity_evidence_count=int(identity_evidence_count), ) - for customer, case_count, identifier_count, identity_evidence_count in items + for customer, notice_count, identifier_count, identity_evidence_count in items ], 'total': total, 'page': page, diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index 8d255bd7..f66dfd61 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -301,9 +301,9 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi pending_seen = True if gate.status in {'pending', 'blocked_retryable'}: return gate, None - # 上传回执是人工完成的外部事实,不是“重试业务动作”。登记成功后仅允许 - # 服务端重新读取该事实并通过最后一个 Gate。 - if gate.gate_code == 'upload_receipt_recorded' and gate.status == 'blocked_manual': + # 人工上传确认是外部完成声明,不是“重试业务动作”。确认成功后仅允许 + # 服务端重新读取 Attempt 事实并通过最后一个 Gate。 + if gate.gate_code == 'manual_upload_handoff' and gate.status == 'blocked_manual': return gate, None return None, None return None, None diff --git a/backend/app/services/shipping_notice/business_case_service.py b/backend/app/services/shipping_notice/business_case_service.py deleted file mode 100644 index 350e093f..00000000 --- a/backend/app/services/shipping_notice/business_case_service.py +++ /dev/null @@ -1,88 +0,0 @@ -""" -services/shipping_notice/business_case_service.py - -用途:为新建货代任务创建或继承业务单聚合。 -依赖:db、ShippingCase、ShippingNotice、uuid/datetime。 -逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。 -""" - -from __future__ import annotations - -import uuid -from datetime import datetime - -from app import db -from app.core.errors import ConflictError -from app.models import ShippingCase, ShippingNotice - - -def generate_shipping_case_no() -> str: - """生成内部业务单聚合编号;仅用于系统关联,不对外替代 business_no。""" - return f"SC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" - - -def create_shipping_case(*, created_by_id: int | None = None) -> ShippingCase: - """ - 创建未绑定客户、未编号的业务单聚合。 - - Args: - created_by_id: 创建任务的用户 ID,可为空。 - Returns: - 尚未提交事务的 ShippingCase。 - """ - case = ShippingCase( - case_no=generate_shipping_case_no(), - created_by_id=created_by_id, - numbering_status='pending', - status='open', - ) - db.session.add(case) - db.session.flush() - return case - - -def resolve_shipping_case_for_new_task( - *, - supersedes_task_id: int | None = None, - duplicate_resolution_type: str | None = None, - created_by_id: int | None = None, -) -> ShippingCase: - """ - 为即将创建的任务解析业务单归属。 - - 核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单, - 保证强制新建重新占用未来流水。 - - Args: - supersedes_task_id: 修订目标任务主键,仅 revision 使用。 - duplicate_resolution_type: normal/revision/force_create。 - created_by_id: 新任务创建人。 - Returns: - 新任务应关联的 ShippingCase。 - Raises: - ConflictError: revision 缺少或找不到父任务。 - """ - resolution_type = str(duplicate_resolution_type or 'normal').strip().lower() - if resolution_type != 'revision': - return create_shipping_case(created_by_id=created_by_id) - - if not supersedes_task_id: - raise ConflictError( - '修订任务缺少父任务', - code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', - ) - parent = db.session.get(ShippingNotice, int(supersedes_task_id)) - if parent is None: - raise ConflictError( - '修订目标任务不存在', - code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', - details={'supersedes_task_id': supersedes_task_id}, - ) - if parent.shipping_case is None: - raise ConflictError( - '修订目标任务缺少业务单关联', - code='SHIPPING_NOTICE.REVISION_CASE_MISSING', - details={'supersedes_task_id': supersedes_task_id}, - ) - return parent.shipping_case - diff --git a/backend/app/services/shipping_notice/business_numbering_service.py b/backend/app/services/shipping_notice/business_numbering_service.py index ea853062..847b2636 100644 --- a/backend/app/services/shipping_notice/business_numbering_service.py +++ b/backend/app/services/shipping_notice/business_numbering_service.py @@ -2,7 +2,7 @@ services/shipping_notice/business_numbering_service.py 用途:为已确认客户的货代业务单分配不可变业务编号。 -依赖:ShippingCase/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。 +依赖:ShippingNotice/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。 逻辑:锁定业务单后按客户与上海业务日期原子递增流水;编号写入业务单快照,事务由调用方提交。 """ @@ -15,7 +15,7 @@ from sqlalchemy import update from app import db from app.core.errors import ConflictError -from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer +from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE BUSINESS_TYPE = "shipping_notice" @@ -121,50 +121,46 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int: return int(value) -def assign_business_number(case: ShippingCase, *, moment: datetime | None = None) -> str: +def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str: """ - 为业务单幂等分配业务编号,调用方负责同事务提交。 - - 核心逻辑:已有编号直接返回;否则校验启用客户与简码快照,取得上海日期流水并写入不可变编号字段。 + 为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。 Args: - case: 已加锁且已绑定标准客户的业务单。 - moment: 可选测试时刻。 - Returns: - 分配或已存在的业务编号。 - Raises: - ConflictError: 客户无效、简码缺失或当日两位流水耗尽。 - """ - if case.business_no: - return str(case.business_no) - if case.customer_id is None: - raise ConflictError( - "Shipping case customer must be confirmed before numbering", - code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED", - ) - customer = db.session.get(ShippingCustomer, int(case.customer_id)) - if customer is None or customer.status != "active": - raise ConflictError( - "Active customer is required before numbering", - code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID", - ) + notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。 + moment: 可选时刻,测试时用于固定上海业务日期。 - short_code = str(customer.short_code or "").strip().upper() + Returns: + 分配或已存在的 business_no。 + + Raises: + ConflictError: 通知单缺少客户或客户无效。 + """ + if notice.business_no: + return str(notice.business_no) + if notice.customer_id is None: + raise ConflictError( + 'Shipping notice customer must be confirmed before numbering', + code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED', + ) + customer = db.session.get(ShippingCustomer, int(notice.customer_id)) + if customer is None or customer.status != 'active': + raise ConflictError( + 'Active customer is required before numbering', + code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID', + ) + short_code = str(customer.short_code or '').strip().upper() if not SHORT_CODE_RE.fullmatch(short_code): raise ConflictError( - "Customer short code is invalid for business numbering", - code="SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID", - details={"customer_id": customer.id, "short_code": short_code}, + 'Customer short code is invalid for business numbering', + code='SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID', ) business_date = shanghai_business_date(moment) sequence_value = _next_sequence_value(customer.id, business_date) - business_no = format_business_no(short_code, business_date, sequence_value) - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = short_code - case.business_date = business_date - case.sequence_value = sequence_value - case.numbering_rule_version = NUMBERING_RULE_VERSION - case.numbering_status = "assigned" - case.business_no = business_no + notice.business_no = format_business_no(short_code, business_date, sequence_value) + notice.business_date = business_date + notice.business_sequence_value = sequence_value + notice.business_numbering_rule_version = NUMBERING_RULE_VERSION + notice.customer_name_snapshot = customer.standard_name + notice.customer_short_code_snapshot = short_code db.session.flush() - return business_no + return str(notice.business_no) diff --git a/backend/app/services/shipping_notice/candidate_qualification_contract.py b/backend/app/services/shipping_notice/candidate_qualification_contract.py index ba6c561f..24566bc9 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_contract.py +++ b/backend/app/services/shipping_notice/candidate_qualification_contract.py @@ -25,8 +25,6 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({ CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v3.0-unified-profile' # 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。 -# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后, -# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。 CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = ( 'auto_create_enabled', 'route_stp_eligible', @@ -35,7 +33,6 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = ( 'key_fields_minimum_confidence', 'evidence_complete', 'field_conflicts_resolved', - 'vc_source_merged_clean', 'duplicate_resolved', 'customer_confirmed', 'idempotency_ok', @@ -50,7 +47,6 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = { 'key_fields_minimum_confidence': 'field_low_confidence', 'evidence_complete': 'evidence_missing', 'field_conflicts_resolved': 'field_conflict', - 'vc_source_merged_clean': 'vc_source_conflict_unresolved', 'duplicate_resolved': 'duplicate_unresolved', 'customer_confirmed': 'customer_confirmation_required', 'idempotency_ok': 'task_already_exists', @@ -67,8 +63,6 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({ 'field_low_confidence', # PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。 'pdf_preferred_critical_conflict', - # Vendor Comments 三来源值不一致,须人工裁决但不硬阻塞人工建单。 - 'vc_source_conflict_unresolved', }) # 解析来源(写入 parser_trace,不直接决定资格)。 diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index 076b3c3d..aa8b8e0b 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -35,11 +35,6 @@ from app.services.shipping_notice.candidate_qualification_contract import ( CANDIDATE_QUALIFICATION_GATE_REASON_CODES, CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES, ) -from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import ( - CQ_VC_BLOCKING_REASONS, - CQ_VC_REVIEW_REASONS, - collect_vc_candidate_conflicts, -) from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled @@ -126,10 +121,6 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]: 核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突 与其他未知阻断项继续 fail-closed。 - 注意:Vendor Comments 三来源冲突由独立 vc_source_merged_clean 门禁 - (见 _vc_gate_ok)评估,不入本集合,避免污染 field_conflicts_resolved - 原有零回归语义。 - Args: candidate: ShippingOrderCandidate 或兼容替身。 @@ -164,66 +155,14 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]: return blocking -# --------------------------------------------------------------------------- -# VC 三来源门禁:独立于 Candidate.conflicts_json,从 structured.extraction -# vendor_comments_merged 读,避免冲突历史与裁决历史相互污染。 -# --------------------------------------------------------------------------- -def _vc_gate_ok(candidate: Any) -> bool: +def current_open_candidate_conflicts(candidate: Any) -> list[Any]: + """返回当前仍开放且会阻断自动建单的 Candidate 冲突。 + + 复核投影与资格门禁必须共享这一入口:历史冲突记录只有在明确标记为 + ``blocking + unresolved`` 时才是当前阻断事实;无法判定的旧结构继续 + fail-closed,避免通过空投影或猜测放行自动建单。 """ - VC 三来源合并结果是否全部清洁(无阻断冲突)。 - - 核心逻辑:缺 VC merged 载荷 → 视为未启用 → OK; - severity == blocking 的项 → 必须视为 fail(硬阻断); - severity == review_required 但 can_auto_create 场景下同样 fail, - 交由上层 CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES 归类到 - review_required 总体状态(允许人工建单,不允许 STP 自动建单)。 - - Args: - candidate: ShippingOrderCandidate 或兼容替身。 - - Returns: - True 表示 VC 路径「已干净」,可放行自动/人工建单。 - """ - try: - items = collect_vc_candidate_conflicts(candidate) - except Exception: # noqa: BLE001 — 门禁 fail-closed:解析异常视为未通过 - return False - for it in items: - if not isinstance(it, dict): - continue - severity = str(it.get('severity') or 'blocking').strip() - reason = str(it.get('reason') or '').strip() - if reason in CQ_VC_BLOCKING_REASONS: - return False - if severity == 'blocking': - return False - if severity == 'review_required': - # review_required 对自动建单门禁同样算失败(上层会映射为 review_required 总体状态) - # 对人工建单是允许的,但 CQ 门禁统一口径:needs_review → fail; - # 人工建单的门禁是独立路径,在 order_review_confirmation_service 中。 - return False - return True - - -def _vc_fine_grained_reason(candidate: Any) -> str | None: - """ - VC 门禁失败时提取首个匹配的细因码,优先给出 format/region 错, - 冲突类错其次,保留默认 vc_source_conflict_unresolved 兜底。 - """ - try: - items = collect_vc_candidate_conflicts(candidate) - except Exception: # noqa: BLE001 - return None - priority_order = [ - 'vc_source_region_unbound', - 'vc_source_format_invalid', - 'vc_source_conflict_unresolved', - ] - seen = {str(x.get('reason') or '').strip() for x in items if isinstance(x, dict)} - for want in priority_order: - if want in seen: - return want - return None + return blocking_candidate_conflicts(candidate) def resolve_candidate_customer_resolved( @@ -410,7 +349,6 @@ def evaluate_candidate_qualification( ) evidence_ok = _evidence_ok(candidate) conflicts_ok = _conflicts_ok(candidate) - vc_ok = _vc_gate_ok(candidate) duplicate_ok = _duplicate_ok(candidate) customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved) idempotency_ok = _idempotency_ok(candidate) @@ -423,7 +361,6 @@ def evaluate_candidate_qualification( 'key_fields_minimum_confidence': key_confidence_ok, 'evidence_complete': evidence_ok, 'field_conflicts_resolved': conflicts_ok, - 'vc_source_merged_clean': vc_ok, 'duplicate_resolved': duplicate_ok, 'customer_confirmed': customer_ok, 'idempotency_ok': idempotency_ok, @@ -441,11 +378,6 @@ def evaluate_candidate_qualification( if pdf_reason: blocking_reason_codes.append(pdf_reason) continue - if key == 'vc_source_merged_clean': - vc_reason = _vc_fine_grained_reason(candidate) - if vc_reason: - blocking_reason_codes.append(vc_reason) - continue blocking_reason_codes.append( CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready') ) @@ -459,20 +391,7 @@ def evaluate_candidate_qualification( blocking_reason_codes=blocking_reason_codes, ) - # [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status - # 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。 evidence_snapshot = _evidence_snapshot(candidate) - try: - vc_items = collect_vc_candidate_conflicts(candidate) - except Exception: # noqa: BLE001 - vc_items = [] - vc_counts = { - 'vc_total_candidates': len(vc_items), - 'vc_review_required': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'review_required']), - 'vc_blocking': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'blocking']), - } - if vc_counts['vc_total_candidates']: - evidence_snapshot = {**evidence_snapshot, **vc_counts} score = _qualification_score(gates) confidence_policy = { 'minimum_confidence': float(min_confidence), diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py index 063758bf..b3fdbf7e 100644 --- a/backend/app/services/shipping_notice/customer_auto_resolution.py +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -15,7 +15,6 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( - ShippingCase, ShippingCustomer, ShippingCustomerShadowResolution, ShippingIdentityEvidence, @@ -35,9 +34,8 @@ from app.services.shipping_notice.customer_normalization import ( normalize_domain, normalize_email, ) -from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int -from app.services.shipping_notice.business_case_service import generate_shipping_case_no -from app.services.shipping_notice.business_numbering_service import assign_business_number +from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no +from app.services.shipping_notice.business_numbering_service import assign_notice_business_number AUTO_RESOLUTION_VERSION = "customer-auto-v2" CUSTOMER_AUDIT_EVENT_TYPES = ( @@ -297,8 +295,18 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: Returns: status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。 """ - # [PARAM_TUNING] 业务策略改为:已发布识别指纹唯一命中即可自动确认; - # 不再以全局开关、历史标注样本量或准确率二次阻断唯一确定结果。 + # [STEP 1] 总开关关闭时不评估证据,保证环境可安全降级至人工确认。 + if not auto_customer_resolution_enabled(): + return { + 'status': 'disabled', + 'rule_version': AUTO_RESOLUTION_VERSION, + 'customer_id': None, + 'evidence': [], + 'quality_gate': { + 'status': 'disabled', + 'is_eligible': False, + }, + } if task.source_candidate_id is None: return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} shadow = db.session.query(ShippingCustomerShadowResolution).filter_by( @@ -313,11 +321,16 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: if shadow is None: return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} - return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': { - 'status': 'bypassed_unique_match_policy', - 'is_eligible': True, - 'reason': '唯一识别指纹命中直接自动确认', - }} + decision = _resolve_auto_customer_from_shadow_resolution(shadow) + quality_gate = _auto_confirmation_quality_gate() + if not quality_gate['is_eligible']: + return { + **decision, + 'status': str(quality_gate['status']), + 'customer_id': None, + 'quality_gate': quality_gate, + } + return {**decision, 'quality_gate': quality_gate} def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: @@ -327,7 +340,7 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: 核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。 """ if task.customer_resolution_status == "confirmed": - return {"status": "already_confirmed", "customer_id": task.shipping_case.customer_id if task.shipping_case else None} + return {"status": "already_confirmed", "customer_id": task.customer_id} decision = resolve_auto_customer_from_shadow(task) db.session.add(ShippingTaskEvent( task_id=task.id, @@ -350,11 +363,11 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: event_type="customer_auto_confirmed", detail_json={ **decision, - "business_no": updated.shipping_case.business_no if updated.shipping_case else None, + "business_no": updated.business_no, }, )) db.session.flush() - return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no} + return {**decision, "status": "auto_confirmed", "business_no": updated.business_no} def correct_numbered_task_customer( @@ -365,10 +378,10 @@ def correct_numbered_task_customer( actor_id: int | None, ) -> dict[str, Any]: """ - 更正已编号业务单的标准客户,同时保留原号作废与替代关系。 + 更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。 - 核心逻辑:锁定原业务单并校验未上传 → 创建替代业务单和新号 → 迁移整条任务版本链 → - 清理当前版本的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 + 核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice → + 清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 Args: task: 原业务号或技术号定位到的当前任务版本。 @@ -387,31 +400,23 @@ def correct_numbered_task_customer( "Customer correction reason is required", code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED", ) - if task.shipping_case_id is None: - raise ConflictError( - "Numbered shipping case is required for customer correction", - code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", - ) - - original_case = ( - db.session.query(ShippingCase) - .filter(ShippingCase.id == int(task.shipping_case_id)) + original = ( + db.session.query(ShippingNotice) + .filter(ShippingNotice.id == int(task.id)) .with_for_update() .one_or_none() ) - if original_case is None: - raise NotFoundError("Shipping case not found", code="SHIPPING.CASE_NOT_FOUND") - if not original_case.business_no: + if original is None or not original.business_no: raise ConflictError( - "Numbered shipping case is required for customer correction", + "Numbered shipping notice is required for customer correction", code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", ) - existing_replacement = db.session.query(ShippingCase.id).filter_by( - replaces_case_id=original_case.id, + existing_replacement = db.session.query(ShippingNotice.id).filter_by( + supersedes_task_id=original.id, ).first() - if existing_replacement is not None or original_case.status == "voided": + if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided': raise ConflictError( - "Shipping case has already been replaced", + "Shipping notice has already been replaced", code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED", ) @@ -422,117 +427,79 @@ def correct_numbered_task_customer( raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED") if customer.status != "active": raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE") - if original_case.customer_id == customer.id: + if original.customer_id == customer.id: raise ValidationError( "Corrected customer must differ from the current customer", code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED", ) - versions = ( - db.session.query(ShippingNotice) - .filter_by(shipping_case_id=original_case.id) - .order_by(ShippingNotice.document_version.asc(), ShippingNotice.id.asc()) - .with_for_update() - .all() - ) - if not versions: + if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}: raise ConflictError( - "Shipping case has no task versions", - code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING", - ) - if any( - str(getattr(version, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} - or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"} - for version in versions - ): - raise ConflictError( - "Uploaded shipping cases require an external cancellation workflow before correction", + "Uploaded shipping notices require an external cancellation workflow before correction", code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED", ) - old_business_no = str(original_case.business_no) - replacement = ShippingCase( - case_no=generate_shipping_case_no(), + old_business_no = str(original.business_no) + now = datetime.utcnow() + customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() + replacement = ShippingNotice( + task_no=generate_task_no(), + user_id=original.user_id, + conversation_id=original.conversation_id, + source_type=original.source_type, + source_file_name=original.source_file_name, + source_file_type=original.source_file_type, + source_content_hash=original.source_content_hash, + source_asset_id=original.source_asset_id, + source_intake_id=original.source_intake_id, + source_candidate_id=original.source_candidate_id, + order_task_id=original.order_task_id, + business_fingerprint=original.business_fingerprint, + fingerprint_version=original.fingerprint_version, + content_fingerprint=original.content_fingerprint, + content_fingerprint_version=original.content_fingerprint_version, + document_version=int(original.document_version or 1) + 1, + supersedes_task_id=original.id, + raw_content=original.raw_content, customer_id=customer.id, customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, - numbering_status="pending", - status="open", - replaces_case_id=original_case.id, - created_by_id=actor_id, + customer_resolution_status="confirmed", + customer_resolution_method="admin_correction", + customer_identity_fingerprint=customer_fingerprint, + customer_confirmed_by=actor_id, + customer_confirmed_at=now, ) db.session.add(replacement) db.session.flush() - new_business_no = assign_business_number(replacement) - - original_case.status = "voided" - original_case.numbering_status = "voided" - now = datetime.utcnow() - customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() - latest = max(versions, key=lambda item: (int(item.document_version or 1), int(item.id))) - for version in versions: - version.shipping_case_id = replacement.id - version.customer_resolution_status = "confirmed" - version.customer_resolution_method = "admin_correction" - version.customer_identity_fingerprint = customer_fingerprint - version.customer_confirmed_by = actor_id - version.customer_confirmed_at = now - db.session.add(ShippingTaskEvent( - task_id=version.id, - event_type="customer_correction_applied", - detail_json={ - "old_case_id": original_case.id, - "new_case_id": replacement.id, - "old_business_no": old_business_no, - "new_business_no": new_business_no, - "old_customer_id": original_case.customer_id, - "new_customer_id": customer.id, - "reason": correction_reason, - "actor_id": actor_id, - }, - )) + new_business_no = assign_notice_business_number(replacement) + original.lifecycle_status = 'voided' + original.voided_at = now + original.voided_by_id = actor_id + original.void_reason = f'customer_correction:{correction_reason}' + correction_detail = { + "old_notice_id": original.id, + "new_notice_id": replacement.id, + "old_business_no": old_business_no, + "new_business_no": new_business_no, + "old_customer_id": original.customer_id, + "new_customer_id": customer.id, + "reason": correction_reason, + "actor_id": actor_id, + } + db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail)) + db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail)) # 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。 - latest.inventory_source_code = None - latest.inventory_connector_type = None - latest.inventory_warehouse_id = None - latest.inventory_source_status = None - latest.inventory_source_method = None - latest.inventory_source_confirmed_by = None - latest.inventory_source_confirmed_at = None - latest.inventory_source_config_version = None - latest.inventory_routing_fingerprint = None - latest.inventory_rpa_consumed_run_no = None - latest.inventory_snapshot_id = None - latest.inventory_lines_json = None - latest.match_status = None - latest.shortage_json = None - latest.line_results_json = None - latest.export_file_path = None - latest.export_file_name = None - latest.freight_ref_no = None - latest.upload_status = None - latest.upload_mode = None - latest.upload_attempt = 0 - latest.upload_started_at = None - latest.upload_finished_at = None - latest.upload_error_code = None - latest.upload_error_message = None - latest.upload_receipt_json = None - latest.idempotency_key = None - latest.current_step = None - latest.review_status = None - latest.pending_human_reason = None - latest.error_message = None db.session.commit() return { - "task_no": latest.task_no, - "old_case_id": original_case.id, - "new_case_id": replacement.id, + "task_no": replacement.task_no, + "old_notice_id": original.id, + "new_notice_id": replacement.id, "old_business_no": old_business_no, "new_business_no": new_business_no, "customer_id": customer.id, - "affected_task_count": len(versions), + "affected_task_count": 1, } diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py index ff57ed42..ea193393 100644 --- a/backend/app/services/shipping_notice/customer_identity_gate.py +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -16,21 +16,17 @@ from sqlalchemy import or_ from app import db from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError -from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent from app.services.shipping_notice.customer_normalization import clean_text -from app.services.shipping_notice.business_numbering_service import assign_business_number CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' def customer_identity_is_confirmed(task: ShippingNotice) -> bool: - """判断任务是否已关联业务单并通过标准客户确认。""" - if task.shipping_case_id is None: + """判断 Notice 自身是否已通过标准客户确认。""" + if task.customer_id is None: return False - case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id)) - if case is None or case.customer_id is None: - return False - customer = db.session.get(ShippingCustomer, int(case.customer_id)) + customer = db.session.get(ShippingCustomer, int(task.customer_id)) return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed') @@ -46,9 +42,6 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con """ if customer_identity_is_confirmed(task): return - case = task.shipping_case or ( - db.session.get(ShippingCase, int(task.shipping_case_id)) if task.shipping_case_id else None - ) raise AppError( code=CUSTOMER_GATE_ERROR_CODE, message='标准客户尚未确认,无法继续后续流程', @@ -56,9 +49,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con details={ 'operation': operation, 'task_no': task.task_no, - 'shipping_case_id': task.shipping_case_id, 'customer_resolution_status': task.customer_resolution_status or 'pending', - 'customer_id': case.customer_id if case else None, + 'customer_id': task.customer_id, }, ) @@ -87,10 +79,10 @@ def confirm_task_customer( commit: bool = True, ) -> ShippingNotice: """ - 人工确认任务所属标准客户,并同步共享业务单下所有任务版本。 + 人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。 - 核心逻辑:锁定业务单 → 校验启用客户 → 原子分配业务号 → 同步 revision 任务确认状态和事件。 - 客户确认与编号同事务提交,任何一步失败都不留下半确认状态。 + 核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。 + 客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。 Args: task: 待确认客户的任务。 @@ -99,19 +91,14 @@ def confirm_task_customer( resolution_method: manual/auto_rule 等审计方法。 commit: 是否提交事务;批次编排传 False 由外层统一提交。 """ - if task.shipping_case_id is None: - raise ConflictError( - 'Shipping task is missing its required shipping case', - code='SHIPPING.CUSTOMER_CASE_REQUIRED', - ) - case = ( - db.session.query(ShippingCase) - .filter(ShippingCase.id == int(task.shipping_case_id)) - .with_for_update() - .one_or_none() + task = ( + db.session.query(ShippingNotice) + .filter(ShippingNotice.id == int(task.id)) + # ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN; + # PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。 + .with_for_update(of=ShippingNotice) + .one() ) - if case is None: - raise NotFoundError('Shipping case not found', code='SHIPPING.CASE_NOT_FOUND') customer = db.session.get(ShippingCustomer, int(customer_id)) if customer is None: raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') @@ -119,50 +106,35 @@ def confirm_task_customer( raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED') if customer.status != 'active': raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') - if case.business_no and case.customer_id not in {None, customer.id}: + if task.business_no and task.customer_id not in {None, customer.id}: raise ConflictError( - 'Numbered shipping case customer cannot be changed silently', - code='SHIPPING.CUSTOMER_NUMBERED_CASE_LOCKED', + 'Numbered shipping notice customer cannot be changed silently', + code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED', ) now = datetime.utcnow() - previous_customer_id = case.customer_id - number_was_assigned = bool(case.business_no) - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - business_no = assign_business_number(case) + previous_customer_id = task.customer_id + task.customer_id = customer.id + task.customer_name_snapshot = customer.standard_name + task.customer_short_code_snapshot = customer.short_code fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest() - tasks = db.session.query(ShippingNotice).filter_by(shipping_case_id=case.id).all() - for version in tasks: - version.customer_resolution_status = 'confirmed' - version.customer_resolution_method = resolution_method - version.customer_identity_fingerprint = fingerprint - version.customer_confirmed_by = actor_id - version.customer_confirmed_at = now - db.session.add(ShippingTaskEvent( - task_id=version.id, - event_type='customer_confirmed', - detail_json={ - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'previous_customer_id': previous_customer_id, - 'method': resolution_method, - 'business_no': business_no, - }, - )) - if not number_was_assigned: - db.session.add(ShippingTaskEvent( - task_id=version.id, - event_type='business_number_assigned', - detail_json={ - 'business_no': business_no, - 'business_date': case.business_date.isoformat() if case.business_date else None, - 'sequence_value': case.sequence_value, - 'numbering_rule_version': case.numbering_rule_version, - }, - )) + task.customer_resolution_status = 'confirmed' + task.customer_resolution_method = resolution_method + task.customer_identity_fingerprint = fingerprint + task.customer_confirmed_by = actor_id + task.customer_confirmed_at = now + db.session.add(ShippingTaskEvent( + task_id=task.id, + event_type='customer_confirmed', + detail_json={ + 'customer_id': customer.id, + 'standard_name': customer.standard_name, + 'short_code': customer.short_code, + 'previous_customer_id': previous_customer_id, + 'method': resolution_method, + 'business_no': task.business_no, + }, + )) if commit: db.session.commit() return db.session.get(ShippingNotice, int(task.id)) diff --git a/backend/app/services/shipping_notice/customer_shadow_resolution.py b/backend/app/services/shipping_notice/customer_shadow_resolution.py index 3d8bee67..f20e7c0d 100644 --- a/backend/app/services/shipping_notice/customer_shadow_resolution.py +++ b/backend/app/services/shipping_notice/customer_shadow_resolution.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py 用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。 依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。 -逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingNotice 或业务编号。 +逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingNotice 或业务编号。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py b/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py deleted file mode 100644 index 130cdeb5..00000000 --- a/backend/app/services/shipping_notice/document_layout/coordinate_region_source_adapter.py +++ /dev/null @@ -1,231 +0,0 @@ -""" -services/shipping_notice/document_layout/coordinate_region_source_adapter.py - -用途:CoordinateRegionSourceAdapter——将 Profile.named_regions 圈选的物理区域映射为 - 可直接送入 Split Core 的区域原文 + 可引用 bbox 证据(page_no + 绝对坐标)。 -依赖:profile_vendor_comments_contract.NamedRegion;coordinate_region_text.read_coordinate_region_text - 与 visual_glyph_rows + positioned_token_spans(证据粒度生成)。 -逻辑:不读 MinIO、不查 DB;只接收 caller 已加载的 glyphs/page 字典;严格按 Q14 约定 - page_scope 规则选择「代表页」——last_page 时从多页集合取末页;失败不抛错,统一 - 返回 status=unavailable + 诊断码,供上游 ProfileFieldSourceMappingService 分支处理。 -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any, Literal - -from app.services.shipping_notice.document_layout.coordinate_region_text import ( - positioned_token_spans, - read_coordinate_region_text, -) -from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( - NamedRegion, -) - - -@dataclass -class CoordinateRegionEvidence: - """单个命中的 token 级证据——供 Observation.evidence_metadata_json 直接序列化。""" - - page_no: int - text: str - x0: float # 0..1 归一化 - x1: float - y0: float - y1: float - - -@dataclass -class CoordinateRegionSourceResult: - """区域抽取结果——对齐 Split Core 结果形状但不做拆分,仅负责原文渲染。""" - - region_id: str - label: str - status: Literal['available', 'unavailable'] - page_no: int | None = None - raw_text: str = '' - lines: list[str] = field(default_factory=list) - evidence_tokens: list[CoordinateRegionEvidence] = field(default_factory=list) - diagnostic_code: str | None = None - diagnostic_message: str | None = None - - -class CoordinateRegionSourceAdapter: - """ - 将 NamedRegion → 原文 + 证据的薄适配器。 - - 【AI 触发时机】:三来源收集阶段,上游遍历 field_source_mappings[].vendor_comments_enabled - 条目并引用命名区域 ID 时调用。 - - 核心逻辑: - [STEP 1] 按 page_scope 从 page_glyphs_map 中选「代表页」: - first_page → pages[0];last_page → pages[-1];all_pages 只看 p0(仅用于区域); - exact_page → 严格匹配 1-based page_no。 - [STEP 2] 调 read_coordinate_region_text 取区域原文(0..1 归一化坐标)。 - [STEP 3] 调 positioned_token_spans 生成 token 级 bbox 证据,用于 Review 高亮点位。 - [STEP 4] 原文按换行拆为 lines,供后续 execute_base_split_rule_set(..., lines=) 复用。 - - Args: - region: NamedRegion 契约对象(已通过 validate_assignment 校验)。 - page_glyphs_map: {1-based_page_no: {'glyphs': [...], 'page': {'width','height'}}} —— - caller 负责按当前 Document 加载,本类无网络 IO。 - """ - - def __init__(self, region: NamedRegion, page_glyphs_map: dict[int, dict[str, Any]]): - self.region = region - self.page_glyphs_map = page_glyphs_map - - # ------------------------------------------------------------------ - # 对外入口 - # ------------------------------------------------------------------ - - def extract(self) -> CoordinateRegionSourceResult: - """ - 执行区域抽取。失败不抛异常,统一置 status=unavailable + 稳定诊断码。 - - Returns: - CoordinateRegionSourceResult,上游据此决定是否跳过 Vendor Comments 来源。 - """ - # [STEP 1] 选择代表页 - page_no = self._resolve_representative_page_no() - if page_no is None: - return CoordinateRegionSourceResult( - region_id=self.region.region_id, - label=self.region.label, - status='unavailable', - diagnostic_code='named_region_page_not_found', - diagnostic_message=( - f'named region {self.region.region_id!r} page_scope={self.region.page_scope} ' - f'page_no={self.region.page_no!r} has no loaded page' - ), - ) - page_bundle = self.page_glyphs_map[page_no] - glyphs = list(page_bundle.get('glyphs') or []) - page = dict(page_bundle.get('page') or {}) - if not glyphs or 'width' not in page or 'height' not in page: - return CoordinateRegionSourceResult( - region_id=self.region.region_id, - label=self.region.label, - status='unavailable', - page_no=page_no, - diagnostic_code='named_region_empty_glyphs', - diagnostic_message='region target page has empty glyphs or missing page size', - ) - - region_coords = { - 'x0': self.region.region.x0, 'y0': self.region.region.y0, - 'x1': self.region.region.x1, 'y1': self.region.region.y1, - } - - # [STEP 2] 渲染区域原文 - raw_text = read_coordinate_region_text( - glyphs=glyphs, page=page, region=region_coords, - ) - if not raw_text.strip(): - return CoordinateRegionSourceResult( - region_id=self.region.region_id, - label=self.region.label, - status='unavailable', - page_no=page_no, - diagnostic_code='named_region_text_empty', - diagnostic_message=f'named region {self.region.region_id!r} has empty body text', - ) - - # [STEP 3] 生成 token 级证据(只保留区域中心在 box 内的 token) - tokens = self._collect_region_evidence_tokens( - glyphs=glyphs, page=page, region_coords=region_coords, page_no=page_no, - ) - - # [STEP 4] 拆行 - lines = [ln.strip() for ln in raw_text.splitlines() if ln.strip()] - - return CoordinateRegionSourceResult( - region_id=self.region.region_id, - label=self.region.label, - status='available', - page_no=page_no, - raw_text=raw_text.strip(), - lines=lines, - evidence_tokens=tokens, - ) - - # ------------------------------------------------------------------ - # 内部帮助 - # ------------------------------------------------------------------ - - def _resolve_representative_page_no(self) -> int | None: - """按 page_scope 规则选择代表页。""" - sorted_pages = sorted(self.page_glyphs_map.keys()) - if not sorted_pages: - return None - scope = self.region.page_scope - if scope == 'first_page': - return sorted_pages[0] - if scope == 'last_page': - return sorted_pages[-1] - if scope == 'all_pages': - # all_pages 的命名区域仅在第一页渲染(常见全页 Header); - # 若管理员要取多页块,应拆为多个命名区域并使用 exact_page。 - return sorted_pages[0] - if scope == 'exact_page': - return self.region.page_no if self.region.page_no in self.page_glyphs_map else None - return None - - @staticmethod - def _collect_region_evidence_tokens( - *, - glyphs: list[dict[str, Any]], - page: dict[str, Any], - region_coords: dict[str, float], - page_no: int, - ) -> list[CoordinateRegionEvidence]: - """筛选命名区域中心范围内的 token,并返回 0..1 归一化 bbox。""" - width, height = float(page['width']), float(page['height']) - rx0, ry0, rx1, ry1 = (region_coords[k] for k in ('x0', 'y0', 'x1', 'y1')) - all_spans = positioned_token_spans(glyphs, respect_explicit_spaces=True) - selected: list[CoordinateRegionEvidence] = [] - for span in all_spans: - sx0 = float(span['x0']) / width - sx1 = float(span['x1']) / width - text = str(span.get('text') or '') - # y 边界:span 只返回横向边界;glyphs 中心用于 y 判定 - # positioned_token_spans 不返回 y,重算 y0/y1 需回溯原 glyph——这里直接用 - # glyphs 子集重算以保证引用不泄漏。 - matched = [ - g for g in glyphs - if _glyph_intersects_span(g, span, width) and _glyph_in_region_center(g, width, height, rx0, ry0, rx1, ry1) - ] - if not matched: - continue - min_y0 = min(float(g['bbox']['y0']) / height for g in matched) - max_y1 = max(float(g['bbox']['y1']) / height for g in matched) - selected.append(CoordinateRegionEvidence( - page_no=page_no, - text=text, - x0=sx0, x1=sx1, - y0=min_y0, y1=max_y1, - )) - return selected - - -def _glyph_intersects_span(glyph: dict[str, Any], span: dict[str, Any], width: float) -> bool: - try: - gx0 = float(glyph['bbox']['x0']) / width - gx1 = float(glyph['bbox']['x1']) / width - except (KeyError, TypeError, ValueError): - return False - return min(gx1, float(span['x1']) / width) > max(gx0, float(span['x0']) / width) - - -def _glyph_in_region_center( - glyph: dict[str, Any], width: float, height: float, - rx0: float, ry0: float, rx1: float, ry1: float, -) -> bool: - try: - b = glyph['bbox'] - cx = (float(b['x0']) + float(b['x1'])) / (2 * width) - cy = (float(b['y0']) + float(b['y1'])) / (2 * height) - except (KeyError, TypeError, ValueError): - return False - return rx0 <= cx <= rx1 and ry0 <= cy <= ry1 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 9f70279e..e6fc1a96 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 @@ -22,6 +22,7 @@ from app.services.shipping_notice.document_layout.coordinate_transform import ( 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 +from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value from app.services.shipping_notice.reservation_id import validated_reservation_id @@ -31,6 +32,186 @@ _DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE) DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no' +def reconstruction_exclusion_regions( + table_region: dict[str, Any], *, include_header_layouts: bool = False, +) -> list[dict[str, Any]]: + """返回明细重建的显式普通排除区;表头框只保留作语义和预览证据。""" + exclusions = [ + dict(item) for item in (table_region.get('exclusion_regions') or []) + if isinstance(item, dict) + ] + if include_header_layouts: + exclusions.extend( + dict(item['region']) + for item in (table_region.get('header_layouts') or []) + if isinstance(item, dict) and isinstance(item.get('region'), dict) + ) + return exclusions + + +def coordinate_profile_character_candidates( + *, + table_region: dict[str, Any], + reference_page_frame: dict[str, Any] | None = None, + page_size: dict[str, Any], + page_characters: list[dict[str, Any]] | None, + table_characters: list[dict[str, Any]] | None, + raw_table_bbox: dict[str, Any] | None = None, + table_id: str | None = None, + page_no: int = 1, + coordinate_transform: dict[str, Any] | None = None, + allow_table_fallback: bool = True, +) -> tuple[list[dict[str, Any]] | None, dict[str, float] | None]: + """按统一契约选择当前表区字符:整页证据优先,真实表框仅扩展纵向范围。 + + 模板区域的横向边界始终有效;真实物理表的纵向边界用于覆盖跨行表框。 + 缺少整页证据时仅回退到该表的冻结字符,不把其它页面或其它表带入。 + """ + try: + page_bbox = { + 'x0': 0.0, 'y0': 0.0, + 'x1': float(page_size['width']), 'y1': float(page_size['height']), + } + except (KeyError, TypeError, ValueError): + return None, None + if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0: + return None, None + projected = apply_coordinate_transform_to_region( + table_region, coordinate_transform=coordinate_transform, + ) + if projected is None: + return None, page_bbox + try: + reference_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_bbox['x1'] + reference_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_bbox['y1'] + except (KeyError, TypeError, ValueError): + return None, page_bbox + if reference_width <= 0 or reference_height <= 0: + return None, page_bbox + region_bbox = { + 'x0': projected['x0'] * reference_width, 'y0': projected['y0'] * reference_height, + 'x1': projected['x1'] * reference_width, 'y1': projected['y1'] * reference_height, + } + is_virtual_page = str(table_id or '') == f'page-{int(page_no)}' + if not is_virtual_page and isinstance(raw_table_bbox, dict): + try: + if not ( + float(raw_table_bbox['x0']) < region_bbox['x1'] + and float(raw_table_bbox['x1']) > region_bbox['x0'] + and float(raw_table_bbox['y0']) < region_bbox['y1'] + and float(raw_table_bbox['y1']) > region_bbox['y0'] + ): + return None, page_bbox + evidence_bbox = dict(region_bbox) + evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_table_bbox['y0'])) + evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_table_bbox['y1'])) + except (KeyError, TypeError, ValueError): + return None, page_bbox + else: + evidence_bbox = region_bbox + if isinstance(page_characters, list): + page_candidates = [ + item for item in page_characters + if isinstance(item, dict) and _character_center_in_region(item, evidence_bbox) + ] + # 页级快照可能只包含订单头或被上游裁剪过;空的页级候选不能遮蔽 + # 当前物理表仍然有效的冻结字符证据。 + if page_candidates: + return page_candidates, page_bbox + if allow_table_fallback and isinstance(table_characters, list): + return table_characters, page_bbox + return None, page_bbox + + +def _character_center_in_region(character: dict[str, Any], region: dict[str, float]) -> bool: + """判断字符中心点是否落入绝对坐标区域。""" + bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None + if bbox is None: + return False + try: + center_x = (float(bbox['x0']) + float(bbox['x1'])) / 2 + center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2 + except (KeyError, TypeError, ValueError): + return False + return region['x0'] <= center_x <= region['x1'] and region['y0'] <= center_y <= region['y1'] + + +def reconstruct_coordinate_profile_rows_with_strategy( + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox | dict[str, Any], + line_layouts: list[dict[str, Any]], + table_region: dict[str, Any] | None = None, + termination_rules: list[dict[str, Any]] | None = None, + exclusion_regions: list[dict[str, Any]] | None = None, + dynamic_exclusion_regions: list[dict[str, Any]] | None = None, + line_start_field_code: str | None = None, + include_deleted: bool = False, + schema_field_metadata: list[dict[str, Any]] | None = None, + initial_fields: dict[str, str] | None = None, + initial_next_offset: int = 0, + coordinate_transform: dict[str, Any] | None = None, + page_no: int = 1, +) -> tuple[list['CoordinateProfileLogicalRow'], Any]: + """统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。""" + from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( + resolve_runtime_parse_strategy, + ) + + fixed_rows = reconstruct_coordinate_profile_rows( + characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, + table_region=table_region, termination_rules=termination_rules, + exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code, + include_deleted=include_deleted, row_reconstruction_mode='fixed_subrows', + schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, + initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform, + ) + adaptive_rows = reconstruct_coordinate_profile_rows( + characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, + table_region=table_region, termination_rules=termination_rules, + exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code, + include_deleted=include_deleted, row_reconstruction_mode='adaptive_record_columns', + schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, + initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform, + ) + dynamic_rows = reconstruct_coordinate_profile_rows( + characters=characters, table_bbox=table_bbox, line_layouts=line_layouts, + table_region=table_region, termination_rules=termination_rules, + exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code, + include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns', + schema_field_metadata=schema_field_metadata, initial_fields=initial_fields, + initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform, + ) + + def strategy_rows(rows: list[CoordinateProfileLogicalRow]) -> list[dict[str, Any]]: + return [ + { + 'status': 'parsed' if not row.issues else 'needs_review', + 'issues': list(row.issues), + 'fields': [ + {'field_code': code, 'value': value} + for code, value in row.fields.items() + ], + } + for row in rows + ] + + strategy = resolve_runtime_parse_strategy( + page_glyphs={str(page_no): characters}, + fixed_rows=strategy_rows(fixed_rows), + adaptive_rows=strategy_rows(adaptive_rows), + dynamic_rows=strategy_rows(dynamic_rows), + ) + if strategy.status != 'selected' or strategy.row_mode is None: + return [], strategy + return ( + fixed_rows if strategy.row_mode == 'fixed_subrows' + else adaptive_rows if strategy.row_mode == 'adaptive_record_columns' + else dynamic_rows, + strategy, + ) + + def resolve_line_start_field_code(value: Any = None) -> str: """ 规范化模板起行锚点字段编码。 @@ -60,6 +241,59 @@ def is_valid_line_start_value(raw: Any) -> bool: return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text)) +def _is_record_start( + values: dict[str, str], + fields: list[dict[str, Any]], + line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> bool: + """用冻结 Schema 的字段类型/校验结果确认明细起行,不依赖业务字段名或列序。""" + if schema_fields is None: + start_value = values.get(line_start_field_code, '') + return is_valid_line_start_value(start_value) + start_field_configured = any( + str(field.get('field_code') or '') == line_start_field_code for field in fields + ) + start_value = values.get(line_start_field_code, '') + def schema_valid(code: str, raw: str) -> bool: + config = schema_fields.get(code) + if not config or not str(raw or '').strip(): + return False + try: + normalized = normalize_order_field_value(raw, config) + except Exception: + return False + return normalized not in (None, '') and validate_order_field_value(normalized, config) + + # 起行字段的 Schema 类型只负责保留/解析值;它被模板配置为起行锚点后, + # 还必须满足通用行号形态,避免 string 字段把表头文本(如 ``0rd``/``B``) + # 当成明细起点。该规则只作用于配置的锚点,不依赖任何业务字段名。 + has_start_anchor = ( + is_valid_line_start_value(start_value) + and schema_valid(line_start_field_code, start_value) + ) + corroborating = sum( + 1 for field in fields + if (code := str(field.get('field_code') or '')) + and code != line_start_field_code + and schema_valid(code, values.get(code, '')) + ) + configured_corroborating_fields = sum( + 1 for field in fields + if (code := str(field.get('field_code') or '')) + and code != line_start_field_code + and code in schema_fields + ) + if has_start_anchor: + # 若模板只绑定起行字段,Schema 没有第二个坐标字段可供交叉验证, + # 允许该锚点单独起行;一旦存在其它已绑定字段,必须有至少一个有效值。 + return corroborating >= 1 or configured_corroborating_fields == 0 + # A profile that explicitly configures a start field must not silently fall back + # to unrelated fields when that anchor is absent. Profiles without such a field + # may use a position-independent two-field business signature. + return not start_field_configured and corroborating >= 2 + + class CoordinateReconstructionModel(BaseModel): """为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。""" @@ -272,8 +506,9 @@ def reconstruct_coordinate_profile_rows( include_deleted: bool = False, line_start_field_code: str | None = None, include_unanchored_rows: bool = False, - row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows', + row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows', coordinate_transform: dict[str, Any] | None = None, + schema_field_metadata: list[dict[str, Any]] | None = None, ) -> list[CoordinateProfileLogicalRow]: """ 按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。 @@ -301,6 +536,16 @@ def reconstruct_coordinate_profile_rows( termination_rules = projected['termination_rules'] exclusion_regions = projected['exclusion_regions'] start_field_code = resolve_line_start_field_code(line_start_field_code) + schema_fields = { + str(item.get('field_code') or ''): item + for item in (schema_field_metadata or []) + if ( + isinstance(item, dict) + and item.get('field_code') + and item.get('enabled', True) + and str(item.get('scope') or '') == 'line' + ) + } if schema_field_metadata is not None else None bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox) ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1)) if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))): @@ -322,6 +567,11 @@ def reconstruct_coordinate_profile_rows( _absolute_relative_region(bbox, item) for item in (exclusion_regions or []) if isinstance(item, dict) ] + # 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其 + # “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions, + # 从而保留管理员配置的普通排除区。 + if row_reconstruction_mode == 'dynamic_x_columns': + exclusions = [] # [STEP 1] 删除文字不是全局业务规则;只有管理员用排除区显式圈定后才授权删除上一条明细。 marker_indices: set[int] = set() authorized_marker_indices: set[int] = set() @@ -353,6 +603,16 @@ def reconstruct_coordinate_profile_rows( # This mode is opt-in per table region. It supports documents whose stable # columns stay put while optional descriptions move values across visual rows. + if row_reconstruction_mode == 'dynamic_x_columns': + return _reconstruct_dynamic_x_columns_profile_rows( + glyphs=glyphs, + table_bbox=bbox, + ordered_layouts=ordered_layouts, + termination_rules=termination_rules or [], + include_deleted=include_deleted, + line_start_field_code=start_field_code, + schema_fields=schema_fields, + ) if row_reconstruction_mode == 'adaptive_record_columns': return _reconstruct_adaptive_record_columns_profile_rows( glyphs=glyphs, @@ -361,6 +621,7 @@ def reconstruct_coordinate_profile_rows( termination_rules=termination_rules or [], include_deleted=include_deleted, line_start_field_code=start_field_code, + schema_fields=schema_fields, ) relative_y_rows = _reconstruct_relative_y_profile_rows( @@ -372,6 +633,7 @@ def reconstruct_coordinate_profile_rows( include_deleted=include_deleted, line_start_field_code=start_field_code, include_unanchored_rows=include_unanchored_rows, + schema_fields=schema_fields, ) if relative_y_rows is not None: return relative_y_rows @@ -434,7 +696,7 @@ def reconstruct_coordinate_profile_rows( flush(role='deleted') continue main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0]) - if is_valid_line_start_value(main_values.get(start_field_code, '')): + if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code, schema_fields): flush() current, current_evidence = main_values, main_evidence sources, next_offset, current_issues = [row_index], 1, main_issues @@ -553,6 +815,7 @@ def _reconstruct_adaptive_record_columns_profile_rows( termination_rules: list[dict[str, Any]], include_deleted: bool, line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, ) -> list[CoordinateProfileLogicalRow]: """按起行锚点分段,并在每段内用字段列及格式读取可变视觉子行。""" main_fields = ordered_layouts[0].get('field_regions') or [] @@ -583,6 +846,7 @@ def _reconstruct_adaptive_record_columns_profile_rows( main_fields=main_fields, table_bbox=table_bbox, line_start_field_code=line_start_field_code, + schema_fields=schema_fields, ) ] results: list[CoordinateProfileLogicalRow] = [] @@ -597,6 +861,17 @@ def _reconstruct_adaptive_record_columns_profile_rows( for field in fields: code = str(field['field_code']) region = _absolute_relative_region(table_bbox, field['region']) + # 自适应列模式只能为单视觉 band 选择候选。若 Schema 绑定的 + # 字段框明确跨越多个 band(如换行客户料号),该模式的单 band + # 候选必然不完整,必须交给 fixed 几何重建处理。 + if schema_fields is not None: + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + if len(intersecting) > 1: + issues.append(f'coordinate_profile_field_band_ambiguous:{code}') + continue candidates: list[tuple[float, int, dict[str, str]]] = [] for band_index, (_, band) in enumerate(record): raw = _adaptive_field_raw(band=band, region=region, field_code=code) @@ -629,7 +904,7 @@ def _reconstruct_adaptive_record_columns_profile_rows( issues.append(f'coordinate_profile_composite_conflict:{extracted_code}') else: values[extracted_code] = extracted_value - if is_valid_line_start_value(values.get(line_start_field_code, '')): + if _is_record_start(values, main_fields, line_start_field_code, schema_fields): results.append(CoordinateProfileLogicalRow( fields=values, source_row_indices=[row_index for row_index, _ in record], @@ -639,6 +914,87 @@ def _reconstruct_adaptive_record_columns_profile_rows( return results if include_deleted else [row for row in results if row.role != 'deleted'] +def _reconstruct_dynamic_x_columns_profile_rows( + *, + glyphs: list[tuple[int, PositionedCharacter]], + table_bbox: LayoutBBox, + ordered_layouts: list[dict[str, Any]], + termination_rules: list[dict[str, Any]], + include_deleted: bool, + line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, +) -> list[CoordinateProfileLogicalRow]: + """按每条记录的有效起行锚点平移完整字段框,恢复稳定 X、漂移 Y 的明细。""" + main_fields = ordered_layouts[0].get('field_regions') or [] + start_field = next( + (item for item in main_fields if isinstance(item, dict) and item.get('field_code') == line_start_field_code), + None, + ) + if not isinstance(start_field, dict) or not isinstance(start_field.get('region'), dict): + return [] + fields = [ + field for layout in ordered_layouts for field in (layout.get('field_regions') or []) + if isinstance(field, dict) and isinstance(field.get('region'), dict) and field.get('field_code') + ] + bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = [] + for row_index, band in enumerate(_group_visual_rows(glyphs)): + text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip() + if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules): + break + bands.append((row_index, band)) + start_region = _absolute_relative_region(table_bbox, start_field['region']) + anchors = [ + index for index, (_row_index, band) in enumerate(bands) + if _is_adaptive_record_start( + band=band, start_region=start_region, main_fields=main_fields, + table_bbox=table_bbox, line_start_field_code=line_start_field_code, + schema_fields=schema_fields, + ) + ] + results: list[CoordinateProfileLogicalRow] = [] + expected_anchor_center = (start_region.y0 + start_region.y1) / 2 + for anchor_index, start in enumerate(anchors): + end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(bands) + record = bands[start:end] + anchor_box = _band_bbox(record[0][1]) + delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center + values: dict[str, str] = {} + issues: list[str] = [] + for field in fields: + code = str(field['field_code']) + saved = _absolute_relative_region(table_bbox, field['region']) + region = LayoutBBox( + x0=saved.x0, y0=saved.y0 + delta_y, + x1=saved.x1, y1=saved.y1 + delta_y, + ) + selected_bands = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + raw = _text_in_multiline_region( + selected_bands, region, + compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, + ) + if not raw: + continue + extracted = extract_profile_field_value( + extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw, + ) + for extracted_code, extracted_value in extracted.items(): + previous = values.get(extracted_code) + if previous is not None and previous != extracted_value: + issues.append(f'coordinate_profile_composite_conflict:{extracted_code}') + else: + values[extracted_code] = extracted_value + if _is_record_start(values, main_fields, line_start_field_code, schema_fields): + results.append(CoordinateProfileLogicalRow( + fields=values, + source_row_indices=[row_index for row_index, _band in record], + role='data', issues=issues, + )) + return results if include_deleted else [row for row in results if row.role != 'deleted'] + + def _adaptive_field_raw( *, band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, field_code: str, ) -> str: @@ -656,22 +1012,43 @@ def _adaptive_field_raw( def _is_adaptive_record_start( *, band: list[tuple[int, PositionedCharacter]], start_region: LayoutBBox, main_fields: list[dict[str, Any]], table_bbox: LayoutBBox, line_start_field_code: str, + schema_fields: dict[str, dict[str, Any]] | None = None, ) -> bool: - """要求起行号及同一主行的其他绑定字段共同成立,排除页眉、地址中的孤立数字。""" - if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)): - return False - evidence_fields = [ - item for item in main_fields - if item.get('field_code') != line_start_field_code and item.get('field_code') in { - 'part_number', 'customer_part_number', 'aws_part_number', - } - ] - return all( - _is_compact_identifier( - _text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region'])) + """按当前主视觉行的 Schema 字段值判断起行,不依赖业务字段名。""" + if schema_fields is None: + if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)): + return False + # 低层旧调用未提供 Schema 时仍使用通用文本形态交叉验证, + # 但不再按业务字段名建立白名单。 + evidence_fields = [ + item for item in main_fields + if isinstance(item, dict) + and item.get('field_code') != line_start_field_code + and isinstance(item.get('region'), dict) + ] + return all( + _is_compact_identifier( + _text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region'])) + ) + for field in evidence_fields ) - for field in evidence_fields - ) + values: dict[str, str] = {} + for field in main_fields: + if not isinstance(field, dict) or not isinstance(field.get('region'), dict): + continue + code = str(field.get('field_code') or '') + if not code or code not in schema_fields: + continue + raw = _adaptive_field_raw( + band=band, + region=_absolute_relative_region(table_bbox, field['region']), + field_code=code, + ) + extracted = extract_profile_field_value( + extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw, + ) + values.update(extracted) + return _is_record_start(values, main_fields, line_start_field_code, schema_fields) def _is_compact_identifier(raw: str) -> bool: @@ -717,6 +1094,7 @@ def _reconstruct_relative_y_profile_rows( include_deleted: bool, line_start_field_code: str, include_unanchored_rows: bool, + schema_fields: dict[str, dict[str, Any]] | None = None, ) -> list[CoordinateProfileLogicalRow] | None: """ 将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。 @@ -741,6 +1119,18 @@ def _reconstruct_relative_y_profile_rows( ) if start_field is None: return None + + def values_for_band(band: list[tuple[int, PositionedCharacter]]) -> dict[str, str]: + values: dict[str, str] = {} + for field in fields: + code = str(field.get('field_code') or '') + region = _absolute_relative_region(table_bbox, field['region']) + raw = _text_in_horizontal_region(band, region) + extracted = extract_profile_field_value( + extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw, + ) + values.update(extracted) + return values bands = _group_visual_rows(glyphs) usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = [] for row_index, band in enumerate(bands): @@ -755,16 +1145,17 @@ def _reconstruct_relative_y_profile_rows( anchors: list[int] = [] for index, (_, band) in enumerate(usable_bands): start_text = _text_in_horizontal_region(band, start_region) - if is_valid_line_start_value(start_text): + if schema_fields is None and is_valid_line_start_value(start_text): anchors.append(index) + elif schema_fields is not None: + values = values_for_band(band) + if _is_record_start(values, fields, line_start_field_code, schema_fields): + anchors.append(index) if not anchors: return [] - sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands) - sample_record = usable_bands[anchors[0]:sample_end] - field_band_indices = _calibrate_field_band_indices( - fields=fields, sample_record=sample_record, table_bbox=table_bbox, - ) + start_region = _absolute_relative_region(table_bbox, start_field['region']) + expected_anchor_center = (start_region.y0 + start_region.y1) / 2 results: list[CoordinateProfileLogicalRow] = [] for anchor_index, start in enumerate(anchors): end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands) @@ -774,23 +1165,34 @@ def _reconstruct_relative_y_profile_rows( )) for _, band in record) values: dict[str, str] = {} issues: list[str] = [] - matched_bands, alignment_issues = _match_field_band_groups( - fields=fields, - record=record, - expected_indices=field_band_indices, - table_bbox=table_bbox, - line_start_field_code=line_start_field_code, - ) - issues.extend(alignment_issues) + anchor_box = _band_bbox(record[0][1]) + delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center for field in fields: code = str(field.get('field_code') or '') if not code: continue - band_index = matched_bands.get(id(field)) - if band_index is None: + saved = _absolute_relative_region(table_bbox, field['region']) + region = LayoutBBox( + x0=saved.x0, y0=saved.y0 + delta_y, + x1=saved.x1, y1=saved.y1 + delta_y, + ) + # A visual field box may intentionally span multiple PDF text lines + # (for example a wrapped customer part number). The previous + # one-band assignment treated that as an ambiguity and dropped the + # field, which caused two vertically stacked part-number fields to + # become empty or reuse the same prefix. When the configured field + # region intersects multiple bands, read all of its own glyphs; + # single-band fields retain the calibrated matching behavior. + intersecting = [ + band for _row_index, band in record + if _regions_overlap_vertically(region, _band_bbox(band)) + ] + if not intersecting: continue - region = _absolute_relative_region(table_bbox, field['region']) - raw = _text_in_horizontal_region(record[band_index][1], region) + raw = _text_in_multiline_region( + intersecting, region, + compact=code in {'part_number', 'customer_part_number', 'aws_part_number'}, + ) if not raw: continue extracted = extract_profile_field_value( @@ -802,7 +1204,7 @@ def _reconstruct_relative_y_profile_rows( issues.append(f'coordinate_profile_composite_conflict:{extracted_code}') else: values[extracted_code] = extracted_value - if is_valid_line_start_value(values.get(line_start_field_code, '')): + if _is_record_start(values, fields, line_start_field_code, schema_fields): results.append(CoordinateProfileLogicalRow( fields=values, source_row_indices=[row_index for row_index, _ in record], @@ -1202,7 +1604,7 @@ def reconstruct_multi_subrow_table( continue main_values = _band_field_values(band, anchors[0]) - if is_valid_line_start_value(main_values.get(start_field_code, '')): + if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code): flush() current_fields = main_values current_sources = [row_index] @@ -1370,13 +1772,17 @@ def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any]) def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool: - """仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。""" - return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1 + """按纵向中心和有效横向重叠收集字符,避免字段边界截断字形。""" + return ( + _inside_horizontal_region(glyph_bbox, region) + and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1 + ) def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool: - """仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。""" - return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 + """接受与字段框正向相交的字形,防止紧贴边界的料号标点被截断。""" + overlap = min(glyph_bbox.x1, region.x1) - max(glyph_bbox.x0, region.x0) + return overlap > 0 def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool: @@ -1499,6 +1905,26 @@ def _text_in_region( return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit) +def _regions_overlap_vertically(left: LayoutBBox, right: LayoutBBox) -> bool: + """判断字段框与视觉 band 是否有纵向证据交集。""" + return min(left.y1, right.y1) > max(left.y0, right.y0) + + +def _text_in_multiline_region( + bands: list[list[tuple[int, PositionedCharacter]]], + region: LayoutBBox, + *, + compact: bool = False, +) -> str: + """按视觉行顺序读取跨行字段,料号换行时去除行间空白。""" + lines: list[str] = [] + for band in sorted(bands, key=lambda item: _band_bbox(item).y0): + text = _text_in_region(band, region).strip() + if text: + lines.append(text) + return ('' if compact else ' ').join(lines) + + def _text_in_horizontal_region( band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, ) -> str: diff --git a/backend/app/services/shipping_notice/document_layout/lifecycle.py b/backend/app/services/shipping_notice/document_layout/lifecycle.py index 3755d50c..85265779 100644 --- a/backend/app/services/shipping_notice/document_layout/lifecycle.py +++ b/backend/app/services/shipping_notice/document_layout/lifecycle.py @@ -11,6 +11,7 @@ backend/app/services/shipping_notice/document_layout/lifecycle.py from __future__ import annotations import hashlib +import gzip import json import logging from datetime import datetime @@ -22,6 +23,7 @@ from sqlalchemy import and_, func, or_, update from app.extensions import db from app.models import ( + FileAsset, ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake, @@ -51,6 +53,81 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({ 'shipping_document_layout_candidate_glyphs_compacted', 'shipping_document_layout_candidate_page_metadata_compacted', }) +COORDINATE_EVIDENCE_REF_KEY = 'coordinate_evidence_ref' +COORDINATE_EVIDENCE_SCHEMA_VERSION = 'shipping_order_coordinate_evidence.v1' + + +def _coordinate_evidence_bytes(evidence: dict[str, Any]) -> bytes: + """将完整坐标证据以稳定 gzip JSON 编码,供不可变 FileAsset 保存。""" + raw = json.dumps(evidence, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8') + return gzip.compress(raw, compresslevel=6, mtime=0) + + +def _persist_coordinate_evidence_asset(*, document: ShippingOrderDocument, evidence: dict[str, Any]) -> dict[str, Any] | None: + """复用现有 FileAsset/MinIO 保存完整坐标证据并返回轻量引用。""" + tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + if not any(isinstance(value, list) and value for value in (*tables.values(), *page_glyphs.values())): + return None + from app.services.file_assets.service import create_derived_file_asset_from_bytes + + parent = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None + intake = db.session.get(ShippingOrderIntake, int(document.intake_id)) + user_id = getattr(intake, 'user_id', None) + if parent is None or user_id is None: + return None + data = _coordinate_evidence_bytes(evidence) + asset, created = create_derived_file_asset_from_bytes( + user_id=int(user_id), parent=parent, data=data, + filename=f'{document.id}-coordinate-evidence.json.gz', + mime_type='application/json+gzip', asset_role='layout_coordinate_evidence', + ) + asset.lifecycle_status = 'referenced' + asset.expires_at = None + asset.deleted_at = None + if created or int(asset.reference_count or 0) == 0: + asset.reference_count = max(int(asset.reference_count or 0), 1) + return { + 'asset_no': str(asset.asset_no), + 'checksum': hashlib.sha256(data).hexdigest(), + 'size': len(data), + 'schema_version': str(evidence.get('version') or COORDINATE_EVIDENCE_SCHEMA_VERSION), + } + + +def _has_coordinate_evidence(evidence: Any) -> bool: + """判断证据是否含有可外置的字符集合;空占位结构保持原快照兼容。""" + if not isinstance(evidence, dict): + return False + for key in ('tables', 'page_glyphs'): + values = evidence.get(key) + if isinstance(values, dict) and any(isinstance(item, list) and item for item in values.values()): + return True + return False + + +def _hydrate_coordinate_evidence(*, payload: dict[str, Any], document: ShippingOrderDocument) -> dict[str, Any]: + """从现有 FileAsset 引用加载完整坐标证据;读取失败时保持缺证据状态。""" + ref = payload.get(COORDINATE_EVIDENCE_REF_KEY) + if not isinstance(ref, dict): + return payload + asset_no = str(ref.get('asset_no') or '').strip() + if not asset_no: + return payload + asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).first() + if asset is None: + return payload + try: + from app.services.file_assets.service import read_asset_bytes + evidence = json.loads(gzip.decompress(read_asset_bytes(asset)).decode('utf-8')) + except Exception: + _LOGGER.exception('coordinate evidence asset load failed document_id=%s asset_no=%s', document.id, asset_no) + return payload + if _has_coordinate_evidence(evidence): + hydrated = dict(payload) + hydrated['coordinate_evidence'] = evidence + return hydrated + return payload def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool: @@ -61,10 +138,8 @@ def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: """ if Path(str(document.filename or '')).suffix.lower() != '.pdf': return True - evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {} - complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict) - recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict) - return complete or recoverable + ref = payload.get(COORDINATE_EVIDENCE_REF_KEY) + return isinstance(ref, dict) and bool(str(ref.get('asset_no') or '').strip()) def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool: @@ -207,14 +282,17 @@ def _fit_layout_payload_to_budget( def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None: """读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。""" - version = document.current_layout_version + version = ( + db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id)) + if document.current_layout_version_id else document.current_layout_version + ) if ( version is None or str(version.status or '') not in CURRENT_LAYOUT_STATUSES or not isinstance(version.payload_json, dict) ): return None - return dict(version.payload_json) + return _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document) def _bind_inline_xfa_structure_analysis( @@ -322,6 +400,16 @@ def record_inline_layout_snapshot( 超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。 """ payload = dict(snapshot) + evidence = payload.get('coordinate_evidence') + if _has_coordinate_evidence(evidence): + evidence_ref = _persist_coordinate_evidence_asset(document=document, evidence=evidence) + if evidence_ref is None and str(payload.get('status') or '') == 'ready': + payload = {**payload, 'status': 'failed', 'issues': [ + *list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed', + ]} + elif evidence_ref is not None: + payload.pop('coordinate_evidence', None) + payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref parser_key = str(parser_key or current_layout_parser_key()) max_bytes = max(int(current_app.config.get( 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, @@ -943,19 +1031,30 @@ def complete_layout_version( if version is None or version.status != 'running' or version.lease_token != lease_token: db.session.rollback() return False + payload = dict(snapshot) + evidence = payload.get('coordinate_evidence') + if _has_coordinate_evidence(evidence): + evidence_ref = _persist_coordinate_evidence_asset(document=version.document, evidence=evidence) + if evidence_ref is None and str(payload.get('status') or '') == 'ready': + payload = {**payload, 'status': 'failed', 'issues': [ + *list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed', + ]} + elif evidence_ref is not None: + payload.pop('coordinate_evidence', None) + payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref max_bytes = max(int(current_app.config.get( 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, )), 1) fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget( - snapshot, max_bytes=max_bytes, + payload, max_bytes=max_bytes, ) - stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot + stored_for_identity = fitted_snapshot if fitted_snapshot is not None else payload checksum, _ = canonical_layout_payload(stored_for_identity) - issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues)) - provider_status = str(snapshot.get('status') or 'failed') + issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues)) + provider_status = str(payload.get('status') or 'failed') status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed' if status == 'ready' and not _ready_layout_evidence_complete( - document=version.document, payload=snapshot, + document=version.document, payload=payload, ): status = 'failed' issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'}) @@ -967,12 +1066,12 @@ def complete_layout_version( status = 'failed' now = datetime.utcnow() version.status = status - version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None - version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32] + version.parser_version = str(payload.get('provider_version') or '')[:64] or None + version.backend = str(payload.get('backend') or LAYOUT_BACKEND)[:32] version.payload_json = stored_payload version.payload_checksum = checksum version.payload_size_bytes = payload_size - version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None + version.quality_json = dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None version.issues_json = sorted(set(issues)) version.lease_token = None version.finished_at = now diff --git a/backend/app/services/shipping_notice/document_layout/native_pdf.py b/backend/app/services/shipping_notice/document_layout/native_pdf.py index da7b1f96..9d6ff9db 100644 --- a/backend/app/services/shipping_notice/document_layout/native_pdf.py +++ b/backend/app/services/shipping_notice/document_layout/native_pdf.py @@ -93,56 +93,62 @@ def extract_native_pdf_pages( """ if not content or render_scale <= 0: raise ValueError('native PDF content and positive render scale are required') - pdf = pdfium.PdfDocument(content) pages: list[NativePdfPage] = [] - for page_index in range(len(pdf)): - page = pdf[page_index] - width, height = page.get_size() - text_page = page.get_textpage() - characters: list[PositionedCharacter] = [] - pending_boundary: str = 'none' - for char_index in range(text_page.count_chars()): - text = text_page.get_text_range(char_index, 1) - if not text: - continue - if not normalize_layout_text(text): - if any(character in {'\r', '\n'} for character in text): - pending_boundary = 'line_break' - elif pending_boundary == 'none' and any(character.isspace() for character in text): - pending_boundary = 'space' - continue - left, bottom, right, top = text_page.get_charbox(char_index, loose=True) - if right <= left or top <= bottom: - # 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。 - pending_boundary = 'none' - continue + pdf = pdfium.PdfDocument(content) + try: + for page_index in range(len(pdf)): + page = pdf[page_index] + text_page = None try: - # 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。 - characters.append(PositionedCharacter( - text=text, - bbox=LayoutBBox( - x0=left, y0=height - top, x1=right, y1=height - bottom, - ), - source_index=char_index, - boundary_before=pending_boundary, + width, height = page.get_size() + text_page = page.get_textpage() + characters: list[PositionedCharacter] = [] + pending_boundary: str = 'none' + for char_index in range(text_page.count_chars()): + text = text_page.get_text_range(char_index, 1) + if not text: + continue + if not normalize_layout_text(text): + if any(character in {'\r', '\n'} for character in text): + pending_boundary = 'line_break' + elif pending_boundary == 'none' and any(character.isspace() for character in text): + pending_boundary = 'space' + continue + left, bottom, right, top = text_page.get_charbox(char_index, loose=True) + if right <= left or top <= bottom: + # 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。 + pending_boundary = 'none' + continue + try: + # 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。 + characters.append(PositionedCharacter( + text=text, + bbox=LayoutBBox( + x0=left, y0=height - top, x1=right, y1=height - bottom, + ), + source_index=char_index, + boundary_before=pending_boundary, + )) + pending_boundary = 'none' + except ValueError: + pending_boundary = 'none' + continue + characters = _assign_page_line_ids(characters, page_no=page_index + 1) + rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360 + pages.append(NativePdfPage( + page_no=page_index + 1, + width=float(width), + height=float(height), + rotation=rotation if rotation in {0, 90, 180, 270} else 0, + characters=characters, + image=_render_native_pdf_page(page, render_scale) if render_images else None, )) - pending_boundary = 'none' - except ValueError: - pending_boundary = 'none' - continue - characters = _assign_page_line_ids(characters, page_no=page_index + 1) - rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360 - pages.append(NativePdfPage( - page_no=page_index + 1, - width=float(width), - height=float(height), - rotation=rotation if rotation in {0, 90, 180, 270} else 0, - characters=characters, - image=( - np.asarray(page.render(scale=render_scale).to_numpy()).copy() - if render_images else None - ), - )) + finally: + if text_page is not None: + text_page.close() + page.close() + finally: + pdf.close() return pages @@ -191,27 +197,43 @@ def attach_native_pdf_page_images( return [] if all(page.image is not None for page in pages): return list(pages) - pdf = pdfium.PdfDocument(content) attached: list[NativePdfPage] = [] - for page in pages: - if page.image is not None: - attached.append(page) - continue - index = int(page.page_no) - 1 - if index < 0 or index >= len(pdf): - raise ValueError('native PDF page_no is out of range for image attach') - image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy() - attached.append(NativePdfPage( - page_no=page.page_no, - width=page.width, - height=page.height, - rotation=page.rotation, - characters=page.characters, - image=image, - )) + pdf = pdfium.PdfDocument(content) + try: + for native_page in pages: + if native_page.image is not None: + attached.append(native_page) + continue + index = int(native_page.page_no) - 1 + if index < 0 or index >= len(pdf): + raise ValueError('native PDF page_no is out of range for image attach') + page = pdf[index] + try: + image = _render_native_pdf_page(page, render_scale) + finally: + page.close() + attached.append(NativePdfPage( + page_no=native_page.page_no, + width=native_page.width, + height=native_page.height, + rotation=native_page.rotation, + characters=native_page.characters, + image=image, + )) + finally: + pdf.close() return attached +def _render_native_pdf_page(page: Any, render_scale: float) -> np.ndarray: + """将 PDFium 页面复制为独立 ndarray 后立即释放临时 bitmap,避免其 finalizer 滞留到进程退出。""" + bitmap = page.render(scale=render_scale) + try: + return np.asarray(bitmap.to_numpy()).copy() + finally: + bitmap.close() + + def build_native_pdf_text_table_fallbacks( content: bytes, *, @@ -232,17 +254,24 @@ def build_native_pdf_text_table_fallbacks( continue start_index, end_index = header header_lines = lines[start_index:end_index + 1] - body_lines = lines[end_index + 1:] - stop_index = next(( - index for index, line in enumerate(body_lines) - if _is_fallback_total(line) or _is_fallback_separator(line) - ), len(body_lines)) - body_lines = body_lines[:stop_index] - if not body_lines: - continue boundaries = _fallback_column_boundaries(header_lines, page.width) if len(boundaries) < 3: continue + body_lines: list[dict[str, Any]] = [] + has_data_row = False + for line in lines[end_index + 1:]: + if _is_fallback_total(line): + break + if _is_fallback_separator(line): + # 采购订单常在表头和首条明细之间画横线;只有已见明细后的横线才是表尾。 + if has_data_row: + break + continue + body_lines.append(line) + if _fallback_data_row(_fallback_cells([line], boundaries)): + has_data_row = True + if not body_lines: + continue header_cells = _fallback_cells(header_lines, boundaries) body_cells = [_fallback_cells([line], boundaries) for line in body_lines] if not any(_fallback_data_row(row) for row in body_cells): 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 c0169327..b2b4d351 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 @@ -23,6 +23,7 @@ from app.services.shipping_notice.document_layout.order_profile import ( AnchorRule, OrderCoordinateProfile, OrderFieldLayout, + ReferencePageFrame, RelativeRegion, ) from app.services.shipping_notice.order_schema.field_rules import ( @@ -53,6 +54,7 @@ def extract_order_fields( *, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False, coordinate_transform: dict[str, Any] | None = None, + allow_fixed_region_confirmation: bool = False, ) -> list[OrderFieldExtraction]: """ 用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。 @@ -63,6 +65,9 @@ def extract_order_fields( coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。 allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的 PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。 + allow_fixed_region_confirmation: 仅唯一匹配模板的正式运行或当前模板盲测回放可启用。 + 它只允许原生 PDF 坐标的无标签固定区域成为 confirmed;OCR、未匹配模板和 + 普通预览仍保持 needs_review。 Returns: 每个已绑定布局对应一个候选,按模板声明顺序返回。 @@ -78,7 +83,9 @@ def extract_order_fields( layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence, + reference_page_frames=effective_profile.reference_page_frames, allow_ocr_preview_fallback=allow_ocr_preview_fallback, + allow_fixed_region_confirmation=allow_fixed_region_confirmation, ) for layout in effective_profile.order_field_layouts ] @@ -103,7 +110,8 @@ def _project_coordinate_transform( def _extract_layout( *, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], - allow_ocr_preview_fallback: bool = False, + reference_page_frames: dict[int, ReferencePageFrame], + allow_ocr_preview_fallback: bool = False, allow_fixed_region_confirmation: bool = False, ) -> OrderFieldExtraction: """处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。""" config = schema_fields.get(layout.field_id) @@ -139,6 +147,7 @@ def _extract_layout( results: list[OrderFieldExtraction] = [] for page_no, glyphs, width, height, source in candidates: + reference_page_frame = reference_page_frames.get(page_no) if not _source_allowed( layout, config=config, @@ -150,18 +159,25 @@ def _extract_layout( if layout.anchor is None: results.append(_read_value_region( layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, - region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None, - fallback=True, + region=_absolute_relative_region( + layout.fallback_value_region, width=width, height=height, + reference_page_frame=reference_page_frame, + ), anchor_bbox=None, + fallback=not (allow_fixed_region_confirmation and source == 'pdf_coordinate'), )) continue matches = _find_anchor_matches( glyphs, layout.anchor, page_width=width, page_height=height, - ignore_reference_region=_uses_movable_anchor_value_region(layout=layout, width=width, height=height), + reference_page_frame=reference_page_frame, + ignore_reference_region=_uses_movable_anchor_value_region( + layout=layout, width=width, height=height, reference_page_frame=reference_page_frame, + ), ) if not matches: reference_anchor = ( _anchor_from_reference_region( glyphs, anchor=layout.anchor, page_width=width, page_height=height, + reference_page_frame=reference_page_frame, ) if _is_placeholder_anchor_text(layout.anchor.text) else None ) @@ -171,7 +187,10 @@ def _extract_layout( # intent, but it must remain review-only until the label is fixed. results.append(_read_value_region( layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, - region=_absolute_value_region(layout=layout, anchor=reference_anchor, width=width, height=height), + region=_absolute_value_region( + layout=layout, anchor=reference_anchor, width=width, height=height, + reference_page_frame=reference_page_frame, + ), anchor_bbox=reference_anchor, fallback=False, review_issue='order_field_anchor_text_mismatch', )) @@ -187,7 +206,10 @@ def _extract_layout( anchor_bbox, _indices = matches[0] results.append(_read_value_region( layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, - region=_absolute_value_region(layout=layout, anchor=anchor_bbox, width=width, height=height), anchor_bbox=anchor_bbox, fallback=False, + region=_absolute_value_region( + layout=layout, anchor=anchor_bbox, width=width, height=height, + reference_page_frame=reference_page_frame, + ), anchor_bbox=anchor_bbox, fallback=False, )) usable = [item for item in results if item.status != 'unavailable'] if len(usable) == 1: @@ -321,6 +343,7 @@ def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], reg def _find_anchor_matches( glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None, + reference_page_frame: ReferencePageFrame | None = None, ignore_reference_region: bool = False, ) -> list[tuple[LayoutBBox, list[int]]]: """在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。""" @@ -348,23 +371,22 @@ def _find_anchor_matches( compact, position=position, length=len(normalized), anchor=anchor, ): bbox = _union_bbox([item for _index, item in consumed]) - if ignore_reference_region or _anchor_bbox_in_reference_region( - bbox, anchor=anchor, page_width=page_width, page_height=page_height, - ): - matches.append((bbox, [index for index, _item in consumed])) + # 先按文本收集全部精确命中;保存的参考框只用于多个同名标签 + # 的消歧,不能让同版式样本中唯一但位置变化的标签直接丢失。 + matches.append((bbox, [index for index, _item in consumed])) start = position + max(len(label), 1) unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {} for bbox, indices in matches: unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices) resolved = list(unique.values()) - # An unlocked label may shift between documents, so its reference box must - # not suppress a sole match. When the same label occurs multiple times, - # however, the saved canvas position is decisive evidence for this sample. + # 唯一文本命中不受历史参考框限制;同名标签多次出现时,保存位置才是 + # 当前样本的消歧证据。若位置也无法唯一消歧,调用方会进入人工复核。 if len(resolved) > 1 and anchor.region is not None and page_width and page_height: positioned = [ item for item in resolved if _anchor_bbox_in_reference_region( - item[0], anchor=anchor, page_width=page_width, page_height=page_height, enforce=True, + item[0], anchor=anchor, page_width=page_width, page_height=page_height, + reference_page_frame=reference_page_frame, enforce=True, ) ] if len(positioned) == 1: @@ -397,6 +419,7 @@ def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) -> def _anchor_bbox_in_reference_region( bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None, + reference_page_frame: ReferencePageFrame | None = None, enforce: bool = False, ) -> bool: """锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。""" @@ -404,17 +427,22 @@ def _anchor_bbox_in_reference_region( return True if page_width is None or page_height is None or page_width <= 0 or page_height <= 0: return False - region = _absolute_relative_region(anchor.region, width=page_width, height=page_height) + region = _absolute_relative_region( + anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame, + ) return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region) def _anchor_from_reference_region( glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float, + reference_page_frame: ReferencePageFrame | None = None, ) -> LayoutBBox | None: """为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。""" if anchor.region is None: return None - region = _absolute_relative_region(anchor.region, width=page_width, height=page_height) + region = _absolute_relative_region( + anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame, + ) selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)] return _union_bbox(selected) if selected else None @@ -500,11 +528,19 @@ def _source_allowed( return not ('coordinate' in required_levels and source != 'pdf_coordinate') -def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox: - """将固定低可靠度归一化页区投影为当前页面绝对框。""" +def _absolute_relative_region( + region: RelativeRegion | None, *, width: float, height: float, + reference_page_frame: ReferencePageFrame | None = None, +) -> LayoutBBox: + """将区域投影为 PDF 点坐标;有标注页框时不得随当前长页高度缩放。""" if region is None: raise ValueError('fallback order field region is required') - return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height) + projection_width = reference_page_frame.width if reference_page_frame is not None else width + projection_height = reference_page_frame.height if reference_page_frame is not None else height + return LayoutBBox( + x0=region.x0 * projection_width, y0=region.y0 * projection_height, + x1=region.x1 * projection_width, y1=region.y1 * projection_height, + ) def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox: @@ -518,14 +554,17 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB ) -def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox: - """读取管理员值框;右侧/下方字段只随标签平移,绝不按标签框尺寸缩放。""" +def _absolute_value_region( + *, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float, + reference_page_frame: ReferencePageFrame | None = None, +) -> LayoutBBox: + """读取管理员值框;有保存参考锚点时整框随唯一命中标签平移,绝不缩放。""" if layout.value_region is not None: if layout.anchor is None or layout.anchor.region is None: return _absolute_anchor_region(layout.value_region, anchor) if layout.value_mode not in {'right_of_anchor', 'below_anchor'}: return _absolute_anchor_region(layout.value_region, anchor) - reference = _absolute_relative_region(layout.anchor.region, width=width, height=height) + reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame) saved = _absolute_anchor_region(layout.value_region, reference) if layout.value_mode == 'right_of_anchor': region = _absolute_anchor_region(layout.value_region, anchor) @@ -536,19 +575,33 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt x1=anchor.x1 + projected_width, y1=region.y1, ) elif layout.absolute_value_region is not None: - saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height) + saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame) if layout.anchor is None or layout.anchor.region is None: return saved - reference = _absolute_relative_region(layout.anchor.region, width=width, height=height) + reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame) else: raise ValueError('anchored order field has no value region') if layout.value_mode not in {'right_of_anchor', 'below_anchor'}: + # absolute_value_region 记录的是标注页上的完整取值框。标签在当前 + # 文档因可选单头内容整体移动时,single_line/multi_line 也必须保留 + # 框的形状,并以该字段自己的唯一锚点中心作同量平移。 + if layout.absolute_value_region is not None: + reference_center_x = (reference.x0 + reference.x1) / 2 + reference_center_y = (reference.y0 + reference.y1) / 2 + anchor_center_x = (anchor.x0 + anchor.x1) / 2 + anchor_center_y = (anchor.y0 + anchor.y1) / 2 + return LayoutBBox( + x0=saved.x0 + anchor_center_x - reference_center_x, + y0=saved.y0 + anchor_center_y - reference_center_y, + x1=saved.x1 + anchor_center_x - reference_center_x, + y1=saved.y1 + anchor_center_y - reference_center_y, + ) return saved anchor_center_x, anchor_center_y = (anchor.x0 + anchor.x1) / 2, (anchor.y0 + anchor.y1) / 2 if _regions_overlap(anchor, reference): return saved if layout.absolute_value_region is not None and not _uses_movable_anchor_value_region( - layout=layout, width=width, height=height, + layout=layout, width=width, height=height, reference_page_frame=reference_page_frame, ): return saved if layout.value_mode == 'right_of_anchor': @@ -563,7 +616,10 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt ) -def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool: +def _uses_movable_anchor_value_region( + *, layout: OrderFieldLayout, width: float, height: float, + reference_page_frame: ReferencePageFrame | None = None, +) -> bool: """判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。""" if layout.value_region is not None: return layout.value_mode in {'right_of_anchor', 'below_anchor'} @@ -572,8 +628,8 @@ def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, or layout.value_mode not in {'right_of_anchor', 'below_anchor'} ): return False - reference = _absolute_relative_region(layout.anchor.region, width=width, height=height) - saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height) + reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame) + saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame) tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2 return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance 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 5b443f1b..6b416d38 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -50,6 +50,15 @@ class RelativeRegion(OrderProfileModel): return self +class ReferencePageFrame(OrderProfileModel): + """冻结标注样本的 PDF CropBox 点尺寸,供跨页高变化时还原相对区域。""" + + width: float = Field(gt=0) + height: float = Field(gt=0) + origin: Literal['pdf_top_left'] = 'pdf_top_left' + box: Literal['cropbox'] = 'cropbox' + + class AnchorRelativeRegion(OrderProfileModel): """仅接收历史锚点相对值框;新模板统一保存 absolute_value_region。""" @@ -251,7 +260,7 @@ class TableRegionProfile(OrderProfileModel): page_no: int | None = Field(default=None, ge=1) region: RelativeRegion # 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。 - line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$') + line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$') # 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。 row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows' # 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核, @@ -291,7 +300,7 @@ class TableRegionProfile(OrderProfileModel): if len(fields) != len(set(fields)): raise ValueError('field_code may bind to only one coordinate region per table') # 草稿可先框物理行;一旦主行开始绑字段,就必须包含起行锚点。 - if self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in { + if self.line_start_field_code and self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in { field.field_code for field in self.line_layouts[0].field_regions }: raise ValueError('main line layout must bind the configured line-start field') @@ -488,6 +497,7 @@ class OrderCoordinateProfile(OrderProfileModel): order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list) draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list) coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel) + reference_page_frames: dict[int, ReferencePageFrame] = Field(default_factory=dict) @model_validator(mode='after') def validate_profile_rules(self) -> 'OrderCoordinateProfile': 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 c3654ee2..11d12dc3 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 @@ -150,6 +150,7 @@ def match_frozen_coordinate_profiles( table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) except (TypeError, ValueError): continue @@ -506,29 +507,49 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N def _resolve_coordinate_transform( *, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any], ) -> tuple[dict[str, Any] | None, list[str]]: - """根据 Profile 声明的唯一静态锚点求受限平移,任何不确定性都返回硬失败原因。 + """根据冻结的模板身份锚点求受限平移,任何不确定性都返回硬失败原因。 Args: - profile: 当前冻结坐标 Profile;仅 ``anchor_frame`` 启用此能力。 + profile: 当前冻结坐标 Profile;旧 ``anchor_frame`` 优先,其他模板复用已框选的 + 必选文档匹配标签,不要求管理员选择坐标模型。 pages: 当前 Layout 的页尺寸证据。 page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。 Returns: - ``(transform, reason_codes)``。legacy 返回 ``(None, [])``;anchor_frame 仅在 - 所有锚点唯一且变换位于声明上限内时返回 ``status=applied``。 + ``(transform, reason_codes)``。没有可证明的静态标签时返回 ``(None, [])``; + 有标签时仅在全部唯一且变换位于受限范围内返回 ``status=applied``。 """ model = profile.coordinate_model + anchors = list(model.anchors) + max_translate_x = model.max_translate_x + max_translate_y = model.max_translate_y if model.type != 'anchor_frame': + anchors = [ + AnchorRule( + anchor_id=anchor.anchor_id, + text=anchor.label, + match_mode='exact', + region=anchor.label_region, + position_locked=True, + minimum_evidence_level=anchor.minimum_evidence_level, + ) + for anchor in profile.document_match.required_anchors + if anchor.label_region is not None + ] + # 没有已框选的稳定标签时保持绝对坐标兼容;不从全文猜测校正基准。 + if not anchors: + return None, [] + if not anchors: return None, [] deltas: list[tuple[float, float]] = [] anchor_points: list[tuple[float, float, float, float]] = [] anchor_ids: list[str] = [] - for anchor in model.anchors: + for anchor in anchors: found = _find_anchor_rule_matches( anchor=anchor, pages=pages, page_glyphs=page_glyphs, - max_translate_x=min(.30, model.max_translate_x * 2), - max_translate_y=min(.30, model.max_translate_y * 2), + max_translate_x=min(.30, max_translate_x * 2), + max_translate_y=min(.30, max_translate_y * 2), ) if not found: return None, ['profile_anchor_frame_anchor_missing'] @@ -552,7 +573,7 @@ def _resolve_coordinate_transform( anchor_points.append((expected_x, expected_y, observed_x, observed_y)) anchor_ids.append(anchor.anchor_id) - if model.transform_mode == 'affine': + if model.type == 'anchor_frame' and model.transform_mode == 'affine': transform, reason = _resolve_affine_coordinate_transform( anchor_points=anchor_points, anchor_ids=anchor_ids, model=model, ) @@ -561,7 +582,7 @@ def _resolve_coordinate_transform( 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'] - if abs(first_x) > model.max_translate_x or abs(first_y) > model.max_translate_y: + if abs(first_x) > max_translate_x or abs(first_y) > max_translate_y: return None, ['profile_anchor_frame_transform_out_of_range'] return { 'status': 'applied', diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py b/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py index 88d77e0c..6625a69d 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_parse_validation.py @@ -51,6 +51,8 @@ def validate_profile_parse_candidate( document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []}, table_regions=profile_def.get('table_regions') or [], order_field_layouts=profile_def.get('order_field_layouts') or [], + coordinate_model=profile_def.get('coordinate_model') or {}, + reference_page_frames=profile_def.get('reference_page_frames') or {}, ) except (TypeError, ValueError): return { diff --git a/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py b/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py deleted file mode 100644 index 9f1bb1f2..00000000 --- a/backend/app/services/shipping_notice/document_layout/profile_field_source_mapping_service.py +++ /dev/null @@ -1,456 +0,0 @@ -""" -services/shipping_notice/document_layout/profile_field_source_mapping_service.py - -用途:Profile 字段来源映射服务(Q18 抽取层裁决前置)——独立收集 Header / Table 列 / - Vendor Comments 三个来源的候选观察,**不直接写 Observation 表**,只返回统一的 - FieldSourceCandidate 列表供 SourceMergeService 做 Q18 裁决合并。 -依赖:profile_vendor_comments_contract(parse_field_source_mappings/parse_named_regions)、 - field_split_core(execute_base_split_rule_set 用于 Vendor Comments 区域拆分)、 - coordinate_region_source_adapter(CoordinateRegionSourceAdapter 物理区域渲染)、 - reservation_relation_projection(ReservationRelationProjection 关系投影)。 -逻辑:严格「后端决定 UI」——本类输出每个候选的 target_scope/target_field_code/ - effective_line_no/value/source/evidence_ref/source_observation_metadata, - 前端只能消费这些投影字段,禁止自行推导业务状态。 -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any, Literal - -from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import ( - CoordinateRegionEvidence, - CoordinateRegionSourceAdapter, - CoordinateRegionSourceResult, -) -from app.services.shipping_notice.document_layout.field_split_core import ( - CoreCapturedRelation, - _CoreSegmentResult, - execute_base_split_rule_set, -) -from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( - NamedRegion, - ProfileFieldSourceMapping, - parse_field_source_mappings, - parse_named_regions, -) -from app.services.shipping_notice.document_layout.reservation_relation_projection import ( - ReservationRelationProjection, - ReservationRelationProjectionResult, -) - - -FieldSourceLiteral = Literal['header_region', 'table_column', 'vendor_comments'] - - -@dataclass -class FieldSourceCandidate: - """ - 单来源单观察候选——Header/Table/Vendor Comments 各自产出后,由 SourceMergeService 裁决。 - - 【后端决定 UI】:scope、line_no、value、format_valid、conflict_group_key 全部在本层 - 计算完毕,前端只读投影,禁止自己用逻辑 if/else 推导。 - """ - - source: FieldSourceLiteral - target_scope: Literal['header', 'line'] - target_field_code: str - target_field_id: str - value: str - normalized_value: str - format_valid: bool | None # None = 本字段不需要格式校验(非 reservation) - format_reason_code: str | None # format_valid=False 时的稳定诊断码(例:reservation_format_invalid) - effective_line_no: int | None # 1-based;header 时为 None;default_all_lines 时为具体行号 - resolution_hint: Literal[ - 'provisional', 'annotation_only', 'invalid_line_reference', - ] = 'provisional' - relation_projection: ReservationRelationProjectionResult | None = None - # 证据区——写入 Observation.evidence_quote / evidence_ref / evidence_metadata_json - evidence_quote: str | None = None - evidence_ref: str | None = None - evidence_metadata: dict[str, Any] = field(default_factory=dict) - # SourceMergeService 内部使用:冲突分组键 = (target_scope, target_field_code, effective_line_no) - conflict_group_key: tuple[Any, ...] = () - - -class ProfileFieldSourceMappingService: - """ - 三来源候选独立收集服务(路径判断与事实分离)。 - - 【AI 触发时机】:订单文档抽取阶段(order_extraction_workflow 在 Observation 写入前) - 调用 collect_candidates() 返回候选列表,再交给 SourceMergeService 裁决合并。 - - 核心执行顺序: - [STEP 1] 解析 Profile definition_json 的 named_regions + field_source_mappings。 - [STEP 2] 对每个 mapping: - a. header_source_enabled → 从 header_observations_by_source_ref 取现成观察 - b. table_source_enabled → 从 table_column_values 取(column_code + line_index) - c. vendor_comments_enabled → 调 CoordinateRegionSourceAdapter + execute_base_split_rule_set - [STEP 3] 对每个 Vendor Comments 拆分结果,调 ReservationRelationProjection.project - 生成 effective_line_no / resolution_hint。 - [STEP 4] 返回 FieldSourceCandidate 列表;未通过 format_policy 的候选保留 - value 但标记 format_valid=False(Q15:格式失败的值不丢弃)。 - """ - - def __init__( - self, - *, - definition_json: dict[str, Any], - header_observations_by_source_ref: dict[str, list[dict[str, Any]]] | None = None, - table_column_values: dict[str, list[dict[str, Any]]] | None = None, - page_glyphs_map: dict[int, dict[str, Any]] | None = None, - # Reservation Relation Projection 三层判定表 - explicit_line_column_values: dict[int, str] | None = None, - profile_business_line_numbers: dict[int, Any] | None = None, - classified_logical_line_numbers: dict[int, int] | None = None, - total_logical_lines: int = 0, - # 格式策略调用方(保留注入点,避免本类直接 import reservation 校验模块造成循环) - format_validator_callback=None, - ): - self.definition_json = definition_json or {} - self.header_observations_by_source_ref = header_observations_by_source_ref or {} - self.table_column_values = table_column_values or {} - self.page_glyphs_map = page_glyphs_map or {} - self.explicit_line_column_values = explicit_line_column_values or {} - self.profile_business_line_numbers = profile_business_line_numbers or {} - self.classified_logical_line_numbers = classified_logical_line_numbers or {} - self.total_logical_lines = total_logical_lines - self.format_validator_callback = format_validator_callback - # 预先解析契约(若失败抛 ValidationError 阻断运行,避免输出坏数据) - self.named_regions: dict[str, NamedRegion] = parse_named_regions( - self.definition_json.get('named_regions'), - ) - self.mappings: list[ProfileFieldSourceMapping] = parse_field_source_mappings( - self.definition_json.get('field_source_mappings'), - ) - - # ------------------------------------------------------------------ - # 对外主入口 - # ------------------------------------------------------------------ - - def collect_candidates(self) -> list[FieldSourceCandidate]: - """ - 返回全量候选。任何内部失败都返回稳定 status 候选(不抛错阻断其他字段)。 - 调用方:SourceMergeService.merge_and_decide() → 再调用 obs 写入。 - """ - candidates: list[FieldSourceCandidate] = [] - for mapping in self.mappings: - if mapping.header_source_enabled and mapping.header_source_ref: - candidates.extend(self._collect_header_source(mapping)) - if mapping.table_source_enabled and mapping.table_column_code: - candidates.extend(self._collect_table_source(mapping)) - if mapping.vendor_comments_enabled and mapping.vendor_comments_region_ref: - candidates.extend(self._collect_vendor_comments_source(mapping)) - for cand in candidates: - cand.conflict_group_key = (cand.target_scope, cand.target_field_code, cand.effective_line_no) - return candidates - - # ------------------------------------------------------------------ - # 三个来源分支(独立收集,不互相读数据——满足 Q18 先独立再裁决) - # ------------------------------------------------------------------ - - def _collect_header_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]: - """Header 区域来源——从 caller 传入的 header_observations_by_source_ref 读取。""" - header_items = self.header_observations_by_source_ref.get(mapping.header_source_ref or '', []) - results: list[FieldSourceCandidate] = [] - for item in header_items: - raw_value = str(item.get('value') or '') - format_valid, reason = self._check_format(mapping, raw_value) - results.append(FieldSourceCandidate( - source='header_region', - target_scope=mapping.target_scope, - target_field_code=mapping.target_field_code, - target_field_id=mapping.target_field_id, - value=raw_value, - normalized_value=_normalize_string(raw_value), - format_valid=format_valid, - format_reason_code=reason, - effective_line_no=None, # header scope 固定 None - evidence_quote=raw_value[:512], - evidence_ref=str(item.get('evidence_ref') or '') or None, - evidence_metadata=dict(item.get('evidence_metadata') or {}), - )) - return results - - def _collect_table_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]: - """表身列来源——从 caller 传入的 table_column_values[column_code] 读取,每行一个候选。""" - rows = self.table_column_values.get(mapping.table_column_code or '', []) - results: list[FieldSourceCandidate] = [] - for row in rows: - try: - line_no = int(row.get('line_index')) + 1 # 转 1-based - except (TypeError, ValueError): - continue - raw_value = str(row.get('value') or '') - format_valid, reason = self._check_format(mapping, raw_value) - results.append(FieldSourceCandidate( - source='table_column', - target_scope=mapping.target_scope, - target_field_code=mapping.target_field_code, - target_field_id=mapping.target_field_id, - value=raw_value, - normalized_value=_normalize_string(raw_value), - format_valid=format_valid, - format_reason_code=reason, - effective_line_no=line_no, - evidence_quote=raw_value[:512], - evidence_ref=str(row.get('evidence_ref') or '') or None, - evidence_metadata=dict(row.get('evidence_metadata') or {}), - )) - return results - - def _collect_vendor_comments_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]: - """ - Vendor Comments 来源——三步走: - 1. CoordinateRegionSourceAdapter 渲染区域原文 + bbox 证据; - 2. execute_base_split_rule_set 拆出段(带 captured_relation); - 3. ReservationRelationProjection 投影关系到 effective_line_no / resolution_hint。 - """ - region_ref = mapping.vendor_comments_region_ref or '' - region = self.named_regions.get(region_ref) - if region is None: - return [self._missing_region_fallback(mapping, region_ref)] - adapter = CoordinateRegionSourceAdapter(region, self.page_glyphs_map) - region_result: CoordinateRegionSourceResult = adapter.extract() - if region_result.status != 'available' or not mapping.vendor_comments_split_rule_set: - return [self._unavailable_region_candidate(mapping, region_result)] - - split_result = execute_base_split_rule_set( - raw_value=region_result.raw_text, - rule_set=mapping.vendor_comments_split_rule_set, - lines=region_result.lines or None, - ) - - projector = ReservationRelationProjection( - relation_policy=mapping.relation_policy, - line_reference_basis=mapping.line_reference_basis, - missing_relation_policy=mapping.missing_relation_policy, - ) - # 先收集 mapped 段,再收集 evidence_only 段(annotation_only 用) - all_segments: list[_CoreSegmentResult] = list(split_result.segments) + list(split_result.evidence_only_segments) - results: list[FieldSourceCandidate] = [] - token_evidence_map = _build_evidence_ref_map(region_result.evidence_tokens) - for seg in all_segments: - rel_proj = projector.project( - captured_relation=seg.captured_relation, - explicit_line_column_values=self.explicit_line_column_values, - profile_business_line_numbers=self.profile_business_line_numbers, - classified_logical_line_numbers=self.classified_logical_line_numbers, - ) - format_valid, reason = self._check_format(mapping, seg.normalized_text) - if rel_proj.resolution == 'bound_to_line': - results.append(self._make_vc_candidate( - mapping=mapping, seg=seg, rel_proj=rel_proj, - region_result=region_result, token_evidence_map=token_evidence_map, - effective_line_no=rel_proj.resolved_logical_line_no, - resolution_hint='provisional', format_valid=format_valid, format_reason=reason, - )) - elif rel_proj.resolution == 'default_all_lines': - # 每行都生成一个(common case:整个 Vendor Comments 段没有 line 号引用) - for line_idx in range(1, max(1, self.total_logical_lines) + 1): - results.append(self._make_vc_candidate( - mapping=mapping, seg=seg, rel_proj=rel_proj, - region_result=region_result, token_evidence_map=token_evidence_map, - effective_line_no=line_idx if mapping.target_scope == 'line' else None, - resolution_hint='provisional', format_valid=format_valid, format_reason=reason, - )) - elif rel_proj.resolution == 'annotation_only': - results.append(self._make_vc_candidate( - mapping=mapping, seg=seg, rel_proj=rel_proj, - region_result=region_result, token_evidence_map=token_evidence_map, - effective_line_no=None, - resolution_hint='annotation_only', format_valid=format_valid, format_reason=reason, - )) - elif rel_proj.resolution == 'invalid_line_reference': - results.append(self._make_vc_candidate( - mapping=mapping, seg=seg, rel_proj=rel_proj, - region_result=region_result, token_evidence_map=token_evidence_map, - effective_line_no=None, - resolution_hint='invalid_line_reference', format_valid=False, - format_reason=reason or 'invalid_line_reference', - )) - else: - # default_header_only / conflict_unresolved - results.append(self._make_vc_candidate( - mapping=mapping, seg=seg, rel_proj=rel_proj, - region_result=region_result, token_evidence_map=token_evidence_map, - effective_line_no=None if mapping.target_scope == 'header' else None, - resolution_hint='provisional', format_valid=format_valid, format_reason=reason, - )) - return results - - # ------------------------------------------------------------------ - # 辅助:格式校验(Q15)+ Vendor Comments 候选构造 - # ------------------------------------------------------------------ - - def _check_format( - self, mapping: ProfileFieldSourceMapping, value: str, - ) -> tuple[bool | None, str | None]: - """返回 (format_valid, reason_code);非 reservation 字段返回 (None, None)。""" - if mapping.target_field_code != 'reservation_id': - return None, None - if not value: - return False, 'reservation_format_empty' - if self.format_validator_callback is not None: - ok = bool(self.format_validator_callback(mapping.format_policy, value)) - return (True, None) if ok else (False, 'reservation_format_invalid') - # 默认回退全局 validated_reservation_id(Q15 方案 A:本期不重构全局) - from app.services.shipping_notice.reservation_id import validated_reservation_id - ok = validated_reservation_id(value) is not None - return (True, None) if ok else (False, 'reservation_format_invalid') - - @staticmethod - def _missing_region_fallback(mapping: ProfileFieldSourceMapping, region_ref: str) -> FieldSourceCandidate: - return FieldSourceCandidate( - source='vendor_comments', - target_scope=mapping.target_scope, - target_field_code=mapping.target_field_code, - target_field_id=mapping.target_field_id, - value='', - normalized_value='', - format_valid=None, - format_reason_code=None, - effective_line_no=None, - resolution_hint='provisional', - evidence_quote=None, - evidence_ref=None, - evidence_metadata={'reason': 'named_region_not_found', 'region_ref': region_ref}, - ) - - @staticmethod - def _unavailable_region_candidate( - mapping: ProfileFieldSourceMapping, region_result: CoordinateRegionSourceResult, - ) -> FieldSourceCandidate: - return FieldSourceCandidate( - source='vendor_comments', - target_scope=mapping.target_scope, - target_field_code=mapping.target_field_code, - target_field_id=mapping.target_field_id, - value='', - normalized_value='', - format_valid=None, - format_reason_code=None, - effective_line_no=None, - resolution_hint='provisional', - evidence_quote=region_result.raw_text[:512] or None, - evidence_ref=None, - evidence_metadata={ - 'reason': region_result.diagnostic_code or 'named_region_unavailable', - 'diagnostic_message': region_result.diagnostic_message, - 'region_id': region_result.region_id, - }, - ) - - @staticmethod - def _make_vc_candidate( - *, - mapping: ProfileFieldSourceMapping, - seg: _CoreSegmentResult, - rel_proj: ReservationRelationProjectionResult, - region_result: CoordinateRegionSourceResult, - token_evidence_map: dict[str, list[CoordinateRegionEvidence]], - effective_line_no: int | None, - resolution_hint: Literal['provisional', 'annotation_only', 'invalid_line_reference'], - format_valid: bool | None, - format_reason: str | None, - ) -> FieldSourceCandidate: - token_ev = _find_best_token_evidence(token_evidence_map, seg.normalized_text) - evidence_quote = seg.raw_text[:512] or None - evidence_ref = _vc_evidence_ref(region_result, seg, token_ev) - metadata: dict[str, Any] = { - 'region_id': region_result.region_id, - 'segment_id': seg.segment_id, - 'rule_id': seg.rule_id, - 'matcher_type': seg.matcher_type, - 'handling': seg.handling, - 'line_bounds_in_region': [seg.line_no, seg.line_end_no], - 'captured_relation_raw': ( - None if seg.captured_relation is None else { - 'type': seg.captured_relation.type, - 'line_no': seg.captured_relation.line_no, - 'raw_text': seg.captured_relation.raw_text, - } - ), - 'relation_projection': _proj_to_json(rel_proj), - 'best_token': (None if token_ev is None else { - 'page_no': token_ev.page_no, - 'x0': token_ev.x0, 'y0': token_ev.y0, - 'x1': token_ev.x1, 'y1': token_ev.y1, - 'text': token_ev.text, - }), - } - return FieldSourceCandidate( - source='vendor_comments', - target_scope=mapping.target_scope, - target_field_code=mapping.target_field_code, - target_field_id=mapping.target_field_id, - value=seg.raw_text, - normalized_value=seg.normalized_text, - format_valid=format_valid, - format_reason_code=format_reason, - effective_line_no=effective_line_no, - resolution_hint=resolution_hint, - relation_projection=rel_proj, - evidence_quote=evidence_quote, - evidence_ref=evidence_ref, - evidence_metadata=metadata, - ) - - -# --------------------------------------------------------------------------- -# 模块级纯函数(避免每次 Service 实例化重复加载) -# --------------------------------------------------------------------------- - - -def _normalize_string(v: str) -> str: - return ' '.join(str(v or '').split()).strip() - - -def _build_evidence_ref_map(tokens: list[CoordinateRegionEvidence]) -> dict[str, list[CoordinateRegionEvidence]]: - out: dict[str, list[CoordinateRegionEvidence]] = {} - for t in tokens: - out.setdefault(_normalize_string(t.text), []).append(t) - return out - - -def _find_best_token_evidence( - evidence_map: dict[str, list[CoordinateRegionEvidence]], value: str, -) -> CoordinateRegionEvidence | None: - norm = _normalize_string(value) - if norm in evidence_map and evidence_map[norm]: - return evidence_map[norm][0] - # 降级:子串命中 - for key, tokens in evidence_map.items(): - if norm and (norm in key or key in norm) and tokens: - return tokens[0] - return None - - -def _vc_evidence_ref( - region_result: CoordinateRegionSourceResult, - seg: _CoreSegmentResult, - token: CoordinateRegionEvidence | None, -) -> str: - """ - 稳定 Observation.evidence_ref。 - 格式:vc:///p/seg-[:---] - """ - base = f"vc://{region_result.region_id}/p{region_result.page_no}/seg-{seg.segment_id}" - if token is not None: - base += ( - f":{round(token.x0, 4)}-{round(token.y0, 4)}-" - f"{round(token.x1, 4)}-{round(token.y1, 4)}" - ) - return base[:512] - - -def _proj_to_json(p: ReservationRelationProjectionResult) -> dict[str, Any]: - return { - 'line_reference_basis': p.line_reference_basis, - 'resolution': p.resolution, - 'resolved_logical_line_no': p.resolved_logical_line_no, - 'annotation_reason': p.annotation_reason, - 'invalid_reference_raw_value': p.invalid_reference_raw_value, - 'invalid_reference_line_no': p.invalid_reference_line_no, - 'audit_chain_count': 0 if p.audit_chain is None else len(p.audit_chain), - } diff --git a/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py b/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py deleted file mode 100644 index ec5f348d..00000000 --- a/backend/app/services/shipping_notice/document_layout/profile_vendor_comments_contract.py +++ /dev/null @@ -1,338 +0,0 @@ -""" -services/shipping_notice/document_layout/profile_vendor_comments_contract.py - -用途:Profile 顶层新增的 Vendor Comments 三来源契约(不修改现有 OrderCoordinateProfile 字段, - 保持「路径判断与事实分离」——definition_json.get 读取命名区域和字段来源映射)。 -依赖:Pydantic、field_split_core.BaseSplitRuleSet、RelativeRegion(来自 order_profile)。 -逻辑:对外暴露 parse_named_regions() / parse_field_source_mappings() / validate_format_policy() - 三个稳定入口;所有变更是否触发「回 Draft + 重新验证」由 profile_regions_require_draft() - 判定,禁止各业务点自行假设回 Draft 条件。 -""" - -from __future__ import annotations - -import hashlib -import json -import re -from typing import Any, Literal - -from pydantic import BaseModel, ConfigDict, Field, model_validator - -from app.core.errors import ValidationError -from app.services.shipping_notice.document_layout.field_split_core import ( - BaseSplitRuleSet, -) -from app.services.shipping_notice.document_layout.order_profile import ( - RelativeRegion, -) - - -# --------------------------------------------------------------------------- -# 顶层 Pydantic 契约——definition_json 结构 -# --------------------------------------------------------------------------- - - -VC_MODEL_CONFIG = ConfigDict(extra='forbid', validate_assignment=True) - - -class NamedRegion(BaseModel): - """ - 物理来源命名区域(Q14 冻结)——管理员圈选的坐标框。 - - 【关键约束】:不是 Schema 字段区域伪装,是 Vendor Comments 等非 XFA 正文块的真实 - 阅读区域。变更此对象必须回 Draft(由 profile_regions_require_draft 判定)。 - """ - - model_config = VC_MODEL_CONFIG - - region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$') - label: str = Field(min_length=1, max_length=160) - region: RelativeRegion - page_scope: Literal['first_page', 'last_page', 'all_pages', 'exact_page'] = 'last_page' - page_no: int | None = Field(default=None, ge=1) - selection_mode: Literal['fixed_region', 'auto_take_last_qualified'] = 'fixed_region' - - @model_validator(mode='after') - def validate_page_semantics(self) -> 'NamedRegion': - if self.page_scope == 'exact_page' and self.page_no is None: - raise ValueError('exact_page named region requires page_no') - if self.page_scope != 'exact_page' and self.page_no is not None: - raise ValueError('page_no is only allowed for exact_page named region') - return self - - -class ReservationFormatPolicy(BaseModel): - """ - Reservation 格式校验策略(Q15 冻结)——Profile 级受控策略,未配置时回退全局 5/10 纯数字。 - - 首期仅支持 numeric_5_or_10 / custom_safe_regex 两种;custom_safe_regex 必须经过 - 长度限制、捕获组限制、危险表达式黑名单与超时上限 4 层门禁。 - """ - - model_config = VC_MODEL_CONFIG - - mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] = 'inherit_global' - pattern: str | None = Field(default=None, min_length=1, max_length=1024) - max_capture_groups: int = Field(default=2, ge=0, le=8) - timeout_ms: int = Field(default=30, ge=10, le=500) - case_sensitive: bool = False - - @model_validator(mode='after') - def validate_regex_policy(self) -> 'ReservationFormatPolicy': - if self.mode != 'custom_safe_regex': - if self.pattern is not None: - raise ValueError('pattern only allowed for custom_safe_regex mode') - return self - if not self.pattern: - raise ValueError('custom_safe_regex requires a non-empty pattern') - _validate_safe_regex_pattern( - self.pattern, - max_groups=self.max_capture_groups, - case_sensitive=self.case_sensitive, - ) - return self - - -class ProfileFieldSourceMapping(BaseModel): - """ - Profile 级字段来源映射(Q9 冻结,并列 split_rules)——声明一个 Schema 字段从三来源 - (header/table_column/vendor_comments)哪几个抽取,以及各自使用的拆分规则与关系策略。 - """ - - model_config = VC_MODEL_CONFIG - - mapping_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') - target_scope: Literal['header', 'line'] - target_field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') - target_field_id: str = Field(min_length=1, max_length=128) - - # 三来源开关——未启用的来源在 ProfileFieldSourceMappingService 直接跳过 - header_source_enabled: bool = False - header_source_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$') - header_normalizer_key: str | None = Field(default=None, min_length=1, max_length=64) - - table_source_enabled: bool = False - table_column_code: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$') - - vendor_comments_enabled: bool = False - vendor_comments_region_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_-]{0,95}$') - vendor_comments_split_rule_set: BaseSplitRuleSet | None = None - - # 关系策略(Q2 双层设计)——本期仅 reservation_id 绑定明细行使用 bind_target_line - relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'] = 'no_relation' - missing_relation_policy: Literal['default_all_lines', 'default_header_only', 'fallback_single_line_when_no_reference'] = 'default_header_only' - line_reference_basis: Literal['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] = 'profile_business_line_no' - - # 三来源空值互补策略——Q4 冲突矩阵里不同 scope 独立保留,同 scope 值不一致 Review - fill_missing_from_other_sources: bool = True - - format_policy: ReservationFormatPolicy = Field(default_factory=ReservationFormatPolicy) - - @model_validator(mode='after') - def validate_source_refs(self) -> 'ProfileFieldSourceMapping': - if self.header_source_enabled and not self.header_source_ref: - raise ValueError('header_source_ref is required when header_source_enabled') - if self.table_source_enabled and not self.table_column_code: - raise ValueError('table_column_code is required when table_source_enabled') - if self.vendor_comments_enabled: - if not self.vendor_comments_region_ref: - raise ValueError('vendor_comments_region_ref is required when vendor_comments_enabled') - if not self.vendor_comments_split_rule_set: - raise ValueError('vendor_comments_split_rule_set is required when vendor_comments_enabled') - return self - - -# --------------------------------------------------------------------------- -# 稳定读取工具:接受 None / 脏 dict,返回归一化契约对象(路径判断与事实分离) -# --------------------------------------------------------------------------- - - -def parse_named_regions(value: Any) -> dict[str, NamedRegion]: - """ - 从 definition_json.named_regions(或 None)解析命名区域字典。 - - 【AI 触发时机】:读取 Profile 配置阶段、预览阶段或变更比对阶段调用。 - 核心逻辑:值为 None/空 dict 时返回空字典(允许客户先不配 Vendor Comments 区域); - 未知键直接保留映射,不抛错;坏值立刻抛 ValidationError 避免运行时污染。 - - Args: - value: Profile definition_json.get('named_regions') 原值。 - - Returns: - {region_id: NamedRegion} 字典。 - """ - if value is None: - return {} - if not isinstance(value, dict): - raise ValidationError( - 'definition_json.named_regions must be an object', - code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID', - ) - result: dict[str, NamedRegion] = {} - for key, raw in value.items(): - if not re.match(r'^[a-z][a-z0-9_-]{0,95}$', str(key)): - raise ValidationError( - f'named region key {key!r} is invalid', - code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID', - ) - try: - item = NamedRegion.model_validate(raw) if isinstance(raw, dict) else raw - except ValueError as exc: - raise ValidationError( - f'named region {key!r} is invalid: {exc}', - code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID', - ) from exc - if item.region_id != key: - raise ValidationError( - f'named region key {key!r} must match nested region_id {item.region_id!r}', - code='SHIPPING.PROFILE_NAMED_REGIONS_MISMATCH', - ) - result[key] = item - return result - - -def parse_field_source_mappings(value: Any) -> list[ProfileFieldSourceMapping]: - """ - 从 definition_json.field_source_mappings(或 None)解析字段来源映射列表。 - - 核心逻辑:返回值为稳定顺序列表,不做去重(重复的 target_scope/target_field_code - 组合将由 SourceMergeService 在抽取层做 Q18 冲突裁决)。 - """ - if value is None: - return [] - if not isinstance(value, list): - raise ValidationError( - 'definition_json.field_source_mappings must be a list', - code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID', - ) - results: list[ProfileFieldSourceMapping] = [] - for raw in value: - try: - results.append(ProfileFieldSourceMapping.model_validate(raw)) - except ValueError as exc: - raise ValidationError( - f'field source mapping is invalid: {exc}', - code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID', - ) from exc - return results - - -# --------------------------------------------------------------------------- -# 变更回 Draft 门禁(Q14 冻结:区域变化必须使 Profile 回 Draft) -# --------------------------------------------------------------------------- - - -REGION_CHANGE_REQUIRES_DRAFT_KEYS = frozenset({ - 'region', 'page_scope', 'page_no', 'selection_mode', -}) - - -def profile_regions_require_draft( - *, - old_named_regions: Any, - new_named_regions: Any, -) -> bool: - """ - 判断 named_regions 变更是否触发 Profile 回 Draft + 重新验证 + 盲测 + 发布。 - - 核心逻辑(fail-safe):任何 region 主键、坐标、页作用域、选取模式的增删改一律回 Draft; - 仅 label 文案调整(便于管理员标注说明)不触发。 - """ - try: - old_map = parse_named_regions(old_named_regions) - new_map = parse_named_regions(new_named_regions) - except ValidationError: - return True # 解析失败默认回 Draft(fail-close) - if set(old_map.keys()) != set(new_map.keys()): - return True - for region_id in old_map: - old_region = old_map[region_id] - new_region = new_map[region_id] - for key in REGION_CHANGE_REQUIRES_DRAFT_KEYS: - if getattr(old_region, key) != getattr(new_region, key): - return True - return False - - -def field_source_mappings_require_draft( - *, - old_mappings: Any, - new_mappings: Any, -) -> bool: - """ - 判断 field_source_mappings 变更是否触发回 Draft。 - - 核心逻辑:除了纯 label 类改动外的任何增删改一律回 Draft(首期全量回 Draft,保留细粒度 - 门禁的未来扩展点)。 - """ - try: - old_list = parse_field_source_mappings(old_mappings) - new_list = parse_field_source_mappings(new_mappings) - except ValidationError: - return True - if len(old_list) != len(new_list): - return True - old_payload = _stable_mapping_dumps(old_list) - new_payload = _stable_mapping_dumps(new_list) - return old_payload != new_payload - - -def _stable_mapping_dumps(items: list[ProfileFieldSourceMapping]) -> str: - payload = [m.model_dump(mode='json', sort_keys=True) for m in items] - return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')) - - -# --------------------------------------------------------------------------- -# 安全正则门禁(Q15 custom_safe_regex 发布前必过) -# --------------------------------------------------------------------------- - - -_UNSAFE_PATTERN_MARKERS = ( - r'\(.+[+*]\)\s*[+*]', # 嵌套量词 例: (a+)+ - r'\(\.?\*\)\s*\*', # 多重.* 回溯 - r'\(\[.*\]\)\{[0-9]+,[0-9]*\}', # 大范围字符类重复 - r'(? None: - """ - custom_safe_regex 的发布前样本验证门禁(Q15)——编译期就拦截危险表达式。 - 【注意】:运行时还需配合 timeout_ms 的 signal 看门狗(在 regex_runner_safe 中实现)。 - """ - if len(pattern) > 1024: - raise ValueError('custom_safe_regex pattern exceeds 1024 characters') - for marker in _UNSAFE_PATTERN_MARKERS: - if re.search(marker, pattern): - raise ValueError('custom_safe_regex pattern looks potentially catastrophic') - flags = 0 if case_sensitive else re.IGNORECASE - try: - compiled = re.compile(pattern, flags) - except re.error as exc: - raise ValueError(f'custom_safe_regex pattern failed to compile: {exc}') from exc - if compiled.groups > max_groups: - raise ValueError( - f'custom_safe_regex has {compiled.groups} capture groups; limit is {max_groups}' - ) - _ = compiled # 引用仅用于静态检查 - - -# --------------------------------------------------------------------------- -# 校验和(盲测/发布基准比对) -# --------------------------------------------------------------------------- - - -def field_source_mappings_checksum(mappings: list[ProfileFieldSourceMapping]) -> str: - """稳定 SHA-256 校验和,供发布冻结与审计引用。""" - payload = _stable_mapping_dumps(mappings).encode('utf-8') - return hashlib.sha256(payload).hexdigest() - - -def named_regions_checksum(regions: dict[str, NamedRegion]) -> str: - """稳定 SHA-256 校验和,供区域变更历史比对。""" - payload = json.dumps( - {rid: r.model_dump(mode='json', sort_keys=True) for rid, r in regions.items()}, - ensure_ascii=True, sort_keys=True, separators=(',', ':'), - ).encode('utf-8') - return hashlib.sha256(payload).hexdigest() diff --git a/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py b/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py deleted file mode 100644 index 58dd3c9a..00000000 --- a/backend/app/services/shipping_notice/document_layout/reservation_format_policy_service.py +++ /dev/null @@ -1,152 +0,0 @@ -""" -services/shipping_notice/document_layout/reservation_format_policy_service.py - -用途:Q15 Reservation ID 格式策略服务——Profile 级 format_policy 受控入口。 - 首期(阶段 2)保持「回退全局 validated_reservation_id(numeric_5_or_10 硬编码)」 - 不变;为未来 custom_safe_regex / 字母型 Reservation 保留扩展点。 -依赖:profile_vendor_comments_contract.ReservationFormatPolicy; - reservation_id.validated_reservation_id(全局回退)。 -逻辑:【技术重试与业务决策分离】——本类只负责**格式判断**,不改变值、不生成 Observation, - 调用方(ProfileFieldSourceMappingService._check_format)根据返回值标记 - reservation_format_invalid,但不丢弃候选(保留为 Review 证据展示)。 -""" - -from __future__ import annotations - -import re -from dataclasses import dataclass -from typing import Literal - -from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( - ReservationFormatPolicy, -) - - -RESERVATION_NUMERIC_5_OR_10_RE = re.compile(r'^(?:\d{5}|\d{10})$') - - -@dataclass -class FormatPolicyResult: - """格式校验结果——只描述事实,不携带业务动作。""" - - valid: bool - mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] - normalized_value: str | None = None # 仅 valid=True 时返回规范化值 - reason_code: str | None = None # valid=False 时的稳定诊断码 - - @property - def should_block_auto_create(self) -> bool: - """格式失败的值不得自动建单(Q15 冻结)。""" - return not self.valid - - -class ReservationFormatPolicyService: - """ - Profile 级 Reservation 格式策略受控入口。 - - 【AI 触发时机】:ProfileFieldSourceMappingService 收集候选、或 Candidate - Qualification 最终门禁时调用 check()。禁止任何地方直接 - if re.match(r'^\d{5,10}$', v) 绕过策略层。 - """ - - def check(self, policy: ReservationFormatPolicy, raw_value: str) -> FormatPolicyResult: - """ - 执行一次格式校验。调用方不得丢弃失败候选,必须将原因码写入 - FieldSourceCandidate.format_reason_code。 - - 核心路径(Q15 冻结): - ① mode=inherit_global → 调全局 validated_reservation_id 保持历史 71 调用方口径; - ② mode=numeric_5_or_10 → 等价于全局(显式模式;便于未来全局重构时切换默认); - ③ mode=custom_safe_regex → 调用发布前已通过 Pydantic 门禁的安全正则。 - """ - value = (raw_value or '').strip() - if not value: - return FormatPolicyResult( - valid=False, mode=policy.mode, normalized_value=None, - reason_code='reservation_format_empty', - ) - mode = policy.mode - if mode in {'inherit_global', 'numeric_5_or_10'}: - return self._check_numeric_5_or_10(value, mode) - if mode == 'custom_safe_regex': - return self._check_custom_safe_regex(policy, value) - return FormatPolicyResult( - valid=False, mode=mode, normalized_value=None, - reason_code='reservation_format_unknown_mode', - ) - - # ------------------------------------------------------------------ - # 内部实现 - # ------------------------------------------------------------------ - - @staticmethod - def _check_numeric_5_or_10( - value: str, - mode: Literal['inherit_global', 'numeric_5_or_10'], - ) -> FormatPolicyResult: - """纯数字 5/10 位——默认回退全局校验,但通过独立模块输出稳定结果。""" - # 先尝试全局 validated_reservation_id(保持与 71 调用方一致),失败再用本模块常量兜底 - try: - from app.services.shipping_notice.reservation_id import validated_reservation_id - global_result = validated_reservation_id(value) - if global_result is not None: - return FormatPolicyResult( - valid=True, mode=mode, normalized_value=global_result, - reason_code=None, - ) - except Exception: # fail-safe:若全局模块异常,不阻塞结果 - pass - match = RESERVATION_NUMERIC_5_OR_10_RE.match(value) - if match: - return FormatPolicyResult( - valid=True, mode=mode, normalized_value=value, - reason_code=None, - ) - return FormatPolicyResult( - valid=False, mode=mode, normalized_value=None, - reason_code='reservation_format_invalid', - ) - - @staticmethod - def _check_custom_safe_regex(policy: ReservationFormatPolicy, value: str) -> FormatPolicyResult: - """安全正则匹配——编译缓存;捕获组第 1 组作为规范化值(否则整串)。""" - pattern = policy.pattern or '' - flags = 0 if policy.case_sensitive else re.IGNORECASE - try: - compiled = re.compile(pattern, flags) - except re.error as exc: - return FormatPolicyResult( - valid=False, mode='custom_safe_regex', normalized_value=None, - reason_code=f'reservation_format_regex_compile_error:{exc.__class__.__name__}', - ) - # 发布前样本验证门禁已限制 catastrophic 风险;这里仅以标准 library 限制长度 - if len(value) > 128: - return FormatPolicyResult( - valid=False, mode='custom_safe_regex', normalized_value=None, - reason_code='reservation_format_value_too_long', - ) - match = compiled.search(value) - if not match: - return FormatPolicyResult( - valid=False, mode='custom_safe_regex', normalized_value=None, - reason_code='reservation_format_invalid', - ) - # 规范化值:第 1 捕获组 → 整串 - normalized: str = value - if compiled.groups >= 1: - try: - first_group = match.group(1) - if first_group: - normalized = str(first_group).strip() - except (IndexError, re.error): - normalized = match.group(0) or value - normalized = normalized.strip() - if not normalized: - return FormatPolicyResult( - valid=False, mode='custom_safe_regex', normalized_value=None, - reason_code='reservation_format_capture_empty', - ) - return FormatPolicyResult( - valid=True, mode='custom_safe_regex', normalized_value=normalized, - reason_code=None, - ) diff --git a/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py b/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py deleted file mode 100644 index 50fc9d67..00000000 --- a/backend/app/services/shipping_notice/document_layout/reservation_relation_projection.py +++ /dev/null @@ -1,228 +0,0 @@ -""" -services/shipping_notice/document_layout/reservation_relation_projection.py - -用途:Reservation 关系投影(Q2 双层设计 + Q12 invalid_line_reference 独立原因码)。 - 将拆分引擎内部捕获的 captured_relation + Profile 关系策略 relation_policy, - 映射为「绑定到哪条行、是否 annotation_only、是否 invalid_line_reference 独立」三输出。 -依赖:field_split_core.CoreCapturedRelation(来自 _CoreSegmentResult.captured_relation)、 - ProfileFieldSourceMapping.relation_policy / line_reference_basis。 -逻辑:严格遵循「路径判断与事实分离」——拆分引擎事实(line_no)只作为证据, - 最终绑定路径必须经过 line_reference_basis 三层映射校验后裁决; - 失败不抛异常,输出稳定 reason_code 供审计和前端翻译。 -""" - -from __future__ import annotations - -from dataclasses import dataclass -from typing import Any, Literal - -from app.services.shipping_notice.document_layout.field_split_core import ( - CoreCapturedRelation, -) - - -@dataclass -class ReservationRelationProjectionResult: - """关系投影最终结果——只输出明确分支,禁止上游自行判断。""" - - line_reference_basis: Literal[ - 'explicit_line_column', - 'profile_business_line_no', - 'classified_logical_line_no', - ] - resolution: Literal[ - 'bound_to_line', # bind_target_line 成功,resolved_logical_line_no 有值 - 'annotation_only', # 显式 annotation_only,Observation 存 metadata - 'default_all_lines', # 关系缺失 + default_all_lines,每行都生成 Observation - 'default_header_only', # 关系缺失 + default_header_only,写到 header scope - 'invalid_line_reference', # 引用了不存在的行号,独立原因码 Q12 - 'conflict_unresolved', # 未来多层映射冲突保留(本期不输出) - ] - resolved_logical_line_no: int | None = None # 1-based 逻辑行号,bound_to_line 时必填 - annotation_reason: str | None = None # annotation_only 时写入 Observation metadata - invalid_reference_raw_value: str | None = None # invalid_line_reference 时返回 raw_text - invalid_reference_line_no: int | None = None - audit_chain: list[dict[str, Any]] | None = None # 路径判断全链路审计快照 - - @property - def should_generate_line_observation(self) -> bool: - return self.resolution == 'bound_to_line' or self.resolution == 'default_all_lines' - - @property - def should_generate_header_observation(self) -> bool: - return self.resolution in {'default_header_only', 'annotation_only', 'invalid_line_reference'} - - -class ReservationRelationProjection: - """ - 把 captured_relation(规则层事实) + profile relation_policy(解释层策略) - 投影为最终绑定结果。 - - 【AI 触发时机】:三来源合并前,为每个 Vendor Comments / Header Reservation 候选 - 决定「写行 Observation 还是写头 Observation 还是 invalid_line_reference」时调用。 - - 核心路径: - [STEP 1] 若 relation_policy=annotation_only → 直接走 annotation_only 分支(审计记录原因)。 - [STEP 2] 若缺失 captured_relation → 走 missing_relation_policy 分支 - (default_all_lines / default_header_only / fallback_single_line_when_no_reference)。 - [STEP 3] 若有 captured_relation.line_no,按 line_reference_basis 三层校验: - ① explicit_line_column:对比 Schema Line 字段值(显式 Line 列),失败→invalid - ② profile_business_line_no:对比 Profile 业务行号(默认客户 PO 行号) - ③ classified_logical_line_no:逻辑行号(行序分类后的结果) - 三层任何一层命中即返回 bound_to_line;全部失败输出 invalid_line_reference 独立原因码。 - """ - - def __init__( - self, - *, - relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'], - line_reference_basis: Literal[ - 'explicit_line_column', - 'profile_business_line_no', - 'classified_logical_line_no', - ] = 'profile_business_line_no', - missing_relation_policy: Literal[ - 'default_all_lines', - 'default_header_only', - 'fallback_single_line_when_no_reference', - ] = 'default_header_only', - ): - self.relation_policy = relation_policy - self.line_reference_basis = line_reference_basis - self.missing_relation_policy = missing_relation_policy - - # ------------------------------------------------------------------ - # 对外入口 - # ------------------------------------------------------------------ - - def project( - self, - *, - captured_relation: CoreCapturedRelation | None, - # 下面四个映射是 Line Reference Basis 的判定表(caller 注入,避免本类查 Schema) - explicit_line_column_values: dict[int, str] | None = None, - profile_business_line_numbers: dict[int, Any] | None = None, - classified_logical_line_numbers: dict[int, int] | None = None, - # 审计备注(annotation_only 时必须填写原因字符串,例如 'customer_commentary_only') - annotation_reason_override: str | None = None, - ) -> ReservationRelationProjectionResult: - """ - 执行关系投影。 - - 【禁止 caller 自行推导】:不要在外部用 if captured_relation.line_no in ... 判断, - 必须走 project() 返回的稳定 resolution 分支。 - """ - audit: list[dict[str, Any]] = [ - {'step': 'policy_in', 'relation_policy': self.relation_policy, - 'line_reference_basis': self.line_reference_basis, - 'missing_relation_policy': self.missing_relation_policy}, - ] - - # [STEP 1] annotation_only 直接返回(本期用于 Customer 备注说明、不参与建单) - if self.relation_policy == 'annotation_only': - audit.append({'step': 'annotation_only', - 'reason': annotation_reason_override or 'profile_relation_policy_annotation_only'}) - return ReservationRelationProjectionResult( - line_reference_basis=self.line_reference_basis, - resolution='annotation_only', - annotation_reason=annotation_reason_override or 'profile_relation_policy_annotation_only', - audit_chain=audit, - ) - - # [STEP 2] 缺失 captured_relation → 走 missing_relation_policy - if captured_relation is None or captured_relation.line_no is None: - audit.append({'step': 'missing_relation', - 'raw_text': captured_relation.raw_text if captured_relation else None}) - return self._resolve_missing_policy(audit) - - # [STEP 3] 三层 line_reference_basis 判定(显式 Line 列值 → Profile 业务行号 → 逻辑行号) - rel_line_no = int(captured_relation.line_no) - audit.append({'step': 'relation_line_no_in', 'line_no': rel_line_no, - 'raw_text': captured_relation.raw_text}) - - basis_order = self._basis_order() - for basis_name in basis_order: - resolved = self._try_basis(basis_name, rel_line_no, explicit_line_column_values or {}, - profile_business_line_numbers or {}, - classified_logical_line_numbers or {}) - if resolved is not None: - audit.append({'step': 'basis_hit', 'basis': basis_name, - 'logical_line_no': resolved}) - return ReservationRelationProjectionResult( - line_reference_basis=self.line_reference_basis, - resolution='bound_to_line', - resolved_logical_line_no=resolved, - audit_chain=audit, - ) - - # 三层全不命中 → invalid_line_reference(Q12 独立原因码 + 独立审计链) - audit.append({'step': 'invalid_line_reference', 'tried_bases': basis_order}) - return ReservationRelationProjectionResult( - line_reference_basis=self.line_reference_basis, - resolution='invalid_line_reference', - invalid_reference_raw_value=captured_relation.raw_text, - invalid_reference_line_no=rel_line_no, - audit_chain=audit, - ) - - # ------------------------------------------------------------------ - # 内部步骤 - # ------------------------------------------------------------------ - - def _basis_order(self) -> list[str]: - """按 Profile.line_reference_basis 输出优先级顺序。""" - if self.line_reference_basis == 'explicit_line_column': - return ['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] - if self.line_reference_basis == 'profile_business_line_no': - return ['profile_business_line_no', 'classified_logical_line_no', 'explicit_line_column'] - return ['classified_logical_line_no', 'profile_business_line_no', 'explicit_line_column'] - - def _try_basis( - self, - basis: str, - rel_line_no: int, - explicit: dict[int, str], - profile_biz: dict[int, Any], - logical: dict[int, int], - ) -> int | None: - """尝试一层判定;命中则返回逻辑行号(1-based),否则返回 None。""" - if basis == 'explicit_line_column': - for logical_idx, raw in explicit.items(): - if str(raw).strip() == str(rel_line_no): - return int(logical_idx) - return None - if basis == 'profile_business_line_no': - for logical_idx, raw in profile_biz.items(): - if str(raw).strip() == str(rel_line_no): - return int(logical_idx) - return None - if basis == 'classified_logical_line_no': - for logical_idx, mapped in logical.items(): - if int(mapped) == rel_line_no: - return int(logical_idx) - return None - return None - - def _resolve_missing_policy(self, audit: list[dict[str, Any]]) -> ReservationRelationProjectionResult: - """缺失关系时按 missing_relation_policy 落分支。""" - policy = self.missing_relation_policy - audit.append({'step': 'missing_policy', 'policy': policy}) - if policy == 'default_all_lines': - return ReservationRelationProjectionResult( - line_reference_basis=self.line_reference_basis, - resolution='default_all_lines', - audit_chain=audit, - ) - if policy == 'fallback_single_line_when_no_reference': - # Q7 开关:默认 OFF;当前 Profile 显式开启时才使用——第一期所有客户 OFF - # 若未来启用,应当返回 bound_to_line → 1;本期保持 default_header_only 语义 - return ReservationRelationProjectionResult( - line_reference_basis=self.line_reference_basis, - resolution='default_header_only', - audit_chain=audit + [{'step': 'fallback_disabled_by_q7_default'}], - ) - return ReservationRelationProjectionResult( - line_reference_basis=self.line_reference_basis, - resolution='default_header_only', - audit_chain=audit, - ) diff --git a/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py b/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py new file mode 100644 index 00000000..f4b2e295 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/runtime_parse_strategy.py @@ -0,0 +1,244 @@ +""" +services/shipping_notice/document_layout/runtime_parse_strategy.py + +用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。 +依赖:仅标准库;由正式抽取与模板质量验证共同调用。 +逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Literal + + +RowMode = Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] +StrategyStatus = Literal['selected', 'needs_review'] + + +@dataclass(frozen=True) +class RuntimeParseStrategy: + """当前文档的临时解析计划,不写回 Profile 或改变后续 Candidate Gate。""" + + status: StrategyStatus + page_nos: tuple[int, ...] + row_mode: RowMode | None + reason_codes: tuple[str, ...] + + +def resolve_runtime_parse_strategy( + *, page_glyphs: dict[str, Any], fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]], + dynamic_rows: list[dict[str, Any]] | None = None, +) -> RuntimeParseStrategy: + """按页级证据与三种重建结果选择唯一安全策略。 + + Args: + page_glyphs: 当前 Layout 的页级坐标事实;空页不进入续页候选。 + fixed_rows: 固定子行重建结果。 + adaptive_rows: 自适应列重建结果。 + dynamic_rows: 不受静态表头排除区影响的动态 X 列重建结果。 + + Returns: + ``selected`` 时调用方只消费 ``row_mode`` 对应结果;关键行不同或均不可用时返回 + ``needs_review``,由既有 Route/Candidate Gate 阻断自动建单。 + """ + page_nos = tuple(sorted( + int(page_no) for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and int(page_no) > 0 and isinstance(glyphs, list) and glyphs + )) + fixed_valid = _valid_rows(fixed_rows) + adaptive_valid = _valid_rows(adaptive_rows) + dynamic_valid = _valid_rows(dynamic_rows or []) + baseline_rows: list[dict[str, Any]] = [] + baseline = None + if fixed_valid and not adaptive_valid: + baseline_rows = fixed_valid + baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + elif adaptive_valid and not fixed_valid: + baseline_rows = adaptive_valid + baseline = RuntimeParseStrategy( + 'selected', page_nos, 'adaptive_record_columns', + ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',), + ) + elif fixed_valid and adaptive_valid: + relation = _compare_row_field_completeness(fixed_valid, adaptive_valid) + if relation == 'fixed_preferred': + baseline_rows = fixed_valid + baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + elif relation == 'adaptive_preferred': + baseline_rows = adaptive_valid + baseline = RuntimeParseStrategy( + 'selected', page_nos, 'adaptive_record_columns', + ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',), + ) + elif relation == 'same': + baseline_rows = fixed_valid + baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ()) + else: + return RuntimeParseStrategy( + 'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',), + ) + if baseline is None and dynamic_valid: + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + if baseline is not None and dynamic_valid: + relation = _compare_dynamic_row_coverage( + baseline_rows=baseline_rows, dynamic_rows=dynamic_valid, + ) + if relation == 'dynamic_preferred': + return RuntimeParseStrategy( + 'selected', page_nos, 'dynamic_x_columns', + ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',), + ) + if relation == 'ambiguous': + return RuntimeParseStrategy( + 'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',), + ) + if baseline is not None: + return baseline + return RuntimeParseStrategy( + 'needs_review', page_nos, None, ('PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',), + ) + + +def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]: + """为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。 + + 历史 ``page_scope`` 仅描述样本标注页,不能要求管理员预判每份文件的续页。 + 当前页已有专属表区时只使用它;没有时复用首页/通用表区,后续仍由行重建结果 + 决定是否确实存在明细,避免把页面范围配置变成自动建单依据。 + """ + if page_no < 1: + return () + valid_regions = [ + region for region in table_regions + if isinstance(region, dict) and str(region.get('region_id') or '') + ] + exact = tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'exact_page' and region.get('page_no') == page_no + ) + if exact: + return exact + first_page = tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'first_page' + ) + if page_no == 1 and first_page: + return first_page + continuation = tuple( + str(region['region_id']) for region in valid_regions + if page_no > 1 and region.get('page_scope') == 'continuation_pages' + ) + if continuation: + return continuation + all_pages = tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'all_pages' + ) + if all_pages: + return all_pages + if first_page: + return first_page + return tuple( + str(region['region_id']) for region in valid_regions + if region.get('page_scope') == 'exact_page' and region.get('page_no') == 1 + ) + + +def _valid_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """只接受无 issue 的已解析行;不将预览或待复核候选当作可自动建单事实。""" + return [ + row for row in rows + if isinstance(row, dict) and row.get('status') == 'parsed' and not row.get('issues') + ] + + +def _business_row_identity(rows: list[dict[str, Any]]) -> tuple[tuple[tuple[str, str], ...], ...]: + """比较两种重建的完整业务字段,缺值也保留以避免静默视作相同。""" + result: list[tuple[tuple[str, str], ...]] = [] + for row in rows: + values = [ + (str(field.get('field_code') or ''), str(field.get('value') or '')) + for field in row.get('fields') or [] if isinstance(field, dict) + ] + result.append(tuple(sorted(values))) + return tuple(result) + + +def _compare_row_field_completeness( + fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]], +) -> Literal['fixed_preferred', 'adaptive_preferred', 'same', 'ambiguous']: + """比较两种重建的字段集合,允许一方仅缺失字段而不丢弃整条明细。 + + 只有对应行数量相同、重叠字段值一致,且所有行都呈现同一方向的字段超集关系时, + 才自动选择更完整的结果;任一字段值冲突或方向不一致都继续进入 Review。 + """ + if len(fixed_rows) != len(adaptive_rows): + return 'ambiguous' + directions: set[str] = set() + for fixed, adaptive in zip(fixed_rows, adaptive_rows): + fixed_fields = _row_fields(fixed) + adaptive_fields = _row_fields(adaptive) + shared = fixed_fields.keys() & adaptive_fields.keys() + conflicts = [code for code in shared if fixed_fields[code] != adaptive_fields[code]] + if conflicts: + # 坐标字段框是模板的权威边界。若 adaptive 只读到 fixed 值的 + # 前缀(典型的跨视觉行料号),完整的 fixed 值应胜出;真正的 + # 不同业务值仍保持 Review,避免把冲突静默吞掉。 + if all( + fixed_fields[code].startswith(adaptive_fields[code]) + and len(fixed_fields[code]) > len(adaptive_fields[code]) + for code in conflicts + ): + directions.add('fixed') + else: + return 'ambiguous' + if fixed_fields.keys() > adaptive_fields.keys(): + directions.add('fixed') + elif adaptive_fields.keys() > fixed_fields.keys(): + directions.add('adaptive') + if not directions: + return 'same' + if len(directions) == 1: + return 'fixed_preferred' if 'fixed' in directions else 'adaptive_preferred' + return 'ambiguous' + + +def _compare_dynamic_row_coverage( + *, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]], +) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']: + """仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。""" + if len(dynamic_rows) < len(baseline_rows): + return 'baseline_preferred' + remaining = [_row_fields(row) for row in dynamic_rows] + for baseline in baseline_rows: + baseline_fields = _row_fields(baseline) + matches = [] + for index, dynamic_fields in enumerate(remaining): + if not baseline_fields.keys() <= dynamic_fields.keys(): + continue + if all( + dynamic_fields[code] == value + or ( + dynamic_fields[code].startswith(value) + and len(dynamic_fields[code]) > len(value) + ) + for code, value in baseline_fields.items() + ): + matches.append(index) + if len(matches) != 1: + return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred' + remaining.pop(matches[0]) + return 'dynamic_preferred' if remaining else 'baseline_preferred' + + +def _row_fields(row: dict[str, Any]) -> dict[str, str]: + """将策略行字段规整为可比较映射;不引入业务字段白名单。""" + return { + str(field.get('field_code') or ''): str(field.get('value') or '') + for field in row.get('fields') or [] + if isinstance(field, dict) and str(field.get('field_code') or '') + } diff --git a/backend/app/services/shipping_notice/document_layout/source_merge_service.py b/backend/app/services/shipping_notice/document_layout/source_merge_service.py deleted file mode 100644 index ed215614..00000000 --- a/backend/app/services/shipping_notice/document_layout/source_merge_service.py +++ /dev/null @@ -1,342 +0,0 @@ -""" -services/shipping_notice/document_layout/source_merge_service.py - -用途:Q18 抽取层裁决——同一 conflict_group_key(scope/field_code/line_no)下的三来源候选 - 合并为最多一条「有效业务 Observation」,禁止同一 scope+line 下多个并列有效 - Observation(防止 compute_effective_reservation_id / 库存匹配 / 履约门禁 - / Excel/RPA 误取其中一个,或冲突被后续静默覆盖)。 -依赖:profile_field_source_mapping_service.FieldSourceCandidate。 -逻辑:严格三步骤(同值合并 → 空值互补 → 值冲突),满足: - ① merge 后只出一个有效 accepted(或 needs_review=无 accepted); - ② 始终保留 source_observations[] 事实快照放入 metadata; - ③ annotation_only / invalid_line_reference 的候选永不成为 accepted, - 只保留在 conflict_payload 里作为 Review 证据。 -输出:MergedObservationCandidate(直接落库前的 Observation 形状封装), - 由 runtime 层实际 SQLAlchemy insert。 -""" - -from __future__ import annotations - -from collections import defaultdict -from dataclasses import dataclass, field -from typing import Any, Literal - -from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import ( - FieldSourceCandidate, -) - - -SourceResolution = Literal[ - 'same_value_merged', # 多个来源值一致 - 'fill_missing', # 一个来源有值,另一来源为空 → 自动填补 - 'needs_review', # 同 scope+line 多来源值不一致 - 'no_value', # 所有来源均为空 → 本冲突组不生成有效 Observation - 'single_source_direct', # 只有一个来源有值,直接落 Observation - 'annotation_only_dropped', # 候选全是 annotation_only / invalid_line_reference -] - - -@dataclass -class SourceObservationSnapshot: - """source_observations[] 事实快照——Observation.metadata 直接序列化。""" - - source: Literal['header_region', 'table_column', 'vendor_comments'] - value: str - normalized_value: str - evidence_ref: str | None - evidence_quote: str | None - line_no_in_source: int | None - format_valid: bool | None - format_reason_code: str | None - extra: dict[str, Any] = field(default_factory=dict) - - -@dataclass -class MergedObservationCandidate: - """ - 合并后候选——最多一份(per conflict_group_key),由 runtime 层写数据库。 - - 【后端决定 UI】:accepted_value 为 None 时,说明该字段+行=必须 Review; - frontend 不能以『第一个 source value』为事实,必须展示 source_observations[]。 - """ - - target_scope: Literal['header', 'line'] - target_field_code: str - target_field_id: str - effective_line_no: int | None - accepted_value: str | None # needs_review/no_value 时为 None - decision_status: Literal['accepted', 'needs_review', 'blocked', 'missing'] - resolution: SourceResolution - source_observations: list[SourceObservationSnapshot] = field(default_factory=list) - conflicts: list[dict[str, Any]] = field(default_factory=list) - # 用于直接映射到 Observation 数据库表列 - evidence_quote: str | None = None - evidence_ref: str | None = None - evidence_metadata: dict[str, Any] = field(default_factory=dict) - # 用于 Observation.source_type / extractor(统一三来源来源标记) - source_type: str = 'profile_field_source_mapping' - extractor: str = 'merged_source_service.v1' - - @property - def should_persist_observation(self) -> bool: - """ - 有效 Observation 生成门禁: - 必须有 accepted_value;annotation_only/invalid 全 drop 时也不输出。 - """ - return self.accepted_value is not None and self.accepted_value != '' - - -class SourceMergeService: - """ - Q18 抽取层裁决服务(先对账再重试——三来源先对账)。 - - 【AI 触发时机】:ProfileFieldSourceMappingService.collect_candidates() 返回候选后, - 下一个函数调用必须是 merge_and_decide()。禁止上游在合并前直接挑一个 source 作为 Observation。 - - 执行顺序(同 conflict_group_key 内): - [STEP 1] 过滤 annotation_only / invalid_line_reference 候选(永不 accepted)。 - [STEP 2] 归一化所有来源 value(去空格、大小写、格式化残差)。 - [STEP 3] 同值合并 same_value_merged → accepted - [STEP 4] 空值互补 fill_missing(需 mapping.fill_missing_from_other_sources=True) - [STEP 5] 以上都不通过 → conflict_needs_review,accepted_value=None - """ - - def __init__(self, candidates: list[FieldSourceCandidate]): - self.candidates = list(candidates) - # 分组:(scope, field_code, line_no) → list[candidates] - self._groups: dict[tuple[Any, ...], list[FieldSourceCandidate]] = defaultdict(list) - for cand in self.candidates: - self._groups[cand.conflict_group_key].append(cand) - - # ------------------------------------------------------------------ - # 对外主入口 - # ------------------------------------------------------------------ - - def merge_and_decide(self) -> list[MergedObservationCandidate]: - """为每个 conflict_group_key 输出 0 或 1 个 MergedObservationCandidate。""" - merged: list[MergedObservationCandidate] = [] - for _key, group in self._groups.items(): - merged.append(self._merge_one_group(group)) - return merged - - # ------------------------------------------------------------------ - # 单组合并核心 - # ------------------------------------------------------------------ - - def _merge_one_group(self, group: list[FieldSourceCandidate]) -> MergedObservationCandidate: - first = group[0] - result = MergedObservationCandidate( - target_scope=first.target_scope, - target_field_code=first.target_field_code, - target_field_id=first.target_field_id, - effective_line_no=first.effective_line_no, - accepted_value=None, - decision_status='missing', - resolution='no_value', - ) - - # [STEP 1] 分离有效候选(排除 annotation_only / invalid) - qualified: list[FieldSourceCandidate] = [] - for cand in group: - snap = self._to_snapshot(cand) - result.source_observations.append(snap) - if cand.resolution_hint == 'provisional': - qualified.append(cand) - else: - # annotation_only / invalid_line_reference 作为 review 证据保留 - result.conflicts.append({ - 'resolution_hint': cand.resolution_hint, - 'source': cand.source, - 'value': cand.normalized_value or cand.value, - 'reason': ( - cand.format_reason_code - or cand.relation_projection.resolution - if cand.relation_projection else 'annotation_only' - ), - }) - - # 无 qualified → 直接 annotation_only_dropped / no_value - if not qualified: - if group: - result.resolution = 'annotation_only_dropped' - result.decision_status = 'blocked' - else: - result.resolution = 'no_value' - result.decision_status = 'missing' - result.evidence_metadata = self._finalize_metadata(result, resolution_meta={}) - return result - - # 只有一个 qualified 且非空 → single_source_direct - non_empty = [c for c in qualified if (c.normalized_value or c.value) != ''] - if len(qualified) == 1 and non_empty: - return self._finalize_single(result, qualified[0]) - if not non_empty: - result.resolution = 'no_value' - result.decision_status = 'missing' - result.evidence_metadata = self._finalize_metadata(result, {}) - return result - if len(non_empty) == 1: - return self._finalize_fill_missing(result, group, non_empty[0], qualified) - - # [STEP 3] 同值合并 same_value_merged - values = {(c.normalized_value or c.value) for c in non_empty} - if len(values) == 1: - return self._finalize_same_value(result, group, next(iter(values))) - - # [STEP 5] 冲突 → needs_review(多来源值不一致) - result.resolution = 'needs_review' - result.decision_status = 'needs_review' - result.accepted_value = None - for c in non_empty: - result.conflicts.append({ - 'source': c.source, - 'value': (c.normalized_value or c.value), - 'evidence_ref': c.evidence_ref, - 'format_valid': c.format_valid, - }) - result.evidence_metadata = self._finalize_metadata(result, {}) - return result - - # ------------------------------------------------------------------ - # 结局封装(保证 evidence_metadata 统一包含 source_observations / resolution) - # ------------------------------------------------------------------ - - def _finalize_single( - self, result: MergedObservationCandidate, cand: FieldSourceCandidate, - ) -> MergedObservationCandidate: - result.accepted_value = cand.normalized_value or cand.value - result.resolution = 'single_source_direct' - result.decision_status = 'accepted' - result.evidence_quote = cand.evidence_quote - result.evidence_ref = cand.evidence_ref - result.evidence_metadata = self._finalize_metadata( - result, - resolution_meta={ - 'accepted_source': cand.source, - 'format_valid': cand.format_valid, - 'format_reason_code': cand.format_reason_code, - }, - primary_candidate=cand, - ) - return result - - def _finalize_fill_missing( - self, result: MergedObservationCandidate, - group: list[FieldSourceCandidate], - winner: FieldSourceCandidate, - all_qualified: list[FieldSourceCandidate], - ) -> MergedObservationCandidate: - result.accepted_value = winner.normalized_value or winner.value - result.resolution = 'fill_missing' - result.decision_status = 'accepted' - result.evidence_quote = winner.evidence_quote - result.evidence_ref = winner.evidence_ref - missing = [ - {'source': c.source, 'reason': 'empty_source'} - for c in all_qualified - if (c.normalized_value or c.value) == '' - ] - result.evidence_metadata = self._finalize_metadata( - result, - resolution_meta={ - 'accepted_source': winner.source, - 'missing_sources': missing, - 'format_valid': winner.format_valid, - 'format_reason_code': winner.format_reason_code, - }, - primary_candidate=winner, - ) - return result - - def _finalize_same_value( - self, result: MergedObservationCandidate, - group: list[FieldSourceCandidate], shared_value: str, - ) -> MergedObservationCandidate: - # 多来源同值:evidence 选 format_valid=True 中来源排序靠前的 - # (vendor_comments 优先,因为有人工圈选证据点位更清晰) - source_priority = ['vendor_comments', 'table_column', 'header_region'] - ordered = sorted( - group, - key=lambda c: ( - 0 if (c.format_valid is not False and (c.normalized_value or c.value) == shared_value) else 1, - source_priority.index(c.source) if c.source in source_priority else 99, - ), - ) - primary = ordered[0] - result.accepted_value = shared_value - result.resolution = 'same_value_merged' - result.decision_status = 'accepted' - result.evidence_quote = primary.evidence_quote - result.evidence_ref = primary.evidence_ref - merged_sources = sorted({c.source for c in ordered if (c.normalized_value or c.value) == shared_value}) - result.evidence_metadata = self._finalize_metadata( - result, - resolution_meta={ - 'merged_from_sources': list(merged_sources), - 'format_valid': primary.format_valid, - 'format_reason_code': primary.format_reason_code, - }, - primary_candidate=primary, - ) - return result - - # ------------------------------------------------------------------ - # 帮助函数 - # ------------------------------------------------------------------ - - @staticmethod - def _to_snapshot(cand: FieldSourceCandidate) -> SourceObservationSnapshot: - return SourceObservationSnapshot( - source=cand.source, - value=cand.value, - normalized_value=cand.normalized_value, - evidence_ref=cand.evidence_ref, - evidence_quote=cand.evidence_quote, - line_no_in_source=cand.effective_line_no, - format_valid=cand.format_valid, - format_reason_code=cand.format_reason_code, - extra=dict(cand.evidence_metadata or {}), - ) - - @staticmethod - def _finalize_metadata( - result: MergedObservationCandidate, - resolution_meta: dict[str, Any], - primary_candidate: FieldSourceCandidate | None = None, - ) -> dict[str, Any]: - """ - 组装 Observation.evidence_metadata_json 最终结构(Q18 冻结形状): - { - "source_observations": [...], // 事实快照(永不丢) - "resolution": "same_value_merged", - "accepted_value": "...", - "conflicts": [ ... ], // 冲突或 annotation_only 项 - "resolution_meta": { ... }, // 来源细节 - "primary": { // 选主证据说明 - "source": "vendor_comments", "evidence_ref": "...", "line_no": 2 - } - } - """ - payload: dict[str, Any] = { - 'source_observations': [ - { - 'source': s.source, 'value': s.value, - 'normalized_value': s.normalized_value, - 'evidence_ref': s.evidence_ref, 'evidence_quote': s.evidence_quote, - 'line_no_in_source': s.line_no_in_source, - 'format_valid': s.format_valid, 'format_reason_code': s.format_reason_code, - 'extra': s.extra or {}, - } for s in result.source_observations - ], - 'resolution': result.resolution, - 'accepted_value': result.accepted_value, - 'conflicts': list(result.conflicts or []), - 'resolution_meta': resolution_meta or {}, - } - if primary_candidate is not None: - payload['primary'] = { - 'source': primary_candidate.source, - 'evidence_ref': primary_candidate.evidence_ref, - 'line_no': primary_candidate.effective_line_no, - } - return payload diff --git a/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py b/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py deleted file mode 100644 index 787acda5..00000000 --- a/backend/app/services/shipping_notice/document_layout/vc_source_candidate_conflicts.py +++ /dev/null @@ -1,195 +0,0 @@ -""" -services/shipping_notice/document_layout/vc_source_candidate_conflicts.py - -用途:从 ProfileFieldSourceMappingService + SourceMergeService 的运行结果 - 产出 Candidate 级冲突项,接入 candidate.conflicts_json。 -依赖: - - vc_source_gate_contract(冲突原因码、冲突项构造器)。 - - profile_field_source_mapping_service(三来源候选收集)。 - - source_merge_service(合并裁决 + needs_review 标记)。 - - candidate_service / ShippingOrderCandidate.structured_result_json(落库载体)。 -逻辑: - [STEP 1] 从 Candidate.structured_result_json 读三来源收集的原始快照; - 缺失(旧数据或未启用 VC Profile)时安全返回空列表,不阻断。 - [STEP 2] 扫描 merged_candidates,needs_review 且 conflict_group_key 未人工裁决 → - 构造 make_vc_candidate_conflict_item(severity=review_required)。 - [STEP 3] 扫描 format_valid=False 且 format_policy.inherit_global=False 的项 → - 独立原因码 vc_source_format_invalid,severity=blocking。 - [STEP 4] named_region_id 指向不存在区域 → vc_source_region_unbound。 - 幂等:同一 conflict_group_key 仅保留一项,合并 detail 不重复追加。 -""" - -from __future__ import annotations - -from typing import Any - -from app.services.shipping_notice.document_layout.vc_source_gate_contract import ( - CQ_REASON_VC_FORMAT_INVALID, - CQ_REASON_VC_REGION_UNBOUND, - CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, - CQ_VC_BLOCKING_REASONS, - CQ_VC_REVIEW_REASONS, - VC_SOURCE_KIND_LABELS, - make_vc_candidate_conflict_item, -) - -# CQ_VC_BLOCKING_REASONS / CQ_VC_REVIEW_REASONS 定义在 vc_source_gate_contract.py(契约层), -# 这里保留薄 re-export,供 candidate_qualification_service 等调用方按旧路径 import, -# 避免修改大量调用点时引入遗漏。 - - -_VC_CANDIDATE_KEY = 'vendor_comments_merged' -_VC_DETAIL_MAX = 8 # 单项 detail 保留最多 8 条来源快照,防止 JSON 膨胀。 - - -def _vc_merged_payload(candidate: Any) -> dict[str, Any] | None: - """ - 从 Candidate 提取 Vendor Comments merged payload。 - - 支持三条路径,按顺序: - 1) structured_result_json.extraction.vendor_comments_merged(新抽取路径) - 2) result_json.extraction.vendor_comments_merged(兼容 Worker 旧写入点) - 3) candidate_json.extraction.vendor_comments_merged(影子评估的替身 dict) - - 任一合法 dict 即返回,否则 None(缺路径视为未启用,安全放行)。 - """ - for attr in ('structured_result_json', 'result_json', 'candidate_json'): - try: - raw = getattr(candidate, attr, None) - except Exception: - raw = None - if isinstance(raw, dict): - ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None - if ext and isinstance(ext.get(_VC_CANDIDATE_KEY), dict): - return ext[_VC_CANDIDATE_KEY] - return None - - -def _conflict_group_key(scope: str, field_code: str, line_no: str | None) -> str: - """稳定冲突键:与 source_merge_service 的 (scope, field_code, line_no) 一致。""" - safe_scope = 'header' if scope == 'header' else 'line' - safe_line = str(line_no or '').strip() or '_' - return f'{safe_scope}:{str(field_code or "").strip()}:{safe_line}' - - -def _summarize_source_observations(cand: dict[str, Any]) -> list[dict[str, Any]]: - """ - 脱敏压缩 source_observations:仅保留 source / value 摘要 / evidence_ref,禁止存完整正文。 - """ - obs = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else [] - summary: list[dict[str, Any]] = [] - for raw in obs[:_VC_DETAIL_MAX]: - if not isinstance(raw, dict): - continue - summary.append({ - 'source': raw.get('source'), - 'source_label': VC_SOURCE_KIND_LABELS.get(str(raw.get('source') or ''), str(raw.get('source') or '')), - 'value_preview': (str(raw.get('value') or '')[:64] + ('…' if len(str(raw.get('value') or '')) > 64 else '')) if raw.get('value') is not None else None, - 'evidence_ref': raw.get('evidence_ref'), - }) - return summary - - -def collect_vc_candidate_conflicts(candidate: Any) -> list[dict[str, Any]]: - """ - 扫描 Vendor Comments 三来源合并结果,生成 Candidate 冲突项。 - - 【AI 触发时机】:当 Candidate Qualification 评估、STP 自动建单前 - 或复核工作台加载冲突列表时,追加本函数返回值到 Candidate.conflicts_json。 - - Args: - candidate: ShippingOrderCandidate ORM 对象或兼容 dict(替身)。 - - Returns: - 符合 vc_source_gate_contract.make_vc_candidate_conflict_item 契约的列表; - 无冲突或未启用 VC 时返回空列表(永不返回 None)。 - """ - payload = _vc_merged_payload(candidate) - if payload is None: - return [] - - merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else [] - named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {} - enabled = payload.get('field_source_mappings') if isinstance(payload.get('field_source_mappings'), dict) else {} - - # [STEP 0] 先校验 named_region 绑定:所有启用 vendor_comments 的 mapping 其 region_id 必须存在。 - seen_region_errors: set[str] = set() - items: list[dict[str, Any]] = [] - - for field_code, mapping in enabled.items(): - if not isinstance(mapping, dict): - continue - if not bool(mapping.get('vendor_comments_enabled')): - continue - rid = str(mapping.get('vendor_comments_named_region_id') or '').strip() - if rid and rid not in named_regions: - key = f'region_missing:{rid}:{field_code}' - if key in seen_region_errors: - continue - seen_region_errors.add(key) - scope_val = str(mapping.get('vendor_comments_target_scope') or mapping.get('target_scope') or 'line').strip() - scope = 'header' if scope_val == 'header' else 'line' - ckey = _conflict_group_key(scope, field_code, None) - items.append(make_vc_candidate_conflict_item( - reason=CQ_REASON_VC_REGION_UNBOUND, - scope=scope, # type: ignore[arg-type] - field_code=field_code, - conflict_group_key=ckey, - detail={'missing_region_id': rid}, - )) - - # [STEP 1] 扫描 merged_candidates:needs_review / format_invalid。 - seen_groups: set[str] = set() - for cand in merged: - if not isinstance(cand, dict): - continue - field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip() - if not field_code: - continue - scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip() - scope_ok = 'header' if scope == 'header' else 'line' - line_no_raw = cand.get('effective_line_no') or cand.get('line_no') - line_no_safe = None if line_no_raw is None else str(line_no_raw) - ckey = _conflict_group_key(scope_ok, field_code, line_no_safe) - - resolution = str(cand.get('resolution') or '').strip() - decision = str(cand.get('decision_status') or '').strip() - format_valid = cand.get('format_valid') - # 显式 False 视为非法(None 表示未启用格式策略,安全放行)。 - format_invalid = (format_valid is False) - conflict_pending = resolution == 'needs_review' and decision != 'dropped' - - if ckey in seen_groups: - continue - detail = { - 'resolution': resolution, - 'decision_status': decision, - 'format_valid': format_valid, - 'sources': _summarize_source_observations(cand), - } - if conflict_pending: - seen_groups.add(ckey) - line_key = str(cand.get('line_key') or '').strip() or None - items.append(make_vc_candidate_conflict_item( - reason=CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, - scope=scope_ok, # type: ignore[arg-type] - field_code=field_code, - line_key=line_key, - line_no=line_no_safe, - conflict_group_key=ckey, - detail=detail, - )) - elif format_invalid: - seen_groups.add(ckey) - line_key = str(cand.get('line_key') or '').strip() or None - items.append(make_vc_candidate_conflict_item( - reason=CQ_REASON_VC_FORMAT_INVALID, - scope=scope_ok, # type: ignore[arg-type] - field_code=field_code, - line_key=line_key, - line_no=line_no_safe, - conflict_group_key=ckey, - detail=detail, - )) - - return items diff --git a/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py b/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py deleted file mode 100644 index 54a6470f..00000000 --- a/backend/app/services/shipping_notice/document_layout/vc_source_evidence_integration.py +++ /dev/null @@ -1,230 +0,0 @@ -""" -services/shipping_notice/document_layout/vc_source_evidence_integration.py - -用途:将 Vendor Comments 三来源 source_observations 注入 ReviewEvidenceView, - 供 Chatflow LLM Review(Phase 4)与复核工作台(Phase 5)共享同一事实源。 -依赖: - - vc_source_gate_contract(VENDOR_COMMENTS_OBSERVATION_SOURCE、build_vc_evidence_ref、is_valid_vc_evidence_ref)。 - - order_review_llm_contract ObservationSource 兼容扩展(新增 source 不在原 frozenset 时 fail-open,不抛错)。 - - Candidate.structured_result_json.extraction.vendor_comments_merged(与 vc_source_candidate_conflicts.py 同一路径)。 -逻辑: - [STEP 1] 提取 VC merged payload(与 Candidate Conflicts 共享 _vc_merged_payload 逻辑,不双份)。 - [STEP 2] 对每个 merged_candidate,展开其 source_observations[]: - - 构造 evidence_ref(优先 vc: 区域引用,缺失时退化 build_evidence_ref layout:)。 - - source 固定 VENDOR_COMMENTS_OBSERVATION_SOURCE;子 source_kind 写入 metadata.source_kind。 - - 保留 quote(原文切片)、confidence、value_bbox。 - [STEP 3] 仅追加,不覆盖/替换原有 Unit/Draft/Frozen 三源证据。 - 幂等:同一 (evidence_ref, source_kind, value) 仅插入一条,避免 LLM 重复上下文。 -""" - -from __future__ import annotations - -from typing import Any - -from app.services.shipping_notice.document_layout.vc_source_gate_contract import ( - VENDOR_COMMENTS_OBSERVATION_SOURCE, - build_vc_evidence_ref, - is_valid_vc_evidence_ref, -) -from app.services.shipping_notice.order_review_llm_contract import ( - build_evidence_ref, - is_valid_evidence_ref, -) - - -def _vc_merged_payload(case_or_candidate: Any) -> dict[str, Any] | None: - """ - 从 ReviewCase(通过 candidate.structured)或直接 Candidate 提取 VC 载荷。 - - 与 vc_source_candidate_conflicts._vc_merged_payload 逻辑一致但独立实现, - 避免引入相互 import(两模块均零 circular 原则)。 - """ - # Case 路径:先取 candidate。 - candidate = getattr(case_or_candidate, 'candidate', None) - attrs_chain: list[Any] = [] - if candidate is not None: - attrs_chain.append(candidate) - attrs_chain.append(case_or_candidate) - for item in attrs_chain: - for attr in ('structured_result_json', 'result_json', 'candidate_json'): - try: - raw = getattr(item, attr, None) - except Exception: - raw = None - if isinstance(raw, dict): - ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None - if ext and isinstance(ext.get('vendor_comments_merged'), dict): - return ext['vendor_comments_merged'] - return None - - -def _safe_str(value: Any) -> str | None: - if value is None: - return None - text = str(value).strip() - return text or None - - -def _normalize_source_obs( - raw: dict[str, Any], - *, - case_document_id: int, - field_code: str | None, - line_key: str | None, - named_regions: dict[str, Any], -) -> dict[str, Any] | None: - """ - 将一条 source_observation 归一化为 ReviewEvidenceView.field_evidences 项形状。 - - 核心:evidence_ref 优先取 vc:region;若 source_kind=vendor_comments 且命中命名区域 - 但缺 page_no,回退从 named_regions[region_id] 取代表页号。 - """ - if not isinstance(raw, dict): - return None - source_kind = _safe_str(raw.get('source')) or 'header_region' - value = raw.get('value') - quote = _safe_str(raw.get('quote') or raw.get('raw_text')) - confidence_raw = raw.get('confidence') - try: - confidence = float(confidence_raw) if confidence_raw is not None else None - except (TypeError, ValueError): - confidence = None - - doc_raw = raw.get('document_id') or case_document_id - try: - doc_id = int(doc_raw) - except (TypeError, ValueError): - doc_id = int(case_document_id or 0) - - page_raw = raw.get('page_no') - try: - page_no = int(page_raw) if page_raw is not None else None - except (TypeError, ValueError): - page_no = None - - # Vendor Comments:若缺 page_no,按 named_regions[region_id].page_scope 推导代表页。 - rid = _safe_str(raw.get('region_id') or raw.get('named_region_id')) - if source_kind == 'vendor_comments' and page_no is None and rid and isinstance(named_regions.get(rid), dict): - region_def = named_regions[rid] - page_scope = _safe_str(region_def.get('page_scope')) or 'first_page' - exact = region_def.get('exact_page_no') or region_def.get('page_no') - if page_scope == 'last_page': - # last_page 未知实际页码时安全置 1,待后续有实际渲染页号再覆盖。 - page_no = page_no or 1 - elif page_scope == 'exact_page' and exact is not None: - try: - page_no = int(exact) - except (TypeError, ValueError): - page_no = page_no or 1 - else: - page_no = page_no or 1 - - evidence_ref: str | None = None - pre_ref = raw.get('evidence_ref') - if isinstance(pre_ref, str) and (is_valid_vc_evidence_ref(pre_ref) or is_valid_evidence_ref(pre_ref)): - evidence_ref = pre_ref.strip() - if not evidence_ref and source_kind == 'vendor_comments' and doc_id > 0 and page_no and rid: - evidence_ref = build_vc_evidence_ref(document_id=doc_id, page_no=page_no, region_id=rid) - if not evidence_ref and doc_id > 0 and page_no: - table_id = raw.get('table_id') if isinstance(raw.get('table_id'), str) else None - row_index = None - try: - ri = raw.get('row_index') - row_index = int(ri) if ri is not None else None - except (TypeError, ValueError): - row_index = None - evidence_ref = build_evidence_ref( - document_id=doc_id, - page_no=page_no, - table_id=table_id, - row_index=row_index, - field_code=field_code, - ) - - bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None - bbox_valid = ( - isinstance(bbox, dict) - and all(k in bbox for k in ('x0', 'y0', 'x1', 'y1')) - and 0.0 <= float(bbox['x0']) < float(bbox['x1']) <= 1.01 - and 0.0 <= float(bbox['y0']) < float(bbox['y1']) <= 1.01 - ) if bbox else False - - doc_match = bool(doc_id) and int(case_document_id or 0) > 0 and int(doc_id) == int(case_document_id) - value_bbox_dict = dict(bbox) if bbox_valid else None - - return { - 'value': value, - 'quote': quote, - 'source': VENDOR_COMMENTS_OBSERVATION_SOURCE, - 'source_kind': source_kind, - 'confidence': confidence, - 'evidence_ref': evidence_ref, - 'provenance_ref': None, # VC 来源直接走 evidence_ref,不伪装 draft provenance。 - 'document_id': doc_id, - 'page_no': page_no, - 'table_id': raw.get('table_id') if isinstance(raw.get('table_id'), str) else None, - 'cell_id': raw.get('cell_id') if isinstance(raw.get('cell_id'), str) else None, - 'row_index': None, # 行级由 line_key 外部关联,row_index 仅 layout table 使用。 - 'value_bbox': value_bbox_dict, - 'value_bbox_valid': bbox_valid, - 'document_matches_case': doc_match, - 'field_code': field_code, - 'line_key': line_key, - } - - -def collect_vc_field_evidences( - *, - case_or_candidate: Any, - case_document_id: int, -) -> list[dict[str, Any]]: - """ - 展开 Vendor Comments 三来源 source_observations 为 ReviewEvidenceView.field_evidences 条目。 - - 【AI 触发时机】: - - Phase 4:构建 LLM 最小证据上下文时,追加三来源引用与 quote; - - Phase 5:复核工作台加载 evidence 对照面板。 - - Args: - case_or_candidate: ShippingOrderReviewCase 或 ShippingOrderCandidate。 - case_document_id: 当前 Case 的主文档 document_id,用于 document_matches_case。 - - Returns: - 归一化 observation 列表;未启用 VC 或路径缺数据返回空列表。 - """ - payload = _vc_merged_payload(case_or_candidate) - if payload is None: - return [] - named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {} - merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else [] - - results: list[dict[str, Any]] = [] - seen: set[tuple[str, str, str]] = set() - for cand in merged: - if not isinstance(cand, dict): - continue - field_code = _safe_str(cand.get('target_field_code') or cand.get('field_code')) - line_key = _safe_str(cand.get('line_key')) - source_list = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else [] - for raw in source_list: - if not isinstance(raw, dict): - continue - norm = _normalize_source_obs( - raw, - case_document_id=int(case_document_id or 0), - field_code=field_code, - line_key=line_key, - named_regions=named_regions, - ) - if norm is None: - continue - key = ( - str(norm.get('evidence_ref') or ''), - str(norm.get('source_kind') or ''), - str(norm.get('value') or '')[:64], - ) - if key in seen: - continue - seen.add(key) - results.append(norm) - return results diff --git a/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py b/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py deleted file mode 100644 index c2d01f77..00000000 --- a/backend/app/services/shipping_notice/document_layout/vc_source_gate_contract.py +++ /dev/null @@ -1,204 +0,0 @@ -""" -services/shipping_notice/document_layout/vc_source_gate_contract.py - -用途:冻结 Vendor Comments 三来源的门禁枚举、证据引用格式、冲突原因码。 -依赖:零 I/O 纯契约模块,禁止 import 业务服务,避免 circular。 -逻辑: - - ObservationSource 新增 vendor_comments_region(与 order_review_llm_contract.py 对齐)。 - - evidence_ref 格式 vc:document_id:pN:region: 独立校验,禁止混入 layout: 前缀。 - - CQ 门禁新增 vc_source_merged_clean;原因码分「业务冲突」「格式不合法」「区域未绑定」三类。 - - 所有常量写入 frozenset/tuple,供 gate/preview/audit 三处共享,禁止双份维护。 -""" - -from __future__ import annotations - -import re -from typing import Any, Final, Literal - -# --------------------------------------------------------------------------- -# 三来源字段来源种类(与前端 vc.types.ts Section E VCFieldSourceKind 一一对应) -# --------------------------------------------------------------------------- -VC_SOURCE_KINDS: Final[frozenset[str]] = frozenset({ - 'header_region', - 'table_column', - 'vendor_comments', -}) -VC_SOURCE_KIND_LABELS: Final[dict[str, str]] = { - 'header_region': 'Header 区域', - 'table_column': '表身列', - 'vendor_comments': 'Vendor Comments', -} -VC_SOURCE_EVIDENCE_PRIORITY: Final[dict[str, int]] = { - # 优先级越大越优先;与 source_merge_service.py 证据选择顺序对齐。 - 'vendor_comments': 3, - 'table_column': 2, - 'header_region': 1, -} - -# --------------------------------------------------------------------------- -# 扩展 ObservationSource(与 order_review_llm_contract 原 4 类互不污染) -# --------------------------------------------------------------------------- -VENDOR_COMMENTS_OBSERVATION_SOURCE: Final[str] = 'vendor_comments_region' -ALL_OBSERVATION_SOURCES_WITH_VC: Final[frozenset[str]] = frozenset({ - 'unit_observation', - 'draft_observation', - 'frozen_layout', - 'text_fallback', - VENDOR_COMMENTS_OBSERVATION_SOURCE, -}) - -# --------------------------------------------------------------------------- -# VC 专用 evidence_ref:vc::p:region: -# 缺任意段即视为无效,不伪造占位。 -# --------------------------------------------------------------------------- -_VC_EVIDENCE_REF_RE = re.compile( - r'^vc:(?P\d+):p(?P\d+):region:(?P[A-Za-z0-9_\-]{1,128})$' -) - - -def is_valid_vc_evidence_ref(value: Any) -> bool: - """ - 校验 Vendor Comments evidence_ref 是否满足三段式契约。 - - 【AI 触发时机】:当需要将 VC 来源写入 Observation evidence_ref、 - 或 LLM 解析 quote 需要定位到命名区域时调用。 - - Args: - value: 待校验字符串。 - - Returns: - True 当且仅当正则命中且段值为正整数。 - """ - if not isinstance(value, str) or not value: - return False - matched = _VC_EVIDENCE_REF_RE.match(value.strip()) - if not matched: - return False - try: - doc = int(matched.group('doc')) - page = int(matched.group('page')) - except (TypeError, ValueError): - return False - return doc > 0 and page > 0 and bool(matched.group('region')) - - -def build_vc_evidence_ref( - *, - document_id: int | None, - page_no: int | None, - region_id: str | None, -) -> str | None: - """ - 按契约生成 VC evidence_ref;缺任意必需段返回 None,绝不伪造。 - - Args: - document_id: PDF 主键,>0。 - page_no: 代表页号,>0。 - region_id: NamedRegion.region_id,非空。 - - Returns: - 合法 vc: 引用或 None。 - """ - if not document_id or not page_no or not region_id: - return None - try: - doc_i = int(document_id) - page_i = int(page_no) - rid = str(region_id).strip() - except (TypeError, ValueError): - return None - if doc_i <= 0 or page_i <= 0 or not rid: - return None - ref = f'vc:{doc_i}:p{page_i}:region:{rid}' - return ref if is_valid_vc_evidence_ref(ref) else None - - -# --------------------------------------------------------------------------- -# Candidate Qualification 门禁:vc_source_merged_clean -# --------------------------------------------------------------------------- -CQ_GATE_VC_SOURCE_MERGED_CLEAN: Final[str] = 'vc_source_merged_clean' -CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED: Final[str] = 'vc_source_conflict_unresolved' -CQ_REASON_VC_FORMAT_INVALID: Final[str] = 'vc_source_format_invalid' -CQ_REASON_VC_REGION_UNBOUND: Final[str] = 'vc_source_region_unbound' -CQ_VC_BLOCKING_REASONS: Final[frozenset[str]] = frozenset({ - CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, - CQ_REASON_VC_FORMAT_INVALID, - CQ_REASON_VC_REGION_UNBOUND, -}) -# 归入 review_required(轻量人工确认)而非 hard-blocked 的原因。 -CQ_VC_REVIEW_REASONS: Final[frozenset[str]] = frozenset({ - CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED, -}) - -# --------------------------------------------------------------------------- -# 合并决议(与 SourceMergeService.resolution 对齐,前端只读不改) -# --------------------------------------------------------------------------- -VC_MERGE_RESOLUTIONS: Final[frozenset[str]] = frozenset({ - 'single_source_direct', - 'same_value_merged', - 'fill_missing', - 'needs_review', - 'annotation_only_dropped', - 'invalid_line_reference_dropped', -}) -VC_DECISION_STATUSES: Final[frozenset[str]] = frozenset({ - 'accepted', - 'pending', - 'dropped', -}) - -# --------------------------------------------------------------------------- -# 证据元数据键(与 Q18 metadata.shape 严格一致) -# --------------------------------------------------------------------------- -VC_EVIDENCE_META_KEYS: Final[frozenset[str]] = frozenset({ - 'source_observations', - 'resolution', - 'accepted_value', - 'conflicts', - 'resolution_meta', - 'primary', -}) - -# --------------------------------------------------------------------------- -# VC Candidate Qualification 冲突项 shape(用于 candidate.conflicts_json 列表项) -# --------------------------------------------------------------------------- -def make_vc_candidate_conflict_item( - *, - reason: str, - scope: Literal['header', 'line'], - field_code: str, - line_key: str | None = None, - line_no: str | None = None, - conflict_group_key: str, - detail: dict[str, Any] | None = None, -) -> dict[str, Any]: - """ - 构造符合 CQ 契约的 Vendor Comments 冲突项。 - - 核心逻辑:reason 必须来自 CQ_VC_BLOCKING_REASONS; - conflict_group_key 用于幂等去重(同组多次评估只记一条)。 - - Args: - reason: 原因码,限 CQ_VC_BLOCKING_REASONS。 - scope: header / line。 - field_code: 订单字段,如 reservation_id。 - line_key: line scope 时的逻辑行键,header 为 None。 - line_no: 原始明细号字符串,便于审计。 - conflict_group_key: (scope, field_code, line_no) 稳定键。 - detail: 三来源 values / source_observations 快照,不含正文大对象。 - - Returns: - candidate.conflicts_json 列表中的一项字典。 - """ - safe_reason = reason if reason in CQ_VC_BLOCKING_REASONS else CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED - return { - 'kind': 'vc_source', - 'reason': safe_reason, - 'severity': 'review_required' if safe_reason in CQ_VC_REVIEW_REASONS else 'blocking', - 'scope': scope, - 'field_code': field_code, - 'line_key': line_key, - 'line_no': line_no, - 'conflict_group_key': conflict_group_key, - 'detail': dict(detail or {}), - } diff --git a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py index c5c82bc5..4dc63539 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_contract.py @@ -63,6 +63,7 @@ XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3 XfaSplitHandling = Literal['mapped', 'evidence_only'] XfaSplitMatcherType = Literal['position', 'prefix', 'regex'] +XfaSplitPostProcessorType = Literal['prefix'] XfaSplitSourceScope = Literal['header', 'line'] XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review'] XfaSplitDuplicatePolicy = Literal['needs_review'] @@ -170,6 +171,28 @@ class XfaSplitSegment(BaseSplitSegment): return self +class XfaSplitPostProcessor(XfaContractModel): + """位置/正则命中后的受限二次取值器,当前仅支持从标签后提取值。""" + + type: XfaSplitPostProcessorType + value: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH) + separators: list[str] = Field(default_factory=lambda: [':', ':']) + case_sensitive: bool = False + + @model_validator(mode='after') + def validate_prefix_shape(self) -> 'XfaSplitPostProcessor': + """标签和分隔符均为受限静态文本,避免引入脚本式 pipeline。""" + value = str(self.value or '').strip() + separators = [str(item) for item in (self.separators or []) if str(item)] + if not value: + raise ValueError('prefix post processor requires non-empty value') + if not separators: + raise ValueError('prefix post processor requires at least one separator') + object.__setattr__(self, 'value', value) + object.__setattr__(self, 'separators', separators) + return self + + class XfaSplitMatcher(BaseSplitMatcher): """ 单行匹配器:position / prefix / regex。 @@ -185,6 +208,7 @@ class XfaSplitMatcher(BaseSplitMatcher): case_sensitive: bool = False pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH) capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS) + post_processors: list[XfaSplitPostProcessor] = Field(default_factory=list, max_length=1) @model_validator(mode='after') def validate_matcher_shape(self) -> 'XfaSplitMatcher': diff --git a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py index 3d395d3c..ec5ac6b7 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_split_rule_engine.py @@ -27,6 +27,7 @@ from app.services.shipping_notice.document_layout.field_split_core import ( ) from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue from app.services.shipping_notice.document_layout.xfa_split_rule_contract import ( + XfaSplitPostProcessor, XfaSplitRuleSet, ) @@ -139,6 +140,56 @@ def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult: ) +def _apply_prefix_post_processor(value: str, processor: XfaSplitPostProcessor) -> str | None: + """从已定位行中提取指定标签及分隔符后的值;未命中必须显式进入复核。""" + source = str(value or '') + comparable = source if processor.case_sensitive else source.lower() + label = processor.value if processor.case_sensitive else processor.value.lower() + start = comparable.find(label) + if start < 0: + return None + tail_start = start + len(label) + tail = source[tail_start:] + for separator in processor.separators: + if tail.startswith(separator): + return tail[len(separator):].strip() + return None + + +def _apply_xfa_post_processors( + result: XfaSplitEngineResult, + *, + rule_set: XfaSplitRuleSet, +) -> XfaSplitEngineResult: + """对已由正式 matcher 定位的行执行受限后处理,并重新聚合正式字段。""" + rules = {rule.rule_id: rule for rule in rule_set.rules} + mapped_fields: dict[str, str] = {} + needs_review = result.status == 'needs_review' + for segment in result.segments: + rule = rules.get(segment.rule_id) + for processor in (rule.matcher.post_processors if rule else []): + extracted = _apply_prefix_post_processor(segment.normalized_text, processor) + if extracted is None: + segment.normalized_text = '' + segment.status = 'needs_review' + needs_review = True + result.diagnostics.append(XfaSplitDiagnostic( + code='post_processor_no_match', + message=f'Rule {segment.rule_id} post processor did not match the selected line', + line_no=segment.line_no, + field_code=segment.target_field_code, + rule_ids=[segment.rule_id], + )) + break + segment.normalized_text = extracted + if segment.handling == 'mapped' and segment.target_field_code: + mapped_fields[segment.target_field_code] = segment.normalized_text + result.mapped_fields = mapped_fields + if needs_review: + result.status = 'needs_review' + return result + + # --------------------------------------------------------------------------- # 对外执行入口——签名 100% 不变 # --------------------------------------------------------------------------- @@ -177,7 +228,7 @@ def execute_split_rule_set( rule_set=rule_set, lines=lines, ) - return _core_result_to_xfa(core_result) + return _apply_xfa_post_processors(_core_result_to_xfa(core_result), rule_set=rule_set) def execute_split_on_leaf( diff --git a/backend/app/services/shipping_notice/document_profile_quality_service.py b/backend/app/services/shipping_notice/document_profile_quality_service.py index 3935dcbf..2d753d23 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -16,7 +16,7 @@ from decimal import Decimal from typing import Any from app import db -from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingDocumentProfileTestRun, ShippingDocumentProfileTestSample, @@ -30,13 +30,18 @@ from app.models import ( ShippingOrderDocumentProfileSample, ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid -from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot +from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot, _hydrate_coordinate_evidence from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile -from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows +from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + coordinate_profile_character_candidates, + reconstruct_coordinate_profile_rows, reconstruction_exclusion_regions, + reconstruct_coordinate_profile_rows_with_strategy, +) +from app.services.shipping_notice.document_layout.runtime_parse_strategy import resolve_runtime_parse_strategy from app.services.shipping_notice.document_layout.order_field_extraction import ( _is_placeholder_anchor_text, extract_order_fields, ) -from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence +from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter from app.services.shipping_notice.order_document_profile_service import ( @@ -44,6 +49,10 @@ from app.services.shipping_notice.order_document_profile_service import ( _normalize_definition, _require_schema_version, ) from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value +from app.services.shipping_notice.reservation_region import ( + apply_reservation_region_candidates, + extract_reservation_from_region_text, +) # 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、 @@ -126,109 +135,50 @@ def _table_html(document_id: int, table_id: str) -> str: raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') -def _coordinate_table_available(document_id: int, table_id: str) -> bool: - """确认 v2 盲测有冻结页面尺寸和目标表的字符证据,不要求 MinerU HTML。""" - document = db.session.get(ShippingOrderDocument, int(document_id)) - layout = current_layout_snapshot(document) if document is not None else {} - raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)), None) - evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {} - return bool( - isinstance(raw_table, dict) - and isinstance((evidence.get('tables') or {}).get(str(table_id)), list) - and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or '')), dict) - ) - - -def _recover_coordinate_table_for_preview( - *, document: ShippingOrderDocument, layout: dict[str, Any], raw_table: dict[str, Any], table_id: str, -) -> dict[str, Any]: - """仅为盲测复核临时恢复表格及整页坐标,不写回冻结布局或正式解析输入。""" - recovered = ensure_on_demand_coordinate_evidence( - document=document, layout=layout, - page_nos={int(raw_table.get('page_no') or 1)}, - table_by_page={int(raw_table.get('page_no') or 1): raw_table}, - ) - evidence = recovered.get('coordinate_evidence') if isinstance(recovered.get('coordinate_evidence'), dict) else {} - if ( - isinstance((evidence.get('tables') or {}).get(str(table_id)), list) - and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or 1)), dict) - ): - return recovered +def _coordinate_table_available_in_layout(layout: dict[str, Any], *, table_id: str, page_no: int) -> bool: + """判断运行期布局是否已有目标表与页面坐标证据。""" evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} - tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} - pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} - page_no = str(raw_table.get('page_no') or 1) - page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - page_sources = (evidence.get('sources') or {}).get('pages') if isinstance(evidence.get('sources'), dict) else {} - if ( - isinstance(tables.get(table_id), list) - and isinstance(pages.get(page_no), dict) - and isinstance(page_glyphs.get(page_no), list) - and str((page_sources or {}).get(page_no) or '') in {'pdf_coordinate', 'ocr_coordinate'} - ): - return layout - if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): - return layout - try: - from app.models import FileAsset - from app.services.file_assets.service import read_asset_bytes - from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages - from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines - from app.services.shipping_notice.order_document_profile_service import ( - _native_characters_in_table, _ocr_lines_to_characters, _ocr_lines_to_page_characters, - ) - - asset = db.session.get(FileAsset, document.asset_id) - if asset is None: - return layout - page = next( - item for item in extract_native_pdf_pages(read_asset_bytes(asset)) - if item.page_no == int(raw_table.get('page_no') or 0) - ) - native_characters = list(getattr(page, 'characters', []) or []) - full_page_characters = [item.model_dump(mode='json') for item in native_characters] - source = 'pdf_coordinate' - characters = _native_characters_in_table( - characters=native_characters, table_bbox=raw_table.get('bbox') or {}, - ) - if not characters: - ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height) - full_page_characters = _ocr_lines_to_page_characters(lines=ocr_lines) - characters = _ocr_lines_to_characters(lines=ocr_lines, table_bbox=raw_table.get('bbox') or {}) - source = 'ocr_coordinate' - if not characters or not full_page_characters: - return layout - next_layout = dict(layout) - next_evidence = dict(evidence) - next_evidence['tables'] = {**tables, table_id: characters} - next_evidence['pages'] = { - **pages, str(page.page_no): {'width': page.width, 'height': page.height}, - } - next_evidence['page_glyphs'] = {**page_glyphs, str(page.page_no): full_page_characters} - sources = dict(evidence.get('sources') or {}) - sources['pages'] = {**dict(sources.get('pages') or {}), str(page.page_no): source} - next_evidence['sources'] = sources - next_layout['coordinate_evidence'] = next_evidence - return next_layout - except Exception: - return layout + return bool( + isinstance((evidence.get('tables') or {}).get(str(table_id)), list) + and isinstance((evidence.get('pages') or {}).get(str(page_no)), dict) + ) def _region_characters_for_quality( *, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], table_id: str, ) -> list[dict[str, Any]] | None: - """为盲测按模板显式策略选取冻结字符;旧模板始终沿用表格局部证据。""" - table_characters = (evidence.get('tables') or {}).get(str(table_id)) - if getattr(region, 'row_reconstruction_mode', 'fixed_subrows') != 'adaptive_record_columns': - return table_characters if isinstance(table_characters, list) else None + """为盲测选择当前页字符,确保与编辑器预览和正式解析共用同一输入事实。""" page_no = str(raw_table.get('page_no') or 1) page_characters = (evidence.get('page_glyphs') or {}).get(page_no) if isinstance(page_characters, list): return page_characters - # 冻结快照仍可能来自升级前的证据结构;保持该模板原有表格证据可读。 + # 旧冻结快照可能没有页级坐标;仅在该事实缺失时回退当前物理表的字符。 + table_characters = (evidence.get('tables') or {}).get(str(table_id)) return table_characters if isinstance(table_characters, list) else None +def _quality_page_characters( + *, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], page_no: int, +) -> list[dict[str, Any]] | None: + """按表格实例隔离盲测行证据,禁止后续页重复消费首页 table glyphs。""" + table_page_no = int(raw_table.get('page_no') or 1) + if page_no == table_page_no: + return _region_characters_for_quality( + region=region, evidence=evidence, raw_table=raw_table, + table_id=str(raw_table.get('table_id') or ''), + ) + continuation = getattr(region, 'continuation_rule', None) + allow_cross_page = bool( + continuation.get('allow_cross_page') + if isinstance(continuation, dict) + else getattr(continuation, 'allow_cross_page', False) + ) + if not allow_cross_page: + return None + page_glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no)) + return page_glyphs if isinstance(page_glyphs, list) else None + + def _ensure_order_field_evidence( *, document: ShippingOrderDocument, layout: dict[str, Any], parser: OrderCoordinateProfile, ) -> dict[str, Any]: @@ -396,7 +346,9 @@ def _candidate_for_sample( 'Blind-test preview layout changed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE', ) - layout = dict(frozen_version.payload_json) if frozen_version is not None else ( + layout = _hydrate_coordinate_evidence( + payload=dict(frozen_version.payload_json), document=document, + ) if frozen_version is not None and document is not None else ( current_layout_snapshot(document) if document is not None else None ) is_document_candidate = str(table_id) == DOCUMENT_CANDIDATE_TABLE_ID @@ -409,21 +361,9 @@ def _candidate_for_sample( # 失败版本不会成为“当前成功快照”,但文档级盲测仍需以其安全元数据 # 为起点从原文件临时恢复坐标;这里不把失败布局提升为正式快照。 layout = dict(document.current_layout_version.payload_json) - if document is None: - raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') - if is_document_candidate and not layout: - # 上传与复核解耦后,后台 Layout 可能仍为 queued/running 且尚无 payload。 - # 文档级候选从安全空骨架进入现有原 PDF 按需恢复链,不等待、不取消也不写回后台任务。 - layout = {'status': 'pending', 'tables': [], 'issues': []} - if not layout: + if document is None or not layout: raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') if isinstance(parser, OrderCoordinateProfile): - if is_document_candidate: - # [STEP 1] MinerU 未产出表格时,盲测仍以原文件字符坐标运行当前模板; - # 证据只驻留本次调用,绝不写回布局或改变生产模板命中输入。 - layout = ensure_on_demand_coordinate_evidence( - document=document, layout=layout, page_nos=None, - ) layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser) schema_fields = { str(item.get('field_id') or ''): item @@ -435,20 +375,12 @@ def _candidate_for_sample( item for item in layout.get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id) ), None) - if isinstance(raw_table, dict) and frozen_version is None: - layout = _recover_coordinate_table_for_preview( - document=document, layout=layout, raw_table=raw_table, table_id=str(table_id), - ) evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} - if ( - not is_document_candidate - and not _coordinate_table_available(document_id, table_id) - and not isinstance((evidence.get('tables') or {}).get(str(table_id)), list) - ): + if not isinstance((evidence.get('tables') or {}).get(str(table_id)), list): raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} - if is_document_candidate and not any(isinstance(value, list) and value for value in page_glyphs.values()): + if not any(isinstance(value, list) and value for value in page_glyphs.values()): raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') rows: list[dict[str, Any]] = [] for region in parser.table_regions: @@ -456,19 +388,14 @@ def _candidate_for_sample( # layout. They are valid template regions, but cannot reconstruct rows. if not region.line_layouts: continue - if is_document_candidate: - eligible_pages = [ - int(page_no) for page_no in pages - if str(page_no).isdigit() - and ( - region.page_scope == 'all_pages' - or (region.page_scope == 'first_page' and int(page_no) == 1) - or (region.page_scope == 'continuation_pages' and int(page_no) > 1) - or (region.page_scope == 'exact_page' and int(page_no) == region.page_no) - ) - ] - else: - eligible_pages = [int(raw_table.get('page_no') or 1)] if isinstance(raw_table, dict) else [] + # ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中 + # 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。 + eligible_pages = [ + int(page_no) for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs + ] + if not eligible_pages and isinstance(raw_table, dict): + eligible_pages = [int(raw_table.get('page_no') or 1)] for page_no in sorted(eligible_pages): page = pages.get(str(page_no)) if not isinstance(page, dict): @@ -477,31 +404,115 @@ def _candidate_for_sample( table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])} except (KeyError, TypeError, ValueError): continue - characters = ( - page_glyphs.get(str(page_no)) - if is_document_candidate - else _region_characters_for_quality( - region=region, evidence=evidence, raw_table=raw_table, table_id=str(table_id), + if is_document_candidate: + characters = page_glyphs.get(str(page_no)) + elif not isinstance(raw_table, dict): + characters = None + else: + characters = _quality_page_characters( + region=region, evidence=evidence, raw_table=raw_table, page_no=page_no, ) + candidate_table_bbox = raw_table.get('bbox') if isinstance(raw_table, dict) and page_no == int(raw_table.get('page_no') or 1) else None + characters, _candidate_page_bbox = coordinate_profile_character_candidates( + table_region=region.region.model_dump(), page_size=page, + reference_page_frame=( + region_frame.model_dump() + if (region_frame := parser.reference_page_frames.get(page_no)) is not None else None + ), + page_characters=characters if isinstance(characters, list) else None, + table_characters=(evidence.get('tables') or {}).get(str(raw_table.get('table_id') or '')) if isinstance(raw_table, dict) else None, + raw_table_bbox=candidate_table_bbox, + table_id=str(raw_table.get('table_id') or '') if isinstance(raw_table, dict) else None, + page_no=page_no, + allow_table_fallback=( + isinstance(raw_table, dict) + and page_no == int(raw_table.get('page_no') or 1) + ), ) if not isinstance(characters, list): continue - rows.extend(item.fields for item in reconstruct_coordinate_profile_rows( - characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox, + # 表头布局只描述列语义和预览高亮,不能作为静态删除区;否则单头高度变化时 + # 会在起行锚点识别前误删首条明细字符。仅应用管理员明确配置的普通排除区。 + reconstruction_exclusions = reconstruction_exclusion_regions(region.model_dump()) + reconstruction_table_bbox = ( + { + 'x0': 0, 'y0': 0, + 'x1': region_frame.width, 'y1': region_frame.height, + } + if region_frame is not None else table_bbox + ) + chosen_rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_table_bbox, line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(), termination_rules=[item.model_dump() for item in region.termination_rules], - exclusion_regions=[item.model_dump() for item in region.exclusion_regions], + exclusion_regions=reconstruction_exclusions, + dynamic_exclusion_regions=reconstruction_exclusions, line_start_field_code=region.line_start_field_code, - row_reconstruction_mode=region.row_reconstruction_mode, - ) if not item.issues) + schema_field_metadata=list(schema_fields.values()), + ) + if strategy.status == 'selected': + rows.extend(item.fields for item in chosen_rows if not item.issues) order_fields = [ { 'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status, 'field_id': item.field_id, 'scope': item.scope, 'page_no': item.page_no, 'issues': list(item.issues), } - for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence) + for item in extract_order_fields( + profile=parser, + schema_fields=schema_fields, + coordinate_evidence=evidence, + allow_fixed_region_confirmation=True, + ) ] + # 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。 + profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + reservation_region = profile_definition.get('reservation_id_region') + if isinstance(reservation_region, dict): + region = reservation_region.get('region') + try: + reservation_page_no = int(reservation_region.get('page_no') or 0) + except (TypeError, ValueError): + reservation_page_no = 0 + if isinstance(region, dict) and reservation_page_no > 0: + layout = _ensure_page_coordinate_evidence( + document=document, layout=layout, page_no=reservation_page_no, + ) + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page = (evidence.get('pages') or {}).get(str(reservation_page_no)) + glyphs = (evidence.get('page_glyphs') or {}).get(str(reservation_page_no)) + if isinstance(page, dict) and isinstance(glyphs, list): + candidates = extract_reservation_from_region_text( + read_coordinate_region_text(glyphs=glyphs, page=page, region=region), + ) + reservation_fields = { + str(field.get('scope') or ''): field + for field in schema_fields.values() + if str(field.get('field_code') or '') == 'reservation_id' + } + applied = apply_reservation_region_candidates( + candidates=candidates, + header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None, + line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None, + line_count=len(rows), + ) + if applied.header_value and reservation_fields.get('header'): + header = reservation_fields['header'] + order_fields.append({ + 'field_code': str(header.get('field_code') or ''), 'value': applied.header_value, + 'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header', + 'page_no': reservation_page_no, 'issues': [], + }) + if reservation_fields.get('line'): + for line_no, value in applied.line_values.items(): + if isinstance(rows[line_no - 1], dict): + rows[line_no - 1]['reservation_id'] = value + if applied.needs_review: + return { + 'document_id': document.id, 'table_id': str(table_id), 'rows': rows, + 'order_fields': order_fields, 'reservation_region_status': 'needs_review', + 'reservation_region_review_reasons': list(applied.review_reasons), + } return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields} raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') @@ -562,7 +573,7 @@ def _common_blind_sample_descriptors( layout_version = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by( ShippingDocumentLayoutVersion.version.desc(), ShippingDocumentLayoutVersion.id.desc(), ).first() - layout = dict(layout_version.payload_json) if layout_version is not None and isinstance(layout_version.payload_json, dict) else {} + layout = current_layout_snapshot(document) or {} tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] if ( layout_version is None or layout_version.status != 'ready' @@ -595,7 +606,9 @@ def _common_blind_sample_descriptors( except ValidationError: continue header_preview = [slot.text for slot in (grid.rows[0] if grid.rows else []) if slot is not None and slot.text][:3] - coordinate_evidence_ready = _coordinate_table_available(document.id, table_id) + coordinate_evidence_ready = _coordinate_table_available_in_layout( + layout, table_id=table_id, page_no=int(table.get('page_no') or 1), + ) descriptors.append({ 'document_id': document.id, 'table_id': table_id, 'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '', @@ -634,6 +647,11 @@ def _compare_blind_candidate( failures: list[str] = [] total = 0 matched = 0 + if candidate.get('reservation_region_status') == 'needs_review': + failures.extend([ + f'reservation_region:{reason}' + for reason in candidate.get('reservation_region_review_reasons') or ['needs_review'] + ]) for field in candidate.get('order_fields') or []: if not isinstance(field, dict): continue @@ -820,7 +838,7 @@ def _prepare_common_blind_sample( or not isinstance(version.payload_json, dict) ): raise ConflictError('Blind-test preview layout changed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE') - layout = dict(version.payload_json) + layout = _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document) raw_table = next(( item for item in layout.get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id) @@ -1084,11 +1102,6 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: or last_run.status != 'passed' or last_run.profile_checksum != _quality_checksum(profile) ): raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY') - if int(actor_id) == int(suite.created_by_id): - raise ForbiddenError( - 'Editor cannot approve own blind test suite', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY', - ) suite.status = 'approved' # A coordinate-template approval is also its publish-quality credential. # Validate the remaining publish prerequisites before committing approval so diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py index c8b6f1eb..fad92a0a 100644 --- a/backend/app/services/shipping_notice/duplicate_detection.py +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -41,7 +41,7 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}: return 'closed' upload = str(get('upload_status', '') or '').strip().lower() - if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no') or get('upload_receipt_json'): + if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'): return 'completed' return 'active' diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index d57ea5eb..2babdf63 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -566,10 +566,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'), 'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'), 'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'), - 'inventory_rpa_timeout': _meta('worker', 'retry_inventory_preparation', 'RPA 执行超时'), + 'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'), 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), - 'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'), + 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), 'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), @@ -583,7 +583,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'), 'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'), 'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'), - 'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并登记结果'), + 'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并确认已上传'), 'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'), 'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'), 'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'), @@ -601,7 +601,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'), 'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'), 'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'), - 'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '缺少上传回执,暂不可关闭'), + 'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '尚未确认已上传,暂不可关闭'), 'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'), 'excel_downloaded': _meta('owner', '', '已下载发货 Excel'), 'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'), diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index f4e69084..881f86f9 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -24,9 +24,11 @@ from openpyxl import load_workbook from openpyxl.cell.cell import MergedCell from sqlalchemy import func from app import db +from app.core.errors import ConflictError from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, + ShippingNoticeLine, ShippingInventoryField, ShippingInventorySource, ShippingOrderSnapshot, @@ -37,6 +39,31 @@ from app.path_utils import resolve_backend_relative_path from app.services.file_assets.storage import file_asset_storage +def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None: + """ + 确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。 + + Args: + task: 当前发货通知单。 + + Raises: + ConflictError: 已存在任意导出 Artifact;后续库存必须创建新的发货通知单。 + """ + if task.id is None: + return + existing = ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first() + if existing is not None: + raise ConflictError( + 'A shipping notice can generate only one Excel artifact', + code='SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED', + details={ + 'task_no': task.task_no, + 'business_no': task.business_no, + 'artifact_no': existing.artifact_no, + }, + ) + + def _storage_root() -> Path: """返回发货通知文件根目录。""" configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip() @@ -45,8 +72,22 @@ def _storage_root() -> Path: return Path(current_app.instance_path) / 'shipping_notice' +def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice: + """后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。""" + if notice.order_snapshot_id: + return notice + if notice.order_task_id: + source = ShippingNotice.query.filter( + ShippingNotice.order_task_id == int(notice.order_task_id), + ShippingNotice.order_snapshot_id.isnot(None), + ).order_by(ShippingNotice.id.asc()).first() + if source is not None: + return source + return notice + + def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]: - """从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。""" + """从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。""" from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked assert_task_not_supersession_blocked(task) snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None @@ -62,19 +103,10 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None: - """生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。""" - case = task.shipping_case - if case is None or not case.business_no: - return None - business_no = str(case.business_no).strip() - prefix = business_no[:-8] if len(business_no) > 8 else business_no - sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else '' - if not sequence and case.sequence_value: - sequence = f'{int(case.sequence_value):02d}' - if not sequence: - return None - export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date() - return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}' + """返回当前发货通知单编号;履约路径不回退到其他聚合标识。""" + if task.business_no: + return str(task.business_no).strip() + return None def _clear_template_data_rows(ws: Any, start_row: int) -> None: @@ -92,6 +124,7 @@ def _system_fact( *, export_sequence: int | None = None, excel_business_no: str | None = None, + notice_no: str | None = None, export_date: date | None = None, ) -> Any: """ @@ -106,8 +139,8 @@ def _system_fact( 对应系统事实值;未知键返回 None。 """ values = { - 'task_no': task.task_no, - 'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None), + 'task_no': notice_no or task.task_no, + 'business_no': notice_no or excel_business_no or task.business_no, 'warehouse_id': task.inventory_warehouse_id, 'inventory_source_code': task.inventory_source_code, 'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(), @@ -160,6 +193,7 @@ def _mapping_value( mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any], header_values: dict[str, Any] | None = None, export_sequence: int | None = None, excel_business_no: str | None = None, + notice_no: str | None = None, export_date: date | None = None, ) -> Any: """ @@ -196,6 +230,7 @@ def _mapping_value( task, key, export_sequence=export_sequence if key == 'export_sequence' else None, excel_business_no=excel_business_no, + notice_no=notice_no, export_date=export_date, ) if key == 'export_sequence' and value is None: @@ -393,6 +428,7 @@ def _filename( template: ShippingExcelTemplate, *, excel_business_no: str | None = None, + notice_no: str | None = None, ) -> str: """按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。""" pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip() @@ -401,16 +437,15 @@ def _filename( if not pattern: raise ValueError('发货 Excel 文件名规则未配置') now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S') - shipping_case = task.shipping_case values = { - 'task_no': task.task_no, - 'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no), + 'task_no': notice_no or task.task_no, + 'business_no': notice_no or excel_business_no or task.business_no or task.task_no, 'source_code': task.inventory_source_code or '', 'ts': now, 'date': now[:8], - 'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '', - 'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '', - 'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '', + 'customer_short_code': task.customer_short_code_snapshot or '', + 'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '', + 'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '', } try: return _safe_filename(pattern.format(**values)) @@ -422,6 +457,7 @@ def _input_checksum( task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate, snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], + notice_id: int | None = None, ) -> str: """以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。""" payload = { @@ -430,12 +466,15 @@ def _input_checksum( 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id, 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, + 'notice_id': notice_id, } raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) return hashlib.sha256(raw.encode('utf-8')).hexdigest() -def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExportArtifact]: +def generate_shipment_excel( + task: ShippingNotice, +) -> tuple[str, str, ShippingExportArtifact]: """ 按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。 【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。 @@ -445,56 +484,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp Raises: ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。 - AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。 + AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。 """ from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked - from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch - from app.core.errors import AppError if not task_is_active(task): raise ValueError('已作废或归档的任务不能生成发货 Excel') assert_task_not_supersession_blocked(task) - # [T6 E2 硬门禁] 生成 Excel 前复用库存满足性判定:每行须库存充足, - # 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。 - if task.id is not None: - pending_rows = db.session.query( - ShippingNoticeLineInventoryMatch.line_key, - ShippingNoticeLineInventoryMatch.match_result, - ShippingNoticeLineInventoryMatch.part_number, - ShippingNoticeLineInventoryMatch.reservation_id, - ShippingNoticeLineInventoryMatch.shortage_qty, - ).filter( - ShippingNoticeLineInventoryMatch.task_id == task.id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ).limit(20).all() - # 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有 - # Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因 - # 缺少新表事实被误判为“未匹配”。 - has_line_match_facts = bool(pending_rows) - from app.services.shipping_notice.fulfillment_workflow import match_completed - if has_line_match_facts and not match_completed(task): - details = [ - { - 'line_key': r[0], - 'match_result': r[1], - 'part_number': r[2], - 'reservation_id': r[3], - 'shortage_qty': r[4], - } - for r in pending_rows - ] - raise AppError( - code='SHIPPING.EXCEL_NOT_READY', - message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。', - http_status=409, - details={ - 'blocking_reason_code': 'inventory_match_incomplete', - 'pending_count': len(pending_rows), - 'pending_rows_preview': details, - 'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。', - }, - ) + assert_notice_has_no_export_artifact(task) + # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 source_code = str(task.inventory_source_code or '').strip().upper() source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() if source is None: @@ -524,18 +523,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp # applies only when the published template actually consumes that system fact. if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip(): raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel') - active_artifact = ShippingExportArtifact.query.filter( - ShippingExportArtifact.task_id == task.id, - ShippingExportArtifact.status.in_({'ready', 'uploading'}), - ).first() - if active_artifact is not None: - raise ValueError('当前任务存在待上传的发货 Excel,必须先完成或授权作废该 Artifact') - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于导出的冻结订单快照') header_values, all_line_values = order_field_id_values(task) export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date() - excel_business_no = _excel_business_no(task, export_date=export_date) from app.services.shipping_notice.reservation_service import ( current_available_snapshot_line_ids, reserve_available_for_artifact, @@ -550,12 +543,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp release_overrides_by_source_line: dict[int, dict[str, Any]] = {} released_source_line_indexes: set[int] = set() - if task.id is not None: + if source_notice.id is not None: release_rows = ( ShippingOrderReviewLineDecision.query .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) .filter( - ShippingOrderReviewCase.confirmed_task_id == int(task.id), + ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), ShippingOrderReviewLineDecision.is_active.is_(True), ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', ) @@ -574,10 +567,19 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp for source_index, line in enumerate(snapshot.lines) if source_index in release_overrides_by_source_line } - verification, available_line_ids = current_available_snapshot_line_ids( - task, - released_snapshot_line_ids=released_snapshot_line_ids, - ) + selected_snapshot_line_ids = { + int(row.snapshot_line_id) + for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all() + if row.snapshot_line_id is not None + } + try: + verification, available_line_ids = current_available_snapshot_line_ids( + source_notice, + released_snapshot_line_ids=released_snapshot_line_ids, + selected_snapshot_line_ids=selected_snapshot_line_ids or None, + ) + except ConflictError: + raise # [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。 line_values = [] for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)): @@ -591,7 +593,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution # [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。 - inventory_lines = resolve_inventory_lines_for_execution(task) + inventory_lines = resolve_inventory_lines_for_execution(source_notice) release_overrides_by_line = _release_overrides_for_export_lines( line_values=line_values, release_overrides_by_source_line=release_overrides_by_source_line, @@ -613,9 +615,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp ) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values] header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields) + # [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、 + # 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。 + if not task.business_no: + from app.services.shipping_notice.business_numbering_service import assign_notice_business_number + + assign_notice_business_number(task) + excel_business_no = _excel_business_no(task, export_date=export_date) filename = _filename(task, template, excel_business_no=excel_business_no) artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}' - directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no + directory_key = task.task_no + directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / directory_key directory.mkdir(parents=True, exist_ok=True) path = directory / f'{artifact_no}_{filename}' template_bytes = file_asset_storage.get_bytes(template.storage_key) @@ -658,14 +668,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp wb.close() content = path.read_bytes() - # 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是 - # 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。 + # 当前 Notice 的唯一 Excel;后续分批履约必须先创建新的 Notice, + # 因而不得在此处替换或追加当前 Notice 的 Artifact。 artifact = ShippingExportArtifact( - artifact_no=artifact_no, task_id=task.id, template_id=template.id, + artifact_no=artifact_no, task_id=task.id, + template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id, input_checksum=_input_checksum( task, source, template, snapshot, header_values, line_values, inventory_lines, + notice_id=int(task.id), ), file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(), file_size=len(content), status='ready', @@ -673,10 +685,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp db.session.add(artifact) db.session.flush() reserve_available_for_artifact( - task, + source_notice, artifact=artifact, verification=verification, released_snapshot_line_ids=released_snapshot_line_ids, + selected_snapshot_line_ids=selected_snapshot_line_ids or None, ) return str(path), filename, artifact except Exception: diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py index 81c916a0..117bac2c 100644 --- a/backend/app/services/shipping_notice/export_archive.py +++ b/backend/app/services/shipping_notice/export_archive.py @@ -3,7 +3,7 @@ services/shipping_notice/export_archive.py 用途:为显式任务集合生成受权限控制的发货 Excel ZIP 下载包。 依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。 -逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。 +逻辑:选择每张通知唯一可下载 Artifact,校验文件 checksum,处理重名并写入 manifest.json。 """ from __future__ import annotations @@ -23,15 +23,23 @@ from app.services.shipping_notice.query_service import get_task_for_user, resolv MAX_ARCHIVE_TASKS = 100 -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())) +def _select_tasks( + *, + user_id: int, + task_refs: list[str] | None, + selection_name: str, + require_business_no: bool = False, +) -> tuple[list[ShippingNotice], str]: + """按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。""" + normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip())) if not normalized_tasks: - raise ValidationError('task_nos is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + raise ValidationError(f'{selection_name} 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: + if task is None or ( + require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper() + ): raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') tasks.append(task) if not tasks: @@ -77,14 +85,28 @@ def _archive_name(filename: str, task_no: str, used: set[str]) -> str: return candidate -def build_export_archive(*, user_id: int, task_nos: list[str]) -> tuple[BinaryIO, str, dict]: +def build_export_archive( + *, + user_id: int, + task_nos: list[str] | None = None, + business_nos: list[str] | None = None, +) -> tuple[BinaryIO, str, dict]: """ 生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。 Returns: (定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。 """ - tasks, archive_key = _select_tasks(user_id=user_id, task_nos=task_nos) + if task_nos is not None and business_nos is not None: + raise ValidationError('select either task_nos or business_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + selection_values = business_nos if business_nos is not None else task_nos + selection_name = 'business_nos' if business_nos is not None else 'task_nos' + tasks, archive_key = _select_tasks( + user_id=user_id, + task_refs=selection_values, + selection_name=selection_name, + require_business_no=business_nos is not None, + ) artifacts = _ready_artifacts(tasks) # 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。 stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b') @@ -113,7 +135,7 @@ def build_export_archive(*, user_id: int, task_nos: list[str]) -> tuple[BinaryIO included += 1 entries.append(entry) manifest = { - 'archive_version': 1, 'selection': {'task_nos': task_nos}, + 'archive_version': 1, 'selection': {selection_name: selection_values}, '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/freight_cancellation_service.py b/backend/app/services/shipping_notice/freight_cancellation_service.py index ebe6a485..b7bf5c5e 100644 --- a/backend/app/services/shipping_notice/freight_cancellation_service.py +++ b/backend/app/services/shipping_notice/freight_cancellation_service.py @@ -1,10 +1,10 @@ """ services/shipping_notice/freight_cancellation_service.py -用途:货代撤销回执登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。 +用途:外部撤销确认登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。 依赖:ShippingFreightCancellation、ShippingNotice、ShippingTaskEvent、Workflow Item Version、 fulfillment_audit。 -逻辑:complete_freight_cancellation 登记回执并作废旧任务;mark_cancelled_task_readonly +逻辑:complete_freight_cancellation 登记外部撤销确认并作废旧任务;mark_cancelled_task_readonly 在用户取消已建单 WorkflowItem 时将 Task 置 pending_void、Excel/Version 只读, 并写前后快照审计。 """ @@ -24,19 +24,15 @@ def complete_freight_cancellation( *, cancellation_id: int, actor_id: int, - freight_receipt_no: str, - receipt_asset_id: int, note: str | None = None, ) -> ShippingFreightCancellation: """ - 登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。 + 登记可追溯的外部撤销确认,随后作废旧任务并解除新版本的履约阻断。 Args: cancellation_id: 撤销单主键。 actor_id: 操作人。 - freight_receipt_no: 货代回执号。 - receipt_asset_id: 回执 FileAsset。 - note: 可选备注。 + note: 外部撤销确认原因,必填。 Returns: 更新后的 ShippingFreightCancellation。 @@ -46,9 +42,9 @@ def complete_freight_cancellation( raise NotFoundError('Freight cancellation not found', code='SHIPPING.FREIGHT_CANCELLATION_NOT_FOUND') if row.status == 'cancelled': return row - receipt = str(freight_receipt_no or '').strip() - if not receipt or not receipt_asset_id: - raise ValidationError('Cancellation receipt number and file are required', code='SHIPPING.FREIGHT_CANCELLATION_RECEIPT_REQUIRED') + confirmation_note = str(note or '').strip() + if not confirmation_note: + raise ValidationError('External cancellation confirmation note is required', code='SHIPPING.FREIGHT_CANCELLATION_CONFIRMATION_REQUIRED') old = ShippingNotice.query.filter_by(id=row.old_task_id).with_for_update().one() new = ShippingNotice.query.filter_by(id=row.new_task_id).with_for_update().one() if new.supersedes_task_id != old.id: @@ -56,9 +52,9 @@ def complete_freight_cancellation( row.status = 'cancelled' row.completed_by_id = int(actor_id) row.completed_at = datetime.utcnow() - row.freight_receipt_no = receipt - row.receipt_asset_id = int(receipt_asset_id) - row.failure_reason = str(note or '').strip() or None + row.freight_receipt_no = None + row.receipt_asset_id = None + row.failure_reason = confirmation_note old.lifecycle_status = 'voided' old.voided_at = datetime.utcnow() old.voided_by_id = int(actor_id) @@ -72,7 +68,7 @@ def complete_freight_cancellation( actor_id=actor_id, detail_json={ 'cancellation_id': row.id, - 'receipt_no': receipt, + 'confirmation_note': confirmation_note, 'new_task_no': new.task_no, 'reason_code': 'task_voided_for_correction', }, @@ -83,7 +79,7 @@ def complete_freight_cancellation( actor_id=actor_id, detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no}, )) - # 统一审计:货代回执登记必须可按 reason_code 检索 + # 统一审计:外部撤销确认必须可按 reason_code 检索。 record_fulfillment_audit( event_type='freight_cancellation_completed', aggregate_type='shipping_task', @@ -97,13 +93,13 @@ def complete_freight_cancellation( before={'lifecycle_status': 'active'}, after={ 'lifecycle_status': 'voided', - 'freight_receipt_no': receipt, + 'external_cancellation_confirmed': True, 'new_task_no': new.task_no, 'cancellation_id': int(row.id), }, metadata={ 'cancellation_id': int(row.id), - 'receipt_asset_id': int(receipt_asset_id), + 'confirmation_note': confirmation_note, 'new_task_no': str(new.task_no), }, source='workspace_api', diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index aefb6fbd..6d350a5e 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -7,12 +7,12 @@ services/shipping_notice/fulfillment_workflow.py tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、 order_task_stage_machine。 逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match; - STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human; + STP 多候选:跨文件匹配后仅全部 ok 记 completed+100%;partial 仍可按滚动库存生成已满足行 Excel; AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警); 开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传; 工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件; - upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据); - RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset; + upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工确认); + RPA 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产; Excel 生成成功写路径清除 invalidated_from_stage(BE-02,禁止投影 GET 清库)。 """ @@ -124,10 +124,10 @@ def _normalize_rpa_success_evidence( expected_filename: str | None = None, ) -> dict[str, Any] | None: """ - 校验 RPA 成功回调中的 success_evidence(BE-05 fail-closed)。 + 校验 RPA 成功回调中的受信状态摘要(fail-closed)。 核心逻辑:kind 须在白名单;selector / observed_at / filename / page_url 必填; - 必须带 dom_snippet + 匹配的 dom_sha256(不可变 DOM 证据); + 必须带经 Worker 校验过的 selector、观察时间、文件名和页面定位; 若提供 expected_filename 则须与证据文件名一致(大小写不敏感)。 Args: @@ -137,8 +137,6 @@ def _normalize_rpa_success_evidence( Returns: 规范化 evidence dict;缺失/非法时 None。 """ - import hashlib - raw = payload.get('success_evidence') if not isinstance(raw, dict): return None @@ -155,16 +153,13 @@ def _normalize_rpa_success_evidence( return None if not dom_snippet or not dom_sha256: return None - # [BE-05] 片段与哈希必须自洽,防止 Worker 自报成功却无对应 DOM。 - computed = hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower() - if computed != dom_sha256: + import hashlib + if hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower() != dom_sha256: return None if expected_filename: expected = str(expected_filename).strip() if expected and filename.lower() != expected.lower(): return None - screenshot_sha256 = str(raw.get('screenshot_sha256') or '').strip().lower() or None - screenshot_base64 = str(raw.get('screenshot_base64') or '').strip() or None return { 'kind': kind, 'selector': selector, @@ -174,42 +169,22 @@ def _normalize_rpa_success_evidence( 'page_url': page_url, 'dom_snippet': dom_snippet[:8000], 'dom_sha256': dom_sha256, - 'screenshot_sha256': screenshot_sha256, - 'screenshot_base64': screenshot_base64, + 'screenshot_sha256': str(raw.get('screenshot_sha256') or '').strip().lower() or None, + 'screenshot_base64': str(raw.get('screenshot_base64') or '').strip() or None, } -def _persist_rpa_success_evidence_asset( - *, - task: 'ShippingNotice', - attempt: Any, - success_evidence: dict[str, Any], -) -> int | None: - """ - 将 RPA 成功 DOM/截图落为 FileAsset,并回写 attempt.evidence_asset_id。 - - 核心逻辑:优先截图 PNG;否则将脱敏 DOM 片段存为 .html;绑定后从 JSON 去掉 base64 大字段。 - - Args: - task: 发货 Notice。 - attempt: ShippingUploadAttempt。 - success_evidence: 已规范化证据(可含 screenshot_base64)。 - - Returns: - FileAsset.id;落库失败时 None(证据仍留在 success_evidence_json)。 - """ +def _persist_rpa_success_evidence_asset(*, task: 'ShippingNotice', attempt: Any, success_evidence: dict[str, Any]) -> int | None: + """将受信 RPA 的 DOM/可选截图保存为内部审计资产;人工上传路径不调用本函数。""" import base64 import hashlib - from app.models import FileAsset - from app.services.file_assets.service import generate_asset_no, _build_storage_key + from app.services.file_assets.service import generate_asset_no, _build_storage_key, mark_asset_referenced from app.services.file_assets.storage import file_asset_storage - from app.services.file_assets.service import mark_asset_referenced if not getattr(task, 'user_id', None): success_evidence.pop('screenshot_base64', None) return None - raw_b64 = str(success_evidence.pop('screenshot_base64', None) or '').strip() data: bytes | None = None filename = f"rpa-success-{int(attempt.id)}.html" @@ -220,41 +195,22 @@ def _persist_rpa_success_evidence_asset( except Exception: data = None if data: - filename = f"rpa-success-{int(attempt.id)}.png" - mime_type = 'image/png' + filename, mime_type = f"rpa-success-{int(attempt.id)}.png", 'image/png' if not data: - snippet = str(success_evidence.get('dom_snippet') or '').encode('utf-8') - if not snippet: - return None - data = snippet + data = str(success_evidence.get('dom_snippet') or '').encode('utf-8') or None + if not data: + return None content_hash = hashlib.sha256(data).hexdigest().lower() expected_shot = str(success_evidence.get('screenshot_sha256') or '').strip().lower() if expected_shot and filename.endswith('.png') and expected_shot != content_hash: return None asset_no = generate_asset_no() - storage_key = _build_storage_key( - user_id=int(task.user_id), - asset_no=asset_no, - filename=filename, - ) - asset = FileAsset( - asset_no=asset_no, - owner_user_id=int(task.user_id), - original_filename=filename, - parent_asset_id=None, - asset_role='rpa_success_evidence', - source_attachment_key=f'rpa-success:{int(attempt.id)}', - storage_provider='minio', - storage_bucket=file_asset_storage.bucket_name, - storage_key=storage_key, - content_hash=content_hash, - file_size=len(data), - mime_type=mime_type, - extension=filename.rsplit('.', 1)[-1], - upload_status='uploading', - lifecycle_status='temporary', - reference_count=0, - ) + storage_key = _build_storage_key(user_id=int(task.user_id), asset_no=asset_no, filename=filename) + asset = FileAsset(asset_no=asset_no, owner_user_id=int(task.user_id), original_filename=filename, + parent_asset_id=None, asset_role='rpa_success_evidence', source_attachment_key=f'rpa-success:{int(attempt.id)}', + storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, + content_hash=content_hash, file_size=len(data), mime_type=mime_type, extension=filename.rsplit('.', 1)[-1], + upload_status='uploading', lifecycle_status='temporary', reference_count=0) db.session.add(asset) db.session.flush() try: @@ -271,7 +227,6 @@ def _persist_rpa_success_evidence_asset( return int(asset.id) - def _hash_rpa_evidence_field(value: str | None) -> str | None: """对 evidence 中的 filename/reference 做 sha256,审计禁止落原文。""" if not value: @@ -628,9 +583,9 @@ def _sync_workflow_stage( def match_completed(task: ShippingNotice) -> bool: """ - STP 制单门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时允许生成 Excel。 + STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。 - 核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。 + 核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。 """ from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision @@ -663,6 +618,52 @@ def match_completed(task: ShippingNotice) -> bool: return True +def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]: + """读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。""" + from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot + from app.services.shipping_notice.export import _source_notice_for_order_facts + + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None + if snapshot is None or source_notice.id is None: + return set() + decisions = ( + ShippingOrderReviewLineDecision.query + .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) + .filter( + ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), + ShippingOrderReviewLineDecision.is_active.is_(True), + ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ) + .all() + ) + released_indexes = { + int(decision.line_index) + for decision in decisions + if decision.line_index is not None + } + return { + int(line.id) + for index, line in enumerate(snapshot.lines) + if index in released_indexes + } + + +def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]: + """返回当前库存轮次可先行导出的冻结订单行;不代表整单已满足。""" + from app.services.shipping_notice.export import _source_notice_for_order_facts + from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids + + try: + _verification, line_ids = current_available_snapshot_line_ids( + _source_notice_for_order_facts(task), + released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task), + ) + except ConflictError: + return set() + return set(line_ids) + + def _match_step_progress_fields( *, match_status: str, @@ -708,7 +709,8 @@ def excel_gate_error(task: ShippingNotice) -> str | None: """校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。""" if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path: return None - if not match_completed(task): + # 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。 + if not match_completed(task) and not exportable_snapshot_line_ids(task): return "workflow.fulfillment.excel_gate_unmatched" return None @@ -757,10 +759,10 @@ def try_auto_chain_after_match( tool_payload = merge_tool_payload(task, payload) - # [STEP 1] 低风险:匹配成功后自动生成 Excel。 + # [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。 if _auto_generate_excel_enabled(): db.session.refresh(task) - if not task.export_file_path and match_completed(task): + if not task.export_file_path and excel_gate_error(task) is None: gen = generate_excel(tool_payload) if gen.get("status") != "ok": return gen @@ -904,6 +906,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, disposition_gate = _task_disposition_gate_response(task) if disposition_gate is not None: return disposition_gate + customer_gate = customer_gate_tool_response(task, operation='match_inventory_line') if customer_gate is not None: return customer_gate @@ -1680,7 +1683,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: 基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。 【AI 触发时机】:本轮至少一个预约单完整满足且用户确认制单时调用;未匹配前禁止调用。 - 核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。 + 核心逻辑:已有导出文件时直接返回成功;否则按当前可导出行通过 excel_gate_error,生成滚动 Excel;未满足行保留在库存满足性 Gate。 Args: payload: 须含 task_id 或 conversation_id。 @@ -1766,7 +1769,11 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids try: - _verification, available_line_ids = current_available_snapshot_line_ids(task) + from app.services.shipping_notice.export import _source_notice_for_order_facts + + _verification, available_line_ids = current_available_snapshot_line_ids( + _source_notice_for_order_facts(task), + ) except ConflictError: available_line_ids = set() if not available_line_ids: @@ -1780,7 +1787,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 2] 先校验是否满足导出门禁。 - # 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。 + # 只要当前库存轮次存在可导出行即可生成滚动 Excel;未满足行继续停留在库存满足性 Gate。 gate_error = excel_gate_error(task) if gate_error: return tool_response( @@ -1894,22 +1901,25 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: status="ok", task_id=task.task_no, message=t("workflow.fulfillment.generate_done", lang=lang).format(file=filename), - data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"}, + data={ + **serialize_task_for_tool(task), + "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export", + }, ) def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: """ - 货代上传入口:RPA 自动/重试,或人工凭据登记。 + 货代上传入口:RPA 自动/重试,或人工确认唯一 Excel 已上传。 【AI 触发时机】:AUTO_UPLOAD 开启且 Excel 就绪时可由 auto_progress 以 mode=auto 调用; - 人工接管后使用 mode=manual_confirm。 + 人工接管后使用 mode=manual_confirm;工作台对外必须先按 business_no 定位 Notice。 核心逻辑:mode=auto|retry_upload → 触发 RPA(受 AUTO_UPLOAD 与重试上限约束); - mode=manual_confirm → 校验凭据后标记 UPLOADED 并关闭 WorkflowItem。 + mode=manual_confirm → 校验唯一 Artifact 后标记 UPLOADED 并关闭 WorkflowItem。 Args: - payload: 须含 task_id;mode=auto|retry_upload|manual_confirm; - manual_confirm 须含 evidence_asset_no、operator_id。 + payload: 内部须含 task_id;mode=auto|retry_upload|manual_confirm; + manual_confirm 须含服务端可信 operator_id,不接收回执或截图/PDF。 Returns: dict[str, Any]: status 可为 ok / running / needs_human / failed。 @@ -1973,11 +1983,11 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: return tool_response( status='failed', task=task, - message='货代自动上传未开启,请人工下载 Excel 并登记上传凭据。', + message='货代自动上传未开启,请人工下载 Excel 并确认已上传。', data=serialize_task_for_tool(task), forbidden_next_tools=['upload_to_freight'], stop_agent_turn=True, - next_required_action='请在任务处理工作台使用「登记人工上传」。', + next_required_action='请在任务处理工作台使用「确认已上传」。', ) return _trigger_freight_upload_rpa( task, @@ -1995,16 +2005,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: ) operator_id = payload.get('operator_id') - evidence_asset_no = str(payload.get('evidence_asset_no') or '') - freight_ref_no = str(payload.get('freight_ref_no') or '') before_upload_status = str(task.upload_status or '') try: attempt = record_manual_upload( task, artifact_id=artifact_id, - evidence_asset_no=evidence_asset_no, operator_id=int(operator_id), - freight_ref_no=freight_ref_no, ) except (ConflictError, ValidationError, TypeError, ValueError) as exc: return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task)) @@ -2032,8 +2038,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: metadata={ 'attempt_id': attempt.id, 'artifact_id': attempt.artifact_id, - 'evidence_asset_no': evidence_asset_no, - 'freight_ref_no': freight_ref_no or None, }, source='workspace_api', sensitivity_level='sensitive', @@ -2072,7 +2076,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: 说明:本期主流程不触发货代 RPA 上传;本回调仅保留兼容,不应由业务主动调用。 核心逻辑:success=True → UPLOADED + freight_ref_no;失败 → UPLOAD_FAILED,达最大重试转人工。 - 缺省或非法 success **fail-closed 为失败**;success=True 必须带 success_evidence.kind。 + 缺省或非法 success **fail-closed 为失败**;success=True 必须带受信状态摘要。 Args: payload: 须含 task_id;success(bool,缺省视为失败);success_evidence(成功必填); @@ -2123,37 +2127,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: task=task, message=( 'RPA upload success requires success_evidence ' - '(kind whitelist, selector, observed_at, filename matching artifact, ' - 'page_url, dom_snippet+dom_sha256)' + '(kind whitelist, selector, observed_at, filename matching artifact and page_url)' ), data=serialize_task_for_tool(task), ) - # [BE-05] 结构化证据必须落 FileAsset;资产失败不得判定上传成功。 - evidence_asset_id = _persist_rpa_success_evidence_asset( - task=task, - attempt=attempt, - success_evidence=success_evidence, - ) - if evidence_asset_id is None: - return tool_response( - status='failed', - task=task, - message=( - 'RPA upload success requires persisted evidence asset ' - '(DOM/screenshot FileAsset); status remains recoverable' - ), - data={ - **serialize_task_for_tool(task), - 'upload_evidence_persist_failed': True, - }, - ) + if _persist_rpa_success_evidence_asset(task=task, attempt=attempt, success_evidence=success_evidence) is None: + return tool_response(status='failed', task=task, message='RPA upload success requires persisted internal audit asset', data=serialize_task_for_tool(task)) if hasattr(attempt, 'success_evidence_json'): - # 回调体中的 base64 已在 persist 时 pop;落库保留 snippet/哈希/asset 引用。 - attempt.success_evidence_json = { - key: value - for key, value in dict(success_evidence).items() - if key != 'screenshot_base64' - } + attempt.success_evidence_json = {key: value for key, value in dict(success_evidence).items() if key != 'screenshot_base64'} try: completed = complete_attempt( attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'), diff --git a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py index 8cf9316f..973b9d34 100644 --- a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -26,6 +26,9 @@ from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, list_eligible_post_ot_line_keys, ) +from app.services.shipping_notice.order_review_fulfillment_decision_service import ( + project_review_case_line_decisions, +) from app.services.shipping_notice.post_ot_wave_progress_service import schedule_post_ot_wave_progress @@ -114,6 +117,12 @@ def coordinate_post_ot_auto_fulfill( } eligible = list_eligible_post_ot_line_keys(case) + projection = project_review_case_line_decisions(case) + unassigned = [ + str(item.get('line_key') or '') + for item in list(projection.get('lines') or []) + if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'} + ] if not eligible: return { 'status': 'idle', @@ -122,6 +131,16 @@ def coordinate_post_ot_auto_fulfill( 'case_no': case.case_no, 'accepted_line_keys': [], } + # [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并, + # 绝不静默替用户决定 Notice 的合并范围。 + if len(eligible) != 1 or set(eligible) != set(unassigned): + return { + 'status': 'idle', + 'reason': 'manual_wave_selection_required', + 'trigger': trigger, + 'case_no': case.case_no, + 'accepted_line_keys': [], + } idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}' try: diff --git a/backend/app/services/shipping_notice/notice_line_service.py b/backend/app/services/shipping_notice/notice_line_service.py index b4a6dfd6..f52632cf 100644 --- a/backend/app/services/shipping_notice/notice_line_service.py +++ b/backend/app/services/shipping_notice/notice_line_service.py @@ -14,13 +14,19 @@ from app import db from app.models import ShippingNoticeLine, ShippingOrderSnapshot -def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrderSnapshot) -> int: +def replace_notice_lines_from_snapshot( + *, + notice_id: int, + snapshot: ShippingOrderSnapshot, + snapshot_line_ids: set[int] | None = None, +) -> int: """ 用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。 Args: notice_id: shipping_notices.id。 snapshot: 已 flush 且带 lines 的 Snapshot。 + snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。 Returns: 写入行数。 @@ -28,7 +34,10 @@ def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrde db.session.query(ShippingNoticeLine).filter_by(notice_id=int(notice_id)).delete(synchronize_session=False) now = datetime.utcnow() rows: list[ShippingNoticeLine] = [] + selected_ids = {int(item) for item in (snapshot_line_ids or set())} for line in list(snapshot.lines or []): + if selected_ids and int(line.id) not in selected_ids: + continue rows.append( ShippingNoticeLine( notice_id=int(notice_id), diff --git a/backend/app/services/shipping_notice/order_document_profile_creation_service.py b/backend/app/services/shipping_notice/order_document_profile_creation_service.py index e9377736..9de2fa43 100644 --- a/backend/app/services/shipping_notice/order_document_profile_creation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_creation_service.py @@ -39,6 +39,8 @@ def _initial_coordinate_definition(main_table_id: str) -> dict[str, Any]: """生成未标注但合法的坐标草稿起点;编辑器后续才添加锚点、表头和行布局。""" region_suffix = re.sub(r'[^a-z0-9_]+', '_', main_table_id.lower()).strip('_') or 'table' return { + # 视觉主表身份必须随共同定义冻结;annotation/training 只保存该身份的样本绑定。 + 'main_table_id': str(main_table_id).strip(), 'document_match': { 'document_type': 'purchase_order', 'page_pattern': 'one_or_more', 'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0, 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 5ccec735..872a8c67 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 @@ -550,6 +550,38 @@ def _fuse_header_regions_with_column_geometry( }) if fused_headers: result['header_regions'] = [*(result.get('header_regions') or []), *fused_headers] + # Widget 仅按“表格内有值控件”聚类,动态 XFA 的表头控件也可能带展示值。 + # 表头文字已通过独立坐标证据确认时,与该表头带实质重叠的 Widget 行不能再 + # 作为明细行候选,否则画布会同时保存 header_field 与 field。 + def _overlaps_fused_header(layout: Any) -> bool: + if not isinstance(layout, dict) or not isinstance(layout.get('region'), dict): + return False + try: + lx0, ly0, lx1, ly1 = (float(layout['region'][key]) for key in ('x0', 'y0', 'x1', 'y1')) + except (KeyError, TypeError, ValueError): + return False + layout_width, layout_height = lx1 - lx0, ly1 - ly0 + if layout_width <= 0 or layout_height <= 0: + return False + for header in fused_headers: + region = header.get('region') if isinstance(header, dict) else None + if not isinstance(region, dict): + continue + try: + hx0, hy0, hx1, hy1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1')) + except (KeyError, TypeError, ValueError): + continue + header_width, header_height = hx1 - hx0, hy1 - hy0 + horizontal_overlap = max(0.0, min(lx1, hx1) - max(lx0, hx0)) + vertical_overlap = max(0.0, min(ly1, hy1) - max(ly0, hy0)) + if header_width > 0 and header_height > 0 and \ + horizontal_overlap / min(layout_width, header_width) >= 0.8 and \ + vertical_overlap / min(layout_height, header_height) >= 0.8: + return True + return False + result['subrow_layouts'] = [ + layout for layout in layouts if not _overlaps_fused_header(layout) + ] return result @@ -632,6 +664,41 @@ def _field_binding_source_conflicts(candidates: list[dict[str, Any]]) -> list[di return conflicts +def _merge_duplicate_field_binding_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]: + """合并同字段同页同坐标的多来源候选,保留全部证据来源。""" + merged: dict[tuple[str, str, str, int, tuple[float, float, float, float]], dict[str, Any]] = {} + order: list[tuple[str, str, str, int, tuple[float, float, float, float]]] = [] + unkeyed_candidates: list[dict[str, Any]] = [] + for candidate in candidates: + binding = candidate.get('binding') if isinstance(candidate, dict) else None + visual = binding.get('visual_binding') if isinstance(binding, dict) else None + bbox = visual.get('normalized_bbox') if isinstance(visual, dict) else None + if not isinstance(binding, dict) or not isinstance(visual, dict) or not isinstance(bbox, dict): + # 缺少完整坐标的候选无法安全判定为重复,但仍是待人工复核的视觉证据。 + unkeyed_candidates.append(candidate) + continue + try: + geometry = tuple(round(float(bbox[key]), 6) for key in ('x0', 'y0', 'x1', 'y1')) + page_no = int(visual.get('page_no') or 1) + except (KeyError, TypeError, ValueError): + unkeyed_candidates.append(candidate) + continue + key = ( + str(binding.get('field_id') or ''), str(binding.get('field_code') or ''), + str(binding.get('scope') or ''), page_no, geometry, + ) + existing = merged.get(key) + if existing is None: + merged[key] = candidate + order.append(key) + continue + existing['evidence_sources'] = list(dict.fromkeys([ + *(existing.get('evidence_sources') or []), *(candidate.get('evidence_sources') or []), + ])) + existing['needs_review'] = bool(existing.get('needs_review') or candidate.get('needs_review')) + return [*unkeyed_candidates, *(merged[key] for key in order)] + + def _execute_visual_automark( *, payload: dict[str, Any], profile_id: int, document_id: int, table_id: str, ) -> dict[str, Any]: @@ -873,8 +940,9 @@ def _execute_visual_automark( table_candidates.append(_table_reconstruction_candidate( source='opencv_geometry', reconstruction=opencv_reconstruction, )) - candidates = table_candidates + field_candidates + widget_candidates - field_conflicts = _field_binding_source_conflicts(field_candidates + widget_candidates) + field_candidates = _merge_duplicate_field_binding_candidates(field_candidates + widget_candidates) + candidates = table_candidates + field_candidates + field_conflicts = _field_binding_source_conflicts(field_candidates) conflicts: list[dict[str, Any]] = [] reconstructions_by_source = { 'pdf_coordinate': native_reconstruction, diff --git a/backend/app/services/shipping_notice/order_document_profile_preview_service.py b/backend/app/services/shipping_notice/order_document_profile_preview_service.py index 76e7eb90..5cbdbbc1 100644 --- a/backend/app/services/shipping_notice/order_document_profile_preview_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_preview_service.py @@ -31,6 +31,7 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import from app.services.shipping_notice.preview_grant_store import preview_grant_store from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter +from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text PREVIEW_GRANT_TTL_SECONDS = 120 diff --git a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py index e5f6d86d..3f9d296c 100644 --- a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py @@ -7,7 +7,7 @@ services/shipping_notice/order_document_profile_publish_check_service.py 逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名、路径/集合/对账阻断, 以及字段级混合数据源可发布性与跨源 OCR mismatch 清零; 不再要求 flatten/synthetic ready / renderer_version / preview checksum; - 消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。 + 消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;管理员可确认发布自己的草稿。 """ from __future__ import annotations @@ -15,11 +15,10 @@ import secrets from datetime import datetime from typing import Any -from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( ShippingOrderDocumentProfile, - ShippingOrderDocumentProfileAudit, ShippingOrderDocumentProfileDraftRevision, ShippingOrderDocumentProfileEditLease, ShippingOrderDocumentProfilePublishCheckReport, @@ -121,40 +120,6 @@ def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingO return payload -def _find_last_profile_editor_id(profile_id: int) -> int | None: - """ - 查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。 - - 核心逻辑:优先审计映射事件;回退至最新 DraftRevision.created_by_id。 - """ - editor_events = ( - 'draft_saved', - 'xfa_mapping_saved', - 'xfa_split_rule_suggested', - 'xfa_segment_mapping_updated', - ) - audit = ( - db.session.query(ShippingOrderDocumentProfileAudit) - .filter( - ShippingOrderDocumentProfileAudit.profile_id == int(profile_id), - ShippingOrderDocumentProfileAudit.event_type.in_(editor_events), - ) - .order_by(ShippingOrderDocumentProfileAudit.id.desc()) - .first() - ) - if audit is not None and audit.actor_id is not None: - return int(audit.actor_id) - revision = ( - db.session.query(ShippingOrderDocumentProfileDraftRevision) - .filter_by(profile_id=int(profile_id)) - .order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()) - .first() - ) - if revision is not None and revision.created_by_id is not None: - return int(revision.created_by_id) - return None - - def _overlap_summary_from_run( run: ShippingOrderDocumentProfileValidationRun | None, ) -> dict[str, Any] | None: @@ -374,6 +339,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None and candidate.run_type == 'layout_signature' and candidate.status == 'passed' and candidate.definition_checksum == revision.definition_checksum + and validation_service._signature_uses_current_evidence_contract(candidate) ): signature_run = candidate if signature_run is None: @@ -491,14 +457,6 @@ def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], act raise ConflictError('Publish check report is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID') if row.blocking_items_json: raise ValidationError('Publish check has blocking items', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID') - if actor_id is not None: - editor_id = _find_last_profile_editor_id(profile.id) - if editor_id is not None and int(editor_id) == int(actor_id): - raise ValidationError( - 'Editor cannot approve own version', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID', - details={'key': 'editor_cannot_approve_own_version'}, - ) confirmed = {str(item) for item in data.get('confirmed_warning_keys') or []} required = {str(item.get('key')) for item in row.warning_items_json or []} if confirmed != required: 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 13db780c..88ccac5f 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -9,6 +9,7 @@ backend/app/services/shipping_notice/order_document_profile_service.py from __future__ import annotations +import base64 import hashlib import io import json @@ -39,8 +40,11 @@ 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 ( + coordinate_profile_character_candidates, derive_incomplete_table_bbox, reconstruct_coordinate_profile_rows, + reconstruct_coordinate_profile_rows_with_strategy, + reconstruction_exclusion_regions, suggest_header_layouts, suggest_header_regions, suggest_multi_subrow_layouts, @@ -71,6 +75,7 @@ from app.services.shipping_notice.order_profile_value_adapter import ( OrderProfileValueAdapter, get_value_adapter, ) +from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$') @@ -423,6 +428,42 @@ def _normalize_definition( ) profile_fields = _schema_profile_fields(schema_version) + reservation_region = raw.get('reservation_id_region') + if reservation_region is not None: + if not isinstance(reservation_region, dict): + raise ValidationError( + 'reservation_id_region must be an object', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID', + ) + reservation_fields = { + scope: field for (scope, code), field in profile_fields.items() + if code == 'reservation_id' + } + # 一个区域可以同时承载整单 Reservation 和指定明细行 Reservation: + # Header 是无行号值的权威落点;Line 字段启用后才消费带行号的值。 + if 'header' not in reservation_fields: + raise ValidationError( + 'Schema must enable header reservation_id for unnumbered Reservation values', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID', + details={'scopes': sorted(reservation_fields), 'required_scope': 'header'}, + ) + region = reservation_region.get('region') + page_no = reservation_region.get('page_no') + if not isinstance(region, dict) or page_no is None: + raise ValidationError( + 'reservation_id_region requires region and page_no', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID', + ) + try: + from app.services.shipping_notice.document_layout.order_profile import RelativeRegion + RelativeRegion.model_validate(region) + if int(page_no) < 1: + raise ValueError('page_no must be positive') + except (TypeError, ValueError) as exc: + raise ValidationError( + 'reservation_id_region geometry is invalid', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID', + ) from exc if raw.get('header_mappings') is not None or raw.get('source_contract') is not None or raw.get('line_mapping') is not None: raise ValidationError( 'Coordinate definition must not mix value-source mapping keys', @@ -439,6 +480,8 @@ def _normalize_definition( 'table_regions': raw.get('table_regions'), 'order_field_layouts': raw.get('order_field_layouts') or [], 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], + 'coordinate_model': raw.get('coordinate_model') or {}, + 'reference_page_frames': raw.get('reference_page_frames') or {}, } for table_region in normalized['table_regions'] or []: if not isinstance(table_region, dict): @@ -502,6 +545,13 @@ def _normalize_definition( } for target in sorted(outputs) ] + # Legacy Vendor Comments mappings are intentionally rejected at the API + # boundary; the only supported special evidence is reservation_id_region. + if raw.get('named_regions') is not None or raw.get('field_source_mappings') is not None: + raise ValidationError( + 'Legacy Vendor Comments mappings are no longer supported; use reservation_id_region', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEGACY_VENDOR_COMMENTS_UNSUPPORTED', + ) for order_field in normalized['order_field_layouts']: if not isinstance(order_field, dict): continue @@ -511,6 +561,24 @@ def _normalize_definition( field = profile_fields.get(('header', code)) if field is None: raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID') + # [STEP] Address layouts saved by the affected workbench version could inherit + # the first page anchor (Number). Reject that proven bad binding at the API + # boundary so stale browsers or direct requests cannot persist it again. + anchor = order_field.get('anchor') + anchor_text = ( + str(anchor.get('text') or '').strip().casefold() + if isinstance(anchor, dict) else '' + ) + if code in {'ship_to_address', 'bill_to_address'} and anchor_text == 'number': + raise ValidationError( + 'Address field cannot bind to the Number anchor', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID', + details={ + 'reason': 'order_field_anchor_semantic_mismatch', + 'field_code': code, + 'anchor_text': str(anchor.get('text') or '').strip(), + }, + ) order_field['field_id'] = str(field['field_id']) order_field['scope'] = 'header' normalizer = order_field.get('normalizer_key') @@ -551,6 +619,8 @@ def _normalize_definition( table_regions=normalized['table_regions'], order_field_layouts=normalized['order_field_layouts'], draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'], + coordinate_model=normalized['coordinate_model'], + reference_page_frames=normalized['reference_page_frames'], ) except (TypeError, ValueError) as exc: # Pydantic locations only describe the submitted contract, so exposing the @@ -577,11 +647,24 @@ def _normalize_definition( code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', ) from exc result = { + # 不能在坐标定义规范化时丢弃创建向导冻结的视觉主表身份。 + 'main_table_id': str(raw.get('main_table_id') or '').strip() or None, 'document_match': contract.document_match.model_dump(), 'table_regions': [item.model_dump() for item in contract.table_regions], 'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts], 'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts], + 'coordinate_model': contract.coordinate_model.model_dump(), + 'reference_page_frames': { + str(page_no): frame.model_dump() + for page_no, frame in contract.reference_page_frames.items() + }, } + if reservation_region is not None: + result['reservation_id_region'] = { + 'region': dict(reservation_region['region']), + 'page_scope': 'exact_page', + 'page_no': int(reservation_region['page_no']), + } if unified_bindings: result['bindings'] = unified_bindings result['template_mode'] = 'coordinate' @@ -661,6 +744,8 @@ def _normalize_visual_definition_for_preview( 'table_regions': table_regions, 'order_field_layouts': order_field_layouts, 'draft_unbound_order_field_layouts': draft_unbound_order_field_layouts, + 'coordinate_model': raw.get('coordinate_model') or {}, + 'reference_page_frames': raw.get('reference_page_frames') or {}, } return _normalize_definition(visual, schema_version=schema_version, preferred_template_mode='coordinate') @@ -675,6 +760,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) @@ -1005,11 +1092,42 @@ def read_preview_page_region_text( source = 'acroform_widget' elif len(matched_widgets) > 1: source = 'acroform_widget_ambiguous' + if not text: + text = _read_rendered_preview_crop_text(data.get('rendered_image_base64')) + if text: + source = 'xfa_rendered_ocr' _audit(profile_id=int(profile_id), document_id=document.id, event_type='preview_region_text_read', actor_id=actor_id, detail={ 'page_no': int(page_no), 'character_count': len(text), 'source': source, }) db.session.commit() - return {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'} + result = {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'} + if data.get('purpose') == 'reservation_id_region': + result['reservation_candidates'] = extract_reservation_from_region_text(text) + return result + + +def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str: + """读取浏览器 PDF.js XFA 画布的受控裁剪图文字,仅用于视觉标注回读。""" + raw = str(rendered_image_base64 or '') + prefix = 'data:image/png;base64,' + if not raw.startswith(prefix): + return '' + try: + payload = base64.b64decode(raw[len(prefix):], validate=True) + if not payload or len(payload) > 2 * 1024 * 1024: + return '' + import numpy as np + from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines + + image = Image.open(io.BytesIO(payload)).convert('RGB') + pixels = np.asarray(image) + height, width = pixels.shape[:2] + if width < 8 or height < 8 or width * height > 4_000_000: + return '' + lines = extract_ocr_lines(pixels, page_width=float(width), page_height=float(height)) + return ' '.join(str(item.text).strip() for item in lines if str(item.text).strip()).strip() + except Exception: + return '' def preview_profile_region( @@ -1033,6 +1151,8 @@ def preview_profile_region( profile_code=profile.profile_code, version=profile.version, document_match=definition['document_match'], table_regions=definition['table_regions'], order_field_layouts=definition['order_field_layouts'], + coordinate_model=definition['coordinate_model'], + reference_page_frames=definition['reference_page_frames'], ) table_id = str(data.get('table_id') or '').strip() if not table_id: @@ -1085,6 +1205,10 @@ def preview_profile_region( except (KeyError, TypeError, ValueError) as exc: raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc strict = bool(data.get('strict')) + schema_field_metadata = [ + item for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line' + ] rows = [] involved_field_codes: list[str] = [] seen_field_codes: set[str] = set() @@ -1098,11 +1222,21 @@ def preview_profile_region( # Header-only pages document column semantics but must never emit data rows. if not table_region.line_layouts: continue - # Adaptive regions explicitly require page evidence because a detected - # table bbox may contain headers only when MinerU misses detail rows. - region_characters = characters - if table_region.row_reconstruction_mode == 'adaptive_record_columns': - region_characters = (evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1)) + # 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema + # 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。 + reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump()) + reference_page_frame = contract.reference_page_frames.get(int(raw_table.get('page_no') or 1)) + region_characters, _candidate_page_bbox = coordinate_profile_character_candidates( + table_region=table_region.region.model_dump(), page_size=page, + reference_page_frame=( + reference_page_frame.model_dump() if reference_page_frame is not None else None + ), + page_characters=(evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1)), + table_characters=characters, + raw_table_bbox=raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None, + table_id=table_id, page_no=int(raw_table.get('page_no') or 1), + allow_table_fallback=True, + ) if not isinstance(region_characters, list): continue # ??????????????????????????? Schema ??? @@ -1117,31 +1251,22 @@ def preview_profile_region( if field_code and field_code not in seen_field_codes: seen_field_codes.add(field_code) involved_field_codes.append(field_code) - reconstructed_rows = reconstruct_coordinate_profile_rows( - characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox, + reconstructed_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=[item for item in region_characters if isinstance(item, dict)], + table_bbox=( + {'x0': 0, 'y0': 0, 'x1': reference_page_frame.width, 'y1': reference_page_frame.height} + if reference_page_frame is not None else page_bbox + ), line_layouts=[item.model_dump() for item in table_region.line_layouts], table_region=table_region.region.model_dump(), termination_rules=[item.model_dump() for item in table_region.termination_rules], - exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions], + exclusion_regions=reconstruction_exclusions, + dynamic_exclusion_regions=reconstruction_exclusions, # ????????????????????????????????? include_deleted=not strict, line_start_field_code=table_region.line_start_field_code, - row_reconstruction_mode=table_region.row_reconstruction_mode, + schema_field_metadata=schema_field_metadata, ) - # Preview must expose coordinate reads for correction even when the current - # sample's start marker is missing; the production extraction path remains strict. - if not reconstructed_rows and not strict: - reconstructed_rows = reconstruct_coordinate_profile_rows( - characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox, - line_layouts=[item.model_dump() for item in table_region.line_layouts], - table_region=table_region.region.model_dump(), - termination_rules=[item.model_dump() for item in table_region.termination_rules], - exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions], - include_deleted=True, - line_start_field_code=table_region.line_start_field_code, - include_unanchored_rows=True, - row_reconstruction_mode=table_region.row_reconstruction_mode, - ) rows.extend(reconstructed_rows) # ?????????????????????????????? if strict: @@ -1198,6 +1323,8 @@ def suggest_profile_header( profile_code=profile.profile_code, version=profile.version, document_match=definition['document_match'], table_regions=definition['table_regions'], order_field_layouts=definition['order_field_layouts'], + coordinate_model=definition['coordinate_model'], + reference_page_frames=definition['reference_page_frames'], ) table_id = str(data.get('table_id') or '').strip() layout = _document_layout(document) @@ -1392,6 +1519,28 @@ def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]: return layout +def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]: + """从标注样本冻结 Layout 提取 PDF CropBox 点尺寸,拒绝使用浏览器提交的物理尺寸。""" + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + frames: dict[str, dict[str, Any]] = {} + for page_no, page in pages.items(): + try: + normalized_page_no = int(page_no) + width, height = float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError): + continue + if normalized_page_no < 1 or width <= 0 or height <= 0: + continue + frames[str(normalized_page_no)] = { + 'width': width, + 'height': height, + 'origin': 'pdf_top_left', + 'box': 'cropbox', + } + return frames + + def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion: """????????? ready Layout ???????????????????????""" version = document.current_layout_version @@ -1648,7 +1797,7 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr ensure_inline_xfa_structure_analysis_identity, record_inline_layout_snapshot, ) - from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence + from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by( ShippingOrderDocumentProfileSample.id.asc(), @@ -1666,28 +1815,17 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) layout_version = _current_ready_layout_version(document) - required_pages = _profile_sample_coordinate_pages( - profile, sample=sample, layout_payload=layout_version.payload_json or {}, + hydrated_layout = _hydrate_coordinate_evidence( + payload=dict(layout_version.payload_json or {}), document=document, ) - if not _layout_has_page_coordinate_evidence(layout_version.payload_json or {}, page_nos=required_pages): - # [STEP 1] ??????????????????? - recovered = ensure_on_demand_coordinate_evidence( - document=document, layout=dict(layout_version.payload_json or {}), page_nos=required_pages, + required_pages = _profile_sample_coordinate_pages( + profile, sample=sample, layout_payload=hydrated_layout, + ) + if not _layout_has_page_coordinate_evidence(hydrated_layout, page_nos=required_pages): + raise ConflictError( + 'Profile sample page coordinate evidence is unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - if not _layout_has_page_coordinate_evidence(recovered, page_nos=required_pages): - raise ConflictError( - 'Profile sample page coordinate evidence is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', - ) - layout_version = record_inline_layout_snapshot( - document, recovered, - parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1', - ) - if str(layout_version.status or '') != 'ready': - raise ConflictError( - 'Profile sample page coordinate evidence cannot be frozen', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', - ) # XFA 视觉补证生成的派生 Layout 必须具有同版本的 datasets 结构分析; # 此处在共同样本冻结边界补齐历史快照,禁止值源 adapter 回退到旧 Layout。 ensure_inline_xfa_structure_analysis_identity( @@ -1802,7 +1940,10 @@ def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tupl def _ensure_page_coordinate_evidence( *, document: ShippingOrderDocument, layout: dict[str, Any], page_no: int, ) -> dict[str, Any]: - """???????????????????????????????????""" + """从当前布局的外置证据引用读取页面坐标;缺失时保持缺失,不重读原 PDF。""" + from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence + + return _hydrate_coordinate_evidence(payload=dict(layout), document=document) glyphs, source = _page_coordinate_characters(layout, page_no=page_no) if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}: return layout @@ -2092,6 +2233,8 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> document_match=definition['document_match'], table_regions=definition['table_regions'], order_field_layouts=definition['order_field_layouts'], draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'], + coordinate_model=definition['coordinate_model'], + reference_page_frames=definition['reference_page_frames'], ) layout = _document_layout(document) if isinstance(raw_page_nos, list) and any(item.page_scope == 'all_pages' for item in profile.order_field_layouts): @@ -2239,7 +2382,7 @@ def _apply_acroform_widget_preview_fallback( def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str, float]) -> bool: - """接受中心点落框或至少 80% 面积相交的 Widget,避免邻近控件串值。""" + """仅接受几乎完整落入标注框的 Widget,禁止局部框回填整段 /V。""" if not isinstance(widget_bbox, dict): return False try: @@ -2248,9 +2391,10 @@ def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str, return False if x1 <= x0 or y1 <= y0: return False - center_inside = region['x0'] <= (x0 + x1) / 2 <= region['x1'] and region['y0'] <= (y0 + y1) / 2 <= region['y1'] intersection = max(0.0, min(x1, region['x1']) - max(x0, region['x0'])) * max(0.0, min(y1, region['y1']) - max(y0, region['y0'])) - return center_inside or intersection / ((x1 - x0) * (y1 - y0)) >= .8 + # Widget /V 是整个控件值。只要框没有完整覆盖控件,就无法证明 /V 属于局部区域; + # 此时必须交给浏览器当前画布的局部 OCR,而不能以中心点或部分面积猜测。 + return intersection / ((x1 - x0) * (y1 - y0)) >= .98 def _read_acroform_widgets_for_preview(*, document: ShippingOrderDocument) -> list[Any]: @@ -3236,6 +3380,16 @@ def save_draft( ) mapping_issues = normalized.pop('_mapping_issues', None) if isinstance(normalized, dict) else None definition = normalized + # [STEP 1] 坐标模板的物理参考框由 annotation Layout 生成;长页样本不会改变 + # 已标注的 PDF 点坐标,客户端也不能伪造该基准。 + if template_mode == 'coordinate' and annotation_document is not None: + reference_page_frames = _reference_page_frames(_document_layout(annotation_document)) + if not reference_page_frames: + raise ValidationError( + 'Annotation sample page dimensions are unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) + definition['reference_page_frames'] = reference_page_frames if value_adapter.requires_split_rule_confirmation and isinstance(definition, dict): confirmation_tokens = data.get('split_rule_confirmation_tokens') if not isinstance(confirmation_tokens, dict): diff --git a/backend/app/services/shipping_notice/order_document_profile_validation_service.py b/backend/app/services/shipping_notice/order_document_profile_validation_service.py index 182b3ed9..b584ee46 100644 --- a/backend/app/services/shipping_notice/order_document_profile_validation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_validation_service.py @@ -38,6 +38,10 @@ from app.services.shipping_notice.document_layout.xfa_contract import ( XFA_PARSER_IDENTITY, ) + +# 签名生成必须先解引用压缩 Layout 的 FileAsset 坐标证据;旧签名不具备该输入契约。 +LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION = 'v1' + def _profile(profile_id: int) -> ShippingOrderDocumentProfile: """读取可验证草稿;发布和退役版本不能被新的草稿验证记录替代。""" profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) @@ -448,8 +452,15 @@ def _training_samples(profile: ShippingOrderDocumentProfile) -> list[ShippingOrd def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]: - """加载样本冻结或当前 ready layout;签名只消费坐标证据摘要,不复制原件。""" - from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + """加载样本冻结或当前 ready layout,并解引用压缩快照的 FileAsset 坐标证据。 + + 冻结 Layout 是签名和发布校验的历史事实;当 payload 只保留 + ``coordinate_evidence_ref`` 时,必须恢复其不可变坐标证据,不能误判为无版面证据。 + """ + from app.services.shipping_notice.document_layout.lifecycle import ( + _hydrate_coordinate_evidence, + current_layout_snapshot, + ) from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ( ensure_on_demand_coordinate_evidence, ) @@ -460,6 +471,11 @@ def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str, from app.models import ShippingDocumentLayoutVersion frozen = db.session.get(ShippingDocumentLayoutVersion, int(sample.layout_version_id)) if frozen is not None and isinstance(frozen.payload_json, dict): + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is not None: + return _hydrate_coordinate_evidence( + payload=dict(frozen.payload_json), document=document, + ) return dict(frozen.payload_json) document = db.session.get(ShippingOrderDocument, int(sample.document_id)) if document is None: @@ -675,6 +691,7 @@ def _build_coordinate_identity_snapshot( evidence = (snapshot.get('signature') or {}).get('evidence_quality') or {} return snapshot, { 'signature_version': LAYOUT_SIGNATURE_ID, + 'evidence_contract_version': LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION, 'signature_checksum': snapshot.get('signature_checksum'), 'matcher_policy_version': MATCHER_POLICY_ID, 'source_sample_count': evidence.get('source_sample_count') or len(samples), @@ -728,7 +745,15 @@ def _resolve_profile_identity_signature_run( or run.run_type != 'layout_signature' or run.status != 'passed' or run.definition_checksum != revision.definition_checksum + or not _signature_uses_current_evidence_contract(run) ): + if auto_run: + run_profile_identity_signature( + profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id, + lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)), + ) + db.session.refresh(profile) + return _resolve_profile_identity_signature_run(profile, revision, auto_run=False) raise ValidationError( 'Profile identity signature is stale for the current draft', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE', @@ -742,6 +767,12 @@ def _resolve_profile_identity_signature_run( return run +def _signature_uses_current_evidence_contract(run: ShippingOrderDocumentProfileValidationRun) -> bool: + """仅允许已按当前 FileAsset 解引用契约生成的签名进入发布唯一性校验。""" + summary = getattr(run, 'summary_json', None) + return isinstance(summary, dict) and summary.get('evidence_contract_version') == LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION + + def resolve_profile_identity_signature( profile: ShippingOrderDocumentProfile, revision: ShippingOrderDocumentProfileDraftRevision, @@ -785,10 +816,16 @@ def _match_thresholds(definition: dict[str, Any]) -> dict[str, float]: """从 document_match 提取发布唯一性门禁阈值。""" document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {} thresholds = document_match.get('scoring_thresholds') if isinstance(document_match.get('scoring_thresholds'), dict) else {} + + def configured_or_default(source: dict[str, Any], key: str, default: float) -> float: + """保留合法的 0 阈值;只有缺失或空值才回退默认门禁。""" + value = source.get(key) + return float(default if value is None else value) + return { - 'minimum_score': float(document_match.get('minimum_score') or 0.9), - 'minimum_margin': float(document_match.get('minimum_margin') or 0.12), - 'evidence_coverage_minimum': float(thresholds.get('evidence_coverage_minimum') or 0.70), + 'minimum_score': configured_or_default(document_match, 'minimum_score', 0.9), + 'minimum_margin': configured_or_default(document_match, 'minimum_margin', 0.12), + 'evidence_coverage_minimum': configured_or_default(thresholds, 'evidence_coverage_minimum', 0.70), } @@ -1031,7 +1068,15 @@ def _resolve_layout_signature_run( or run.run_type != 'layout_signature' or run.status != 'passed' or run.definition_checksum != revision.definition_checksum + or not _signature_uses_current_evidence_contract(run) ): + if auto_run: + run_profile_identity_signature( + profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id, + lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)), + ) + db.session.refresh(profile) + return _resolve_layout_signature_run(profile, revision, auto_run=False) raise ValidationError( 'Layout signature is stale for the current draft', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE', diff --git a/backend/app/services/shipping_notice/order_extraction_route_contract.py b/backend/app/services/shipping_notice/order_extraction_route_contract.py index 612ff0b7..32d79d1c 100644 --- a/backend/app/services/shipping_notice/order_extraction_route_contract.py +++ b/backend/app/services/shipping_notice/order_extraction_route_contract.py @@ -105,6 +105,11 @@ STABLE_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({ 'no_special_profile_feature', 'generic_extraction_disabled', 'generic_gate_blocked', + 'coordinate_evidence_unavailable', + # Runtime Parse Strategy:当前文档的坐标/行结构判断无法唯一裁决时固定进入 Review。 + 'PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION', + 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS', + 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION', 'llm_review_disabled', 'extraction_emergency_stop', 'rejected', 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 83421f27..7dee2a91 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -3618,6 +3618,7 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str, 'primary_notice': workspace_projection.get('primary_notice'), 'user_visible_stage': workspace_projection.get('user_visible_stage'), 'health_tips': workspace_projection.get('health_tips') or [], + 'lifecycle_progress': workspace_projection.get('lifecycle_progress') or {}, 'cancellation': workspace_projection.get('cancellation'), 'progress_version': workspace_projection.get('progress_version'), 'elapsed_seconds': workspace_projection.get('elapsed_seconds'), diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index a0caa566..d3a1a077 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -25,10 +25,18 @@ from app.services.shipping_notice.order_extraction_runtime_snapshot import ( from app.services.shipping_notice.document_layout.html_table import parse_html_grid 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_table_reconstruction import ( + coordinate_profile_character_candidates, + reconstruct_coordinate_profile_rows, reconstruct_coordinate_profile_rows_with_strategy, + reconstruction_exclusion_regions, +) from app.services.shipping_notice.document_layout.coordinate_transform import ( apply_coordinate_transform_to_region, ) +from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( + resolve_runtime_parse_strategy, + select_runtime_region_ids, +) 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, @@ -47,6 +55,10 @@ from app.services.shipping_notice.order_extraction_route_contract import ( from app.services.shipping_notice.tool_common import generic_extraction_enabled, profile_auto_selection_enabled from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value +from app.services.shipping_notice.reservation_region import ( + apply_reservation_region_candidates, + extract_reservation_from_vendor_comments_pages, +) @dataclass(frozen=True) @@ -281,6 +293,8 @@ def _frozen_order_profile(raw: dict[str, Any]) -> OrderCoordinateProfile: table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) @@ -316,6 +330,7 @@ def _coordinate_profile_rows( contract: Any, schema_fields: dict[str, dict[str, Any]], document_id: int | None = None, initial_carry: dict[str, Any] | None = None, coordinate_transform: dict[str, Any] | None = None, + row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows', ) -> list[dict[str, Any]] | None: """ 用模板表区和整页字符生成带字段坐标的紧凑行候选。 @@ -356,12 +371,13 @@ def _coordinate_profile_rows( if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0: return None rows: list[dict[str, Any]] = [] + runtime_region_ids = set(select_runtime_region_ids( + table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no, + )) for region in profile.table_regions: - if region.page_scope == 'first_page' and page_no != 1: - continue - if region.page_scope == 'continuation_pages' and page_no <= 1: - continue - if region.page_scope == 'exact_page' and page_no != region.page_no: + # 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页 + # 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。 + if region.region_id not in runtime_region_ids: continue # A continuation page may carry column headers only; it is not a data layout. if not region.line_layouts: @@ -369,47 +385,42 @@ def _coordinate_profile_rows( relative_region = _coordinate_region_mapping(region.region) if relative_region is None: return None - evidence_relative_region = _translate_coordinate_region( - relative_region, coordinate_transform=coordinate_transform, + reference_page_frame = profile.reference_page_frames.get(page_no) + reconstruction_page_bbox = ( + { + 'x0': 0, 'y0': 0, + 'x1': reference_page_frame.width, 'y1': reference_page_frame.height, + } + if reference_page_frame is not None else page_bbox ) - if evidence_relative_region is None: - return None - region_bbox = { - 'x0': evidence_relative_region['x0'] * page_bbox['x1'], - 'y0': evidence_relative_region['y0'] * page_bbox['y1'], - 'x1': evidence_relative_region['x1'] * page_bbox['x1'], - 'y1': evidence_relative_region['y1'] * page_bbox['y1'], - } raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None - if not is_virtual_page and raw_bbox is not None and not _coordinate_regions_overlap(raw_bbox, region_bbox): - continue - # [STEP] 横向边界服从模板;纵向取模板样例区与真实物理表的并集。模板 y 区间只描述 - # 一条样例版式,不能截掉其后重复明细;MinerU 框过短时仍由模板区保住 continuation。 - evidence_bbox = dict(region_bbox) - if raw_bbox is not None: - evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_bbox.get('y0', region_bbox['y0']))) - evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_bbox.get('y1', region_bbox['y1']))) - if isinstance(page_characters, list): - characters = [ - item for item in page_characters - if isinstance(item, dict) and _coordinate_character_in_region(item, evidence_bbox) - ] - else: - # 历史快照没有整页字符时保留表内字符兼容;新快照必须优先整页证据。 - characters = tables.get(table_id) + characters, _candidate_page_bbox = coordinate_profile_character_candidates( + table_region=region.region.model_dump(), page_size=page_size, + reference_page_frame=( + reference_page_frame.model_dump() if reference_page_frame is not None else None + ), + page_characters=page_characters if isinstance(page_characters, list) else None, + table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None, + raw_table_bbox=raw_bbox, table_id=table_id, page_no=page_no, + coordinate_transform=coordinate_transform, + allow_table_fallback=(not is_virtual_page and page_no == int(raw_table.get('page_no') or 1)), + ) if not isinstance(characters, list): return None carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {} for reconstructed in reconstruct_coordinate_profile_rows( - characters=[item for item in characters if isinstance(item, dict)], table_bbox=page_bbox, + characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox, line_layouts=[item.model_dump() for item in region.line_layouts], table_region=relative_region, termination_rules=[item.model_dump() for item in region.termination_rules], - exclusion_regions=[item.model_dump() for item in region.exclusion_regions], + exclusion_regions=reconstruction_exclusion_regions( + region.model_dump(), + ), initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0), line_start_field_code=region.line_start_field_code, - row_reconstruction_mode=region.row_reconstruction_mode, + row_reconstruction_mode=row_reconstruction_mode, coordinate_transform=coordinate_transform, + schema_field_metadata=list(schema_fields.values()), ): values: list[dict[str, Any]] = [] issues = list(reconstructed.issues) @@ -456,9 +467,17 @@ def _coordinate_profile_rows( def _selected_coordinate_transform( *, profile_match: dict[str, Any], raw_profile: dict[str, Any], ) -> dict[str, Any] | None: - """从共同 matcher 的唯一选中候选取得运行时变换,禁止为行解析二次匹配。""" + """仅为显式 anchor_frame 模板转交 matcher 的已选变换。 + + 普通 legacy 模板的绝对字段坐标已由其发布盲测验证;matcher 为提高身份匹配 + 鲁棒性推导的临时位移不得改变这类模板的正式取值区域。 + """ if str(profile_match.get('status') or '') not in {'unique_match', 'selected_by_score'}: return None + definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {} + coordinate_model = definition.get('coordinate_model') if isinstance(definition.get('coordinate_model'), dict) else {} + if str(coordinate_model.get('type') or 'legacy') != 'anchor_frame': + return None identity = ( str(raw_profile.get('profile_code') or ''), int(raw_profile.get('version') or 0), @@ -525,6 +544,69 @@ def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> return False +def _physical_table_targets_profile_region( + *, raw_table: dict[str, Any], table_regions: list[dict[str, Any]], page_size: dict[str, Any] | None, + reference_page_frame: dict[str, Any] | None = None, + coordinate_transform: dict[str, Any] | None = None, +) -> bool: + """判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。 + + 同页的页脚汇总、签章等 MinerU 物理表不属于订单明细模板,不能因其无法重建 + 而阻断已成功的目标表。虚拟页、缺失 bbox 或页尺寸异常时维持既有整页坐标回退, + 避免表检测遗漏被错误跳过。 + """ + page_no = int(raw_table.get('page_no') or 1) + if str(raw_table.get('table_id') or '') == f'page-{page_no}': + return True + raw_bbox = raw_table.get('bbox') + if not isinstance(raw_bbox, dict) or not isinstance(page_size, dict): + return True + try: + page_width, page_height = float(page_size['width']), float(page_size['height']) + projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_width + projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_height + except (KeyError, TypeError, ValueError): + return True + if page_width <= 0 or page_height <= 0 or projection_width <= 0 or projection_height <= 0: + return True + active_region_ids = set(select_runtime_region_ids( + table_regions=table_regions, page_no=page_no, + )) + active_regions = [ + region for region in table_regions + if isinstance(region, dict) + and str(region.get('region_id') or '') in active_region_ids + and isinstance(region.get('region'), dict) + and region.get('line_layouts') + ] + if not active_regions: + return True + for region in active_regions: + projected = apply_coordinate_transform_to_region( + region['region'], coordinate_transform=coordinate_transform, + ) + if projected is None: + continue + absolute_region = { + 'x0': projected['x0'] * projection_width, 'y0': projected['y0'] * projection_height, + 'x1': projected['x1'] * projection_width, 'y1': projected['y1'] * projection_height, + } + if _coordinate_regions_overlap(raw_bbox, absolute_region): + return True + return False + + +def _virtual_page_without_rows_is_nonblocking( + *, raw_table: dict[str, Any], fixed_rows: list[dict[str, Any]] | None, + adaptive_rows: list[dict[str, Any]] | None, dynamic_rows: list[dict[str, Any]] | None = None, +) -> bool: + """空虚拟页只作为漏检表格的补偿候选,不能把已有目标表成功覆盖为失败。""" + page_no = int(raw_table.get('page_no') or 1) + if str(raw_table.get('table_id') or '') != f'page-{page_no}': + return False + return not (fixed_rows or []) and not (adaptive_rows or []) and not (dynamic_rows or []) + + def _coordinate_character_in_region(character: dict[str, Any], region: dict[str, float]) -> bool: """按字符中心点裁剪模板表区,避免边缘字形重叠把页头或相邻表带入。""" bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None @@ -729,13 +811,30 @@ def _profile_table_candidates( if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version and str(item.get('checksum') or '') == match.checksum ] + # 只有唯一选中的模板显式标注了 Reservation 专区,才补齐全文坐标并开启 + # Vendor Comments→Terms 跨页扫描;其他候选模板不得改变未标注模板的读取范围。 + selected_reservation_region = ( + (profiles[0].get('definition') or {}).get('reservation_id_region') + if len(profiles) == 1 and isinstance(profiles[0], dict) else None + ) + if isinstance(selected_reservation_region, dict) and document_model is not None: + layout = ensure_on_demand_coordinate_evidence( + document=document_model, layout=layout, page_nos=None, + table_by_page={int(item.get('page_no') or 1): item for item in raw_tables}, + ) if match_only: + reservation_region = ( + _reservation_region_candidates(raw_profile=profiles[0], layout=layout) + if len(profiles) == 1 else {'candidates': [], 'reason': None} + ) return { 'matched': True, 'blocking': False, 'tables': [], 'issues': [], 'match': profile_match, + 'reservation_region_candidates': reservation_region['candidates'], + 'reservation_region_reason': reservation_region['reason'], } result_tables: list[dict[str, Any]] = [] issues: list[str] = [] @@ -781,6 +880,25 @@ def _profile_table_candidates( coordinate_transform = _selected_coordinate_transform( profile_match=profile_match, raw_profile=raw_profile, ) + profile_table_regions = [ + item.model_dump() for item in profile.table_regions + if callable(getattr(item, 'model_dump', None)) + ] + evidence_pages = ( + (layout.get('coordinate_evidence') or {}).get('pages') or {} + ) + page_size = evidence_pages.get(str(raw_table.get('page_no') or 1)) + reference_page_frame = profile.reference_page_frames.get(int(raw_table.get('page_no') or 1)) + if not _physical_table_targets_profile_region( + raw_table=raw_table, + table_regions=profile_table_regions, + page_size=page_size if isinstance(page_size, dict) else None, + reference_page_frame=( + reference_page_frame.model_dump() if reference_page_frame is not None else None + ), + coordinate_transform=coordinate_transform, + ): + continue carry = None parent_table_id = str(raw_table.get('continuation_of') or '') if parent_table_id: @@ -792,18 +910,51 @@ def _profile_table_candidates( ): carry = candidate break - coordinate_rows = _coordinate_profile_rows( + fixed_rows = _coordinate_profile_rows( raw_profile=raw_profile, raw_table=raw_table, layout=layout, contract=contract, schema_fields=schema_fields, document_id=int(unit.document_id), initial_carry=carry, coordinate_transform=coordinate_transform, + row_reconstruction_mode='fixed_subrows', + ) + adaptive_rows = _coordinate_profile_rows( + raw_profile=raw_profile, raw_table=raw_table, layout=layout, + contract=contract, schema_fields=schema_fields, + document_id=int(unit.document_id), initial_carry=None, + coordinate_transform=coordinate_transform, + row_reconstruction_mode='adaptive_record_columns', + ) + dynamic_rows = _coordinate_profile_rows( + raw_profile=raw_profile, raw_table=raw_table, layout=layout, + contract=contract, schema_fields=schema_fields, + document_id=int(unit.document_id), initial_carry=None, + coordinate_transform=coordinate_transform, + row_reconstruction_mode='dynamic_x_columns', ) except (TypeError, ValueError): issues.append('order_profile_snapshot_invalid') continue - if coordinate_rows is None: + if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: issues.append('order_profile_coordinate_reconstruction_unavailable') continue + if _virtual_page_without_rows_is_nonblocking( + raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, + dynamic_rows=dynamic_rows, + ): + continue + strategy = resolve_runtime_parse_strategy( + page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {}, + fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, + dynamic_rows=dynamic_rows, + ) + if strategy.status != 'selected' or strategy.row_mode is None: + issues.extend(strategy.reason_codes) + continue + coordinate_rows = ( + fixed_rows if strategy.row_mode == 'fixed_subrows' + else adaptive_rows if strategy.row_mode == 'adaptive_record_columns' + else dynamic_rows + ) if coordinate_rows: complete_rows = [] for row in coordinate_rows: @@ -811,7 +962,7 @@ def _profile_table_candidates( if ( region is not None and region.continuation_rule.allow_cross_page - and region.row_reconstruction_mode == 'fixed_subrows' + and strategy.row_mode == 'fixed_subrows' and row.get('_coordinate_row_count', 0) < len(region.line_layouts) ): cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = { @@ -838,6 +989,7 @@ def _profile_table_candidates( issues.append('order_profile_multiple_matches') continue raw_profile, parsed = matches[0] + reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout) result_tables.append({ 'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'), 'profile_code': str(raw_profile.get('profile_code') or ''), @@ -847,6 +999,13 @@ def _profile_table_candidates( 'page_no': int(raw_table.get('page_no') or 1), 'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'rows': parsed, + 'reservation_region_candidates': reservation_region['candidates'], + 'reservation_region_reason': reservation_region['reason'], + 'runtime_parse_strategy': { + 'page_nos': list(strategy.page_nos), + 'row_mode': strategy.row_mode, + 'reason_codes': list(strategy.reason_codes), + }, }) return { 'matched': matched_any, @@ -1523,16 +1682,30 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult decision = adapter_result.decision # [STEP 2] 公共建单:任何 adapter 只能交付 table/证据,不能自行裁决生命周期。 if adapter_result.table is not None: + reservation_candidates = ( + adapter_result.table.get('reservation_region_candidates') + if isinstance(adapter_result.table, dict) else None + ) + if not isinstance(reservation_candidates, list): + reservation_candidates = profile_result.get('reservation_region_candidates') + reservation_region_reason = ( + adapter_result.table.get('reservation_region_reason') + if isinstance(adapter_result.table, dict) else None + ) or profile_result.get('reservation_region_reason') orders, reason_code = _build_approved_profile_order_result( unit=unit, intake=intake, schema=schema, definition=definition, table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields, allow_manual_review=False, + reservation_region_candidates=reservation_candidates if isinstance(reservation_candidates, list) else None, + reservation_region_reason=str(reservation_region_reason or '') or None, ) if orders is None and adapter_result.allow_manual_row_review and reason_code == 'row_needs_review': orders, review_reason = _build_approved_profile_order_result( unit=unit, intake=intake, schema=schema, definition=definition, table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields, allow_manual_review=True, + reservation_region_candidates=reservation_candidates if isinstance(reservation_candidates, list) else None, + reservation_region_reason=str(reservation_region_reason or '') or None, ) if orders is not None: decision['fallback_reason_codes'] = ['row_needs_review'] @@ -1553,6 +1726,11 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult ) decision['parsed_table_count'] = 1 decision['route_type'] = 'profile_deterministic' + if any(order.get('reservation_region_status') == 'needs_review' for order in orders): + decision['fallback_reason_codes'] = ['reservation_region_needs_review'] + return _apply_stp_route_adjudication( + decision, execution_mode='review_required', orders=orders, + ) if decision.get('fallback_reason_codes'): return _apply_stp_route_adjudication( decision, execution_mode='review_required', orders=orders, @@ -1621,6 +1799,8 @@ def _route_reason_for_issue(issue: str) -> str: 'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch', 'order_profile_multiple_matches': 'profile_ambiguous', 'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable', + 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS': 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS', + 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION': 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION', } # 第零层:on-demand 坐标恢复失败码直接收敛为证据不可用,不经过 fallback 误报为 drift。 if str(issue).startswith('coordinate_evidence_'): @@ -1635,13 +1815,34 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfile: profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0), document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, ) +def _reservation_region_candidates(*, raw_profile: dict[str, Any], layout: dict[str, Any]) -> dict[str, Any]: + """仅对已标注专区的模板,跨页读取 Vendor Comments 到首次 Terms 标题间的候选。""" + definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {} + configured = definition.get('reservation_id_region') + if not isinstance(configured, dict): + return {'candidates': [], 'reason': None} + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + pages = [ + (int(page_no), glyphs) + for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) + ] + candidates, reason = extract_reservation_from_vendor_comments_pages(pages) + return {'candidates': candidates, 'reason': reason} + + def _build_approved_profile_order_result( *, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any], table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None, allow_manual_review: bool = False, + reservation_region_candidates: list[dict[str, Any]] | None = None, + reservation_region_reason: str | None = None, ) -> tuple[list[dict[str, Any]] | None, str | None]: """ 把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。 @@ -1779,6 +1980,66 @@ def _build_approved_profile_order_result( } if source_missing_fields['header']['field_ids'] or source_missing_fields['lines']: base_order['source_missing_fields'] = source_missing_fields + # Reservation 专用区域可同时生成整单默认值和指定行覆盖值。有效值的行优先 + # 回退由 Schema Runtime 的 compute_effective_reservation_id 统一处理,无须复制 Header。 + reservation_scope = { + str(item.get('scope') or ''): item for item in fields + if str(item.get('field_code') or '') == 'reservation_id' + } + candidates = reservation_region_candidates or list(table.get('reservation_region_candidates') or []) + reservation_region_reason = reservation_region_reason or str(table.get('reservation_region_reason') or '') or None + if reservation_region_reason: + base_order['reservation_region_status'] = 'needs_review' + base_order['reservation_region_review_reasons'] = [reservation_region_reason] + if candidates: + header_target = reservation_scope.get('header') + line_target = reservation_scope.get('line') + applied = apply_reservation_region_candidates( + candidates=candidates, + header_field_id=str(header_target.get('field_id') or '') if header_target else None, + line_field_id=str(line_target.get('field_id') or '') if line_target else None, + line_count=len(line_groups), + ) + if applied.header_value and header_target: + header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {}) + header_fields.append({'field_id': str(header_target.get('field_id') or ''), 'observations': [{ + 'value': applied.header_value, 'document_id': int(unit.document_id), + 'quote': str(header_evidence.get('raw_text') or '')[:1000], 'confidence': 1.0, + }]}) + header_id = str(header_target.get('field_id') or '') + source_missing_fields['header']['field_ids'] = [ + field_id for field_id in source_missing_fields['header']['field_ids'] if field_id != header_id + ] + header_code = str(header_target.get('field_code') or '') + source_missing_fields['header']['field_codes'] = [ + field_code for field_code in source_missing_fields['header']['field_codes'] if field_code != header_code + ] + if line_target: + for line_no, value in applied.line_values.items(): + line_evidence = next(( + item for item in candidates + if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value + ), {}) + line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{ + 'value': value, 'document_id': int(unit.document_id), + 'quote': str(line_evidence.get('raw_text') or '')[:1000], 'confidence': 1.0, + }]}) + line_id = str(line_target.get('field_id') or '') + line_code = str(line_target.get('field_code') or '') + for missing in source_missing_fields['lines']: + if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1: + missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id] + missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code] + source_missing_fields['lines'] = [ + item for item in source_missing_fields['lines'] + if item.get('field_ids') or item.get('field_codes') + ] + if not source_missing_fields['header']['field_ids'] and not source_missing_fields['lines']: + base_order.pop('source_missing_fields', None) + if applied.needs_review: + base_order['reservation_region_candidates'] = candidates + base_order['reservation_region_status'] = 'needs_review' + base_order['reservation_region_review_reasons'] = list(applied.review_reasons) if not has_review_rows: base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1' # 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。 @@ -1927,6 +2188,7 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An candidates = extract_order_fields( profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields, coordinate_evidence=layout.get('coordinate_evidence') or {}, + allow_fixed_region_confirmation=True, coordinate_transform=_selected_coordinate_transform( profile_match=match.model_dump(mode='json') if hasattr(match, 'model_dump') else match, raw_profile=raw, 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 ec0175c3..3f9c4c96 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -39,6 +39,141 @@ from app.services.shipping_notice.progress_feature_flags import ( ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'} IN_FLIGHT_UNIT_STATUSES = {'routing', 'matching_profile', 'extracting', 'merging_supplement'} +# Run/ProgressEvent 的内部事件统一收敛为工作台可见步骤;用户态不暴露 Worker 状态名。 +_LIFECYCLE_EVENT_STEP_CODES = { + 'plan_created': 'document_queued', + 'document_queued': 'document_queued', + 'layout_parsing_started': 'layout_parsing_started', + 'layout_parsing_completed': 'layout_parsing_completed', + 'profile_matching': 'profile_matching', + 'profile_candidates_scored': 'profile_matching', + 'profile_auto_selected': 'profile_matched', + 'profile_matched': 'profile_matched', + 'table_reconstructed': 'table_reconstructed', + 'order_fields_extracted': 'order_fields_extracted', + 'email_supplement_merged': 'email_supplement_merged', + 'candidate_ready': 'review_ready', + 'review_required': 'review_required', +} + +# 这些事件本身就是一个业务动作已经完成的事实。ProgressEvent 的 status 为了 +# 兼容 Run/Unit 的实时状态,部分仍会记录为 running,不能据此把已完成步骤漏掉。 +_LIFECYCLE_COMPLETION_EVENT_CODES = frozenset({ + 'layout_parsing_completed', + 'profile_auto_selected', + 'profile_matched', + 'table_reconstructed', + 'order_fields_extracted', + 'email_supplement_merged', + 'candidate_ready', +}) +_LIFECYCLE_UNIT_STEP_CODES = { + 'pending': 'document_queued', + 'routing': 'profile_matching', + 'matching_profile': 'profile_matching', + 'extracting': 'order_fields_extracted', + 'merging_supplement': 'email_supplement_merged', + 'candidate_ready': 'review_ready', + 'review_required': 'review_required', +} + + +def _build_lifecycle_progress( + run: ShippingOrderProcessingRun, + *, + units: list[ShippingOrderProcessingUnit], + effective_status: str, + current_activity: dict[str, Any] | None, + health_tips: list[dict[str, Any]], +) -> dict[str, Any]: + """ + 构建复核工作台消费的用户态生命周期进度。 + + 核心逻辑:复用当前 Run 的事件、状态、最后活动和健康提示,映射为五阶段中的 + 接收解析/订单复核及阶段内步骤;不返回正文、Provider、Job 或堆栈信息。 + """ + event_rows = [] + if getattr(run, 'id', None) is not None: + event_rows = ( + ShippingOrderExtractionProgressEvent.query + .filter_by(run_id=run.id, visibility='workspace') + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.asc(), ShippingOrderExtractionProgressEvent.id.asc()) + .all() + ) + completed: list[str] = [] + seen: set[str] = set() + for event in event_rows: + event_code = str(event.event_code or '').strip() + if ( + str(event.status or '').lower() != 'completed' + and event_code not in _LIFECYCLE_COMPLETION_EVENT_CODES + ): + continue + step = _LIFECYCLE_EVENT_STEP_CODES.get(event_code) + if step and step not in seen: + seen.add(step) + completed.append(step) + + raw_event = str((current_activity or {}).get('event_code') or '').strip() + current_step = _LIFECYCLE_EVENT_STEP_CODES.get(raw_event) + if raw_event in _LIFECYCLE_COMPLETION_EVENT_CODES: + active_unit = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None) + current_step = _LIFECYCLE_UNIT_STEP_CODES.get(str(active_unit.status or '')) if active_unit else None + if ( + effective_status in {'queued', 'processing'} + and current_step == 'layout_parsing_started' + and not any(unit.status in IN_FLIGHT_UNIT_STATUSES for unit in units) + ): + current_step = 'document_queued' + if not current_step: + current_step = 'document_queued' if effective_status in {'queued', 'processing'} else None + if current_step and current_step not in completed and effective_status in {'queued', 'processing'}: + # 当前运行中的步骤不能同时标记已完成;保留历史完成步骤顺序。 + completed = [step for step in completed if step != current_step] + + lifecycle_stage = 'intake_parse' + if current_step in {'review_ready', 'review_required'} or effective_status == 'review_required': + lifecycle_stage = 'order_review' + if effective_status in {'completed'}: + lifecycle_stage = 'order_review' + lifecycle_status = { + 'queued': 'running', + 'processing': 'running', + 'review_required': 'waiting', + 'failed': 'failed', + 'cancelled': 'cancelled', + 'completed': 'completed', + 'partially_completed': 'waiting', + }.get(effective_status, 'waiting') + health_status = 'failed' if lifecycle_status == 'failed' else ('attention' if health_tips else 'normal') + last_activity_at = (current_activity or {}).get('last_activity_at') or ( + run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None + ) + blocking_reason_i18n_key = None + if lifecycle_status == 'failed': + blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.failed' + elif lifecycle_status == 'cancelled': + blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.cancelled' + elif effective_status == 'review_required': + blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.review_required' + elif health_tips: + tip_code = str(health_tips[0].get('code') or '').strip() + if tip_code: + blocking_reason_i18n_key = f'chat.shippingProcessing.progress.lifecycleReason.{tip_code}' + return { + 'lifecycle_stage': lifecycle_stage, + 'lifecycle_status': lifecycle_status, + 'current_step_code': current_step, + 'current_step_i18n_key': ( + f'chat.shippingProcessing.progress.step.{current_step}' if current_step else None + ), + 'completed_step_codes': completed, + 'last_activity_at': last_activity_at, + 'health_status': health_status, + 'blocking_reason_i18n_key': blocking_reason_i18n_key, + 'primary_action': None, + } + # 候选待处理原因中偏「冲突/歧义」的码;其余有 missing_fields 或待补语义的归入待补信息。 _CANDIDATE_CONFLICT_REASON_CODES = frozenset({ 'email_supplement_conflict', @@ -536,6 +671,47 @@ def _latest_progress_events(run: ShippingOrderProcessingRun) -> tuple[dict[tuple return events, current +def serialize_lifecycle_progress( + run: ShippingOrderProcessingRun, + *, + units: list[ShippingOrderProcessingUnit] | None = None, + effective_status: str | None = None, + current_event: ShippingOrderExtractionProgressEvent | None = None, + health_tips: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + """构建轻量 Run 进度,供复核首屏读取,避免加载完整工作台文件与处理项投影。""" + resolved_units = units if units is not None else ( + list(run.extraction_plan.units or []) if run.extraction_plan is not None else [] + ) + resolved_status = effective_status or _effective_run_status(run, units=resolved_units) + if current_event is None and getattr(run, 'id', None) is not None: + _, current_event = _latest_progress_events(run) + current_activity: dict[str, Any] | None = None + if resolved_status in {'queued', 'processing'}: + if str(run.phase or '') == 'waiting_layout': + current_activity = {'event_code': 'layout_parsing_started'} + elif current_event is not None: + current_activity = {'event_code': current_event.event_code} + else: + active_unit = next((unit for unit in resolved_units if unit.status in ACTIVE_UNIT_STATUSES), None) + current_activity = { + 'event_code': ('document_queued' if run.status == 'queued' else active_unit.status) + if active_unit is not None else 'document_queued', + } + if current_activity is not None and run.last_activity_at is not None: + current_activity['last_activity_at'] = run.last_activity_at.isoformat() + 'Z' + resolved_tips = health_tips if health_tips is not None else ( + _health_tips_for_run(run, resolved_units) if progress_ui_v3_enabled() else [] + ) + return _build_lifecycle_progress( + run, + units=resolved_units, + effective_status=resolved_status, + current_activity=current_activity, + health_tips=resolved_tips, + ) + + def _latest_layout_document_events(run: ShippingOrderProcessingRun) -> dict[tuple[int, str], ShippingOrderExtractionProgressEvent]: """按 PDF 收集版面解析事件;该阶段早于 Unit 创建,不能复用 Unit 事件映射。""" events: dict[tuple[int, str], ShippingOrderExtractionProgressEvent] = {} @@ -1670,6 +1846,14 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: else (run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None) ), } + health_tips = _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [] + lifecycle_progress = serialize_lifecycle_progress( + run, + units=units, + effective_status=effective_status, + current_event=current_event, + health_tips=health_tips, + ) return { 'effective_status': effective_status, 'summary': { @@ -1698,7 +1882,8 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: ), 'user_visible_stage': 'failed' if effective_status == 'failed' else _run_user_visible_stage(run, units), # 回滚进度 UI v3 时不下发健康提示,避免前端展示灰度未启用的细化提醒。 - 'health_tips': _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [], + 'health_tips': health_tips, + 'lifecycle_progress': lifecycle_progress, 'cancellation': _cancellation_projection(run), 'progress_version': int(run.progress_version or 0), 'elapsed_seconds': _elapsed_seconds(started_at=run.started_at or run.created_at, finished_at=run.finished_at, now=now), diff --git a/backend/app/services/shipping_notice/order_field_purposes.py b/backend/app/services/shipping_notice/order_field_purposes.py index b7d31056..7cae906b 100644 --- a/backend/app/services/shipping_notice/order_field_purposes.py +++ b/backend/app/services/shipping_notice/order_field_purposes.py @@ -12,7 +12,7 @@ from typing import Any from app import db from app.models import ShippingOrderSnapshot, ShippingNotice -from app.services.shipping_notice.export import order_field_id_values +from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values _PURPOSE_BY_CAPABILITY = { @@ -25,7 +25,8 @@ _PURPOSE_BY_CAPABILITY = { def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]: """读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。""" - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于履约的冻结订单快照') rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule') diff --git a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py index 396a8ed5..a25bf053 100644 --- a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py +++ b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py @@ -22,11 +22,24 @@ def owns_definition(definition_or_mode: dict[str, Any] | str | None) -> bool: def owns_layout(layout: dict[str, Any] | None) -> bool: - """只按冻结 datasets capability 选择末端值源,不按 PDF provider 分流。""" + """仅在 Layout 明确证明为受支持的 XFA hybrid 文档时选择 datasets 值源。 + + ``xfa_capability`` 可能因历史复用、诊断失败或派生快照而存在,不能单独 + 作为 PDF 类型判断依据;必须同时满足结构分析已完成、文档类型为当前支持 + 的 XFA kind,且 XFA 功能开关开启。 + """ + from app.services.shipping_notice.document_layout.xfa_contract import XFA_SUPPORTED_DOCUMENT_KINDS + capability = layout.get('xfa_capability') if isinstance(layout, dict) and isinstance(layout.get('xfa_capability'), dict) else {} + document_kind = str( + capability.get('document_kind') + or (layout.get('document_kind') if isinstance(layout, dict) else '') + or '', + ).strip() return bool( xfa_enabled() and isinstance(layout, dict) + and document_kind in XFA_SUPPORTED_DOCUMENT_KINDS and (capability.get('structure_analysis_ready') or capability.get('dataset_structure_fingerprint')) ) @@ -1330,13 +1343,42 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]: metrics = build_xfa_validation_metrics(definition=definition, extraction=extraction, cross_check_summary=validation.cross_check_summary, schema_field_ids=field_ids) rows = [{str(field['field_code']): quality_service._json_value(field.get('value')) for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_code')} for row in extraction.rows] datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': [row for row in rows if row]} + # Reservation 专用证据区不是 XFA 的拆分映射:它和坐标模板盲测共用同一解析器。 + # 视觉候选中的整单值与指定行覆盖值应参与最终 blind candidate,避免盲测与正式 + # 公共建单路径出现不同结果。 + visual_reservation_headers = [ + item for item in visual_candidate.get('order_fields') or [] + if isinstance(item, dict) and item.get('field_code') == 'reservation_id' + ] + if visual_reservation_headers: + datasets_candidate['order_fields'] = [ + item for item in datasets_candidate['order_fields'] + if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header') + ] + visual_reservation_headers + for index, visual_row in enumerate(visual_candidate.get('rows') or []): + if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict): + continue + if visual_row.get('reservation_id') not in (None, ''): + datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id'] ocr_comparison = _blind_candidate_cross_check( visual_candidate=visual_candidate, datasets_candidate=datasets_candidate, ) reason_codes = list(extraction.reason_codes or []) + list(validation.reason_codes or []) if ocr_comparison['status'] == 'mismatched': reason_codes.append('ocr_datasets_mismatch') - return {'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate, 'extraction_status': extraction.status, 'reason_codes': reason_codes, 'line_row_count': len(rows), 'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0), 'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0), 'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0), 'cross_checks': dict(validation.cross_check_summary or {}), 'ocr_datasets_cross_check': ocr_comparison} + return { + 'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate, + 'extraction_status': extraction.status, 'reason_codes': reason_codes, + 'line_row_count': len(rows), 'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0), + 'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0), + 'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0), + 'cross_checks': dict(validation.cross_check_summary or {}), + 'ocr_datasets_cross_check': ocr_comparison, + **({ + 'reservation_region_status': visual_candidate['reservation_region_status'], + 'reservation_region_review_reasons': visual_candidate.get('reservation_region_review_reasons') or [], + } if visual_candidate.get('reservation_region_status') == 'needs_review' else {}), + } def blind_gate_failures(*, candidate: dict[str, Any], sample_id: int) -> tuple[list[str], dict[str, float]]: 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 26ff330a..7ce8d332 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -58,7 +58,6 @@ from app.services.shipping_notice.batch_create_idempotency import ( assert_no_exact_duplicate_notices, normalize_create_idempotency_key, ) -from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary @@ -883,7 +882,7 @@ def _persist_wave_lines_for_task( Args: case: 复核 Case。 - task: 本波次新建 Task。 + task: 本波次新建的 Notice。 line_keys: 本波次完整行键。 wave_no: 波次序号(从 1 起)。 revision_id: 可选确认修订 ID。 @@ -1357,9 +1356,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) # [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。 try: - shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user_id)) task = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), user_id=int(user_id), + task_no=generate_task_no(), user_id=int(user_id), conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename, source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash, source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id), diff --git a/backend/app/services/shipping_notice/order_review_evidence_view.py b/backend/app/services/shipping_notice/order_review_evidence_view.py index c91391b7..e15d6671 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_view.py +++ b/backend/app/services/shipping_notice/order_review_evidence_view.py @@ -29,9 +29,6 @@ from app.services.shipping_notice.order_review_llm_contract import ( build_provenance_ref, is_valid_evidence_ref, ) -from app.services.shipping_notice.document_layout.vc_source_evidence_integration import ( - collect_vc_field_evidences, -) from app.services.shipping_notice.order_review_llm_policy_registry import ( resolve_llm_context_policy, ) @@ -659,35 +656,6 @@ def build_review_evidence_view(case) -> dict[str, Any]: ) fv['field_evidences'].append(norm) - # [SOURCE 4] Vendor Comments 三来源 source_observations(Phase 4 新增) - # 追加:不覆盖/替换原有 Unit/Draft/Frozen 三源,仅扩展 LLM 上下文与工作台证据对照。 - # 在 finalize 之前插入,以便 _finalize_field_evidences 正确选 primary 与 value_source。 - vc_evidences = collect_vc_field_evidences( - case_or_candidate=case, - case_document_id=case_document_id, - ) - for vc_ev in vc_evidences: - if not isinstance(vc_ev, dict): - continue - scope_ok = str(vc_ev.get('field_code') or vc_ev.get('source_kind') or '').strip() - line_key = vc_ev.get('line_key') - field_code = vc_ev.get('field_code') - # 反查 field_id:优先用 schema_fields key→field_code 匹配;找不到则安全跳过不伪造。 - fid = None - for f_id, meta in schema_fields.items(): - if isinstance(meta, dict) and str(meta.get('field_code') or '').strip() == str(field_code or '').strip(): - fid = f_id - break - if not fid: - # 找不到 schema 映射的 VC 字段不注入,防止污染未定义字段。 - continue - scope_meta = schema_fields.get(fid, {}) - scope = 'header' if str(scope_meta.get('scope') or '').strip() == 'header' or (isinstance(scope_meta, dict) and line_key is None) else 'line' - if scope == 'line' and line_key is None: - line_key = 'header' - fv = _ensure_field(fid, scope=scope, line_key=None if scope == 'header' else str(line_key or 'header')) - fv['field_evidences'].append(vc_ev) - # finalize:选 primary + value_source 判定 for fv in header_fields.values(): _finalize_field_evidences(fv) 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 3a87cdd8..2e4d7a1d 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 ( + current_open_candidate_conflicts, field_evidence_gap_is_non_blocking, recalculate_candidate_qualification, resolve_review_case_customer_resolved, @@ -35,11 +36,6 @@ from app.services.shipping_notice.pdf_priority_adjudication import ( is_primary_pdf_source_type, ) from app.services.shipping_notice.progress_audit_contract import PDF_PRIORITY_EVIDENCE_RANKS -from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import ( - collect_vc_candidate_conflicts, -) - -_VC_CONFLICT_PREFIX = 'vc:' _EVIDENCE_GAP_REASONS = frozenset({ 'evidence_missing', 'pdf_evidence_missing', @@ -265,91 +261,6 @@ def _finding_scope(case: ShippingOrderReviewCase, *, field_code: str, line_index return 'unscoped' -def _project_vc_candidate_conflicts( - *, - case: ShippingOrderReviewCase, - candidate: ShippingOrderCandidate, -) -> list[dict[str, Any]]: - """ - 将 Vendor Comments 三来源冲突项投影为与普通字段冲突兼容的工作台格式。 - - 核心逻辑: - - conflict_key 加 vc: 前缀,避免与 line_index:field_code 格式冲突; - - 从 detail.sources 中提取候选来源值组装 options(含 vc_source_kind 标记); - - format_invalid / region_unbound 类冲突若仅有单一来源,则仍保留一项用于展示诊断。 - """ - items: list[dict[str, Any]] = [] - try: - vc_items = collect_vc_candidate_conflicts(candidate) - except Exception: # noqa: BLE001 — 投影层 fail-open:异常不影响其他冲突展示 - return items - for vc in vc_items: - if not isinstance(vc, dict): - continue - field_code = str(vc.get('field_code') or '').strip() - if not field_code: - continue - scope_raw = str(vc.get('scope') or 'line').strip() - line_no_safe = vc.get('line_no') - try: - line_index = int(line_no_safe) - 1 if scope_raw != 'header' and line_no_safe not in (None, '') else -1 - except (TypeError, ValueError): - line_index = -1 - detail = vc.get('detail') if isinstance(vc.get('detail'), dict) else {} - sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else [] - options: list[dict[str, Any]] = [] - seen: set[str] = set() - for src in sources: - if not isinstance(src, dict): - continue - vp = src.get('value_preview') - if vp in (None, ''): - continue - key = str(vp).strip() - if key in seen: - continue - seen.add(key) - source_kind = str(src.get('source') or '').strip() - source_label = str(src.get('source_label') or source_kind).strip() - options.append({ - 'value_key': key, - 'display_value': vp, - 'sources': [source_label] if source_label else [], - 'source_type': None, - 'source_types': [source_kind] if source_kind else [], - 'evidence_role': 'auxiliary', - 'evidence_rank': None, - 'vc_source_kind': source_kind, - 'vc_source_kind_label': source_label, - 'evidence_ref': src.get('evidence_ref'), - }) - # 对于 format_invalid / region_unbound 类诊断,即使无多选值也继续投影,便于工作台展示原因。 - cg_key = str(vc.get('conflict_group_key') or '').strip() - conflict_key = _VC_CONFLICT_PREFIX + (cg_key or f'{scope_raw}:{field_code}:{line_no_safe or "_"}') - line_key = vc.get('line_key') if scope_raw != 'header' else ( - _line_key_for_index(case, line_index) if line_index >= 0 else None - ) - items.append({ - 'conflict_key': conflict_key, - 'field_code': field_code, - 'line_index': line_index if line_index >= 0 else None, - 'line_key': line_key, - 'severity': str(vc.get('severity') or 'blocking'), - 'reason': str(vc.get('reason') or 'vc_source_conflict_unresolved'), - 'options': options, - 'observation_ids': [], - 'vc_kind': True, - 'vc_reason': str(vc.get('reason') or ''), - 'vc_conflict_group_key': cg_key or None, - 'vc_detail': { - 'resolution': detail.get('resolution'), - 'decision_status': detail.get('decision_status'), - 'format_valid': detail.get('format_valid'), - }, - }) - return items - - def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """ 将 Candidate 的值冲突与证据缺失分区投影,并按稳定 Finding 身份去重。 @@ -365,6 +276,11 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu evidence_issues: list[dict[str, Any]] = [] seen: set[tuple[str, str]] = set() raw_conflicts = list(candidate.conflicts_json or []) + open_conflict_keys = { + _stored_conflict_key(item) + for item in current_open_candidate_conflicts(candidate) + if isinstance(item, dict) + } adjudication = _adjudication_blob(candidate) observations = _observations_index(adjudication) for item in raw_conflicts: @@ -382,12 +298,20 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu line_index = -1 value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')] reason = str(item.get('reason') or 'field_conflict') + # 资格层仍认为该 Finding 阻断时,投影不得静默丢弃;即使候选值不完整, + # 也必须给用户一个可解释的 Review 入口,保持 UI/Gate 同源。 + is_current_open_blocking = _stored_conflict_key(item) in open_conflict_keys 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: + if len(value_keys) < 2 and not is_evidence_gap and not is_current_open_blocking: continue + if is_current_open_blocking and len(value_keys) < 2: + reason = str(reason or 'field_conflict') + recovery_action = str(item.get('recovery_action') or 'review_current_evidence').strip() or 'review_current_evidence' + else: + recovery_action = str(item.get('recovery_action') or '').strip() or None observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid] options = _finding_source_options(item) or [ _option_display( @@ -409,7 +333,7 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu 'reason': reason, 'options': options, 'observation_ids': observation_ids, - 'recovery_action': str(item.get('recovery_action') or '').strip() or None, + 'recovery_action': recovery_action, } # 同一 scope/field/reason 只能有一个开放 Finding;重复来源合并为一张卡。 finding_identity = (finding['conflict_key'], reason) @@ -417,7 +341,6 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu continue seen.add(finding_identity) (evidence_issues if is_evidence_gap else value_conflicts).append(finding) - value_conflicts.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate)) return value_conflicts, evidence_issues @@ -433,56 +356,6 @@ def project_review_case_evidence_issues(case: ShippingOrderReviewCase) -> list[d return evidence_issues -def _resolve_vc_candidate_decision( - *, - candidate: ShippingOrderCandidate, - conflict_group_key: str, - chosen_value: Any, -) -> None: - """ - 在 Vendor Comments merged_candidates 快照中标记对应项为人工裁决接受。 - - 核心逻辑:定位 conflict_group_key 匹配的 merged_candidate → - 覆写 decision_status=accepted / resolution=manual_review / accepted_value=chosen_value → - 后续 collect_vc_candidate_conflicts 将自动跳过该项(resolution!=needs_review 或 decision=accepted/dropped)。 - """ - from datetime import datetime # noqa: PLC0415 — 延迟 import 避免模块级循环依赖 - - structured = dict(candidate.structured_result_json or {}) - extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {} - vc_merged = extraction.get('vendor_comments_merged') - if not isinstance(vc_merged, dict): - return - merged_list = vc_merged.get('merged_candidates') - if not isinstance(merged_list, list): - return - updated_list: list[dict[str, Any]] = [] - for cand in merged_list: - if not isinstance(cand, dict): - updated_list.append(cand) - continue - field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip() - scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip() - scope_ok = 'header' if scope == 'header' else 'line' - line_no_raw = cand.get('effective_line_no') or cand.get('line_no') - line_no_safe = None if line_no_raw is None else str(line_no_raw) - safe_line = str(line_no_safe or '').strip() or '_' - ckey = f'{scope_ok}:{field_code}:{safe_line}' - if ckey == str(conflict_group_key or '').strip(): - cand = { - **cand, - 'decision_status': 'accepted', - 'resolution': 'manual_review', - 'accepted_value': chosen_value, - 'manual_resolved_at': datetime.utcnow().isoformat(), - } - updated_list.append(cand) - vc_merged['merged_candidates'] = updated_list - extraction['vendor_comments_merged'] = vc_merged - structured['extraction'] = extraction - candidate.structured_result_json = structured - - def resolve_review_case_field_conflict( *, user_id: int, @@ -525,178 +398,66 @@ def resolve_review_case_field_conflict( ) raw_key = str(conflict_key or '').strip() - is_vc_conflict = raw_key.startswith(_VC_CONFLICT_PREFIX) - field_code = '' line_index = -1 chosen_display: Any = None mode = str(resolution or '').strip().lower() - if is_vc_conflict: - vc_group_key = raw_key[len(_VC_CONFLICT_PREFIX):] - try: - vc_items = collect_vc_candidate_conflicts(candidate) - except Exception as exc: # noqa: BLE001 - raise NotFoundError( - 'VC conflict not accessible', - code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', - details={'conflict_key': conflict_key}, - ) from exc - target_vc: dict[str, Any] | None = None - for vc in vc_items: - if not isinstance(vc, dict): - continue - scope_raw = str(vc.get('scope') or 'line').strip() - scope_ok = 'header' if scope_raw == 'header' else 'line' - line_no_safe = vc.get('line_no') - safe_line = str(line_no_safe or '').strip() or '_' - fcode = str(vc.get('field_code') or '').strip() - ckey = f'{scope_ok}:{fcode}:{safe_line}' - want_cg = str(vc.get('conflict_group_key') or ckey).strip() - if want_cg == vc_group_key: - target_vc = vc - field_code = fcode - if scope_ok != 'header' and line_no_safe not in (None, ''): - try: - line_index = int(line_no_safe) - 1 - except (TypeError, ValueError): - line_index = -1 - break - if target_vc is None: - raise NotFoundError( - 'VC conflict not found', - code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', - details={'conflict_key': conflict_key}, - ) - detail = target_vc.get('detail') if isinstance(target_vc.get('detail'), dict) else {} - sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else [] - value_options: list[tuple[str, Any]] = [] - seen: set[str] = set() - for src in sources: - if not isinstance(src, dict): - continue - vp = src.get('value_preview') - if vp in (None, ''): - continue - k = str(vp).strip() - if k in seen: - continue - seen.add(k) - value_options.append((k, vp)) - if mode == 'adopt_option': - if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_options): - raise ValidationError( - 'option_index is required for adopt_option', - code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID', - ) - chosen_display = value_options[int(option_index)][1] - elif mode == 'custom': - if custom_value in (None, ''): - raise ValidationError( - 'custom_value is required', - code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED', - ) - chosen_display = custom_value - else: - raise ValidationError( - 'Invalid conflict resolution', - code='SHIPPING.INVALID_CONFLICT_RESOLUTION', - details={'resolution': resolution}, - ) + conflicts = list(candidate.conflicts_json or []) + target_idx = -1 + target: dict[str, Any] | None = None + for idx, item in enumerate(conflicts): + if isinstance(item, dict) and _stored_conflict_key(item) == raw_key: + target_idx = idx + target = item + break + if target is None or target_idx < 0: + raise NotFoundError( + 'Field conflict not found', + code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', + details={'conflict_key': conflict_key}, + ) + field_code = str(target.get('field') or '').strip() + try: + line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1 + except (TypeError, ValueError): + line_index = -1 + value_keys = [str(value) for value in (target.get('values') or []) if value not in (None, '')] + if mode == 'adopt_option': + if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys): + raise ValidationError('option_index is required for adopt_option', code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID') + options = _finding_source_options(target) + option = options[int(option_index)] if options else _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_index(_adjudication_blob(candidate)), + ) + chosen_display = option.get('display_value') + elif mode == 'custom': + if custom_value in (None, ''): + raise ValidationError('custom_value is required', code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED') + chosen_display = custom_value else: - conflicts = list(candidate.conflicts_json or []) - target_idx = -1 - target: dict[str, Any] | None = None - for idx, item in enumerate(conflicts): - if not isinstance(item, dict): - continue - key = _stored_conflict_key(item) - if key == raw_key: - target_idx = idx - target = item - break - if target is None or target_idx < 0: - raise NotFoundError( - 'Field conflict not found', - code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND', - details={'conflict_key': conflict_key}, - ) - field_code = str(target.get('field') or '').strip() - try: - line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1 - except (TypeError, ValueError): - line_index = -1 - value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')] - if mode == 'adopt_option': - if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys): - raise ValidationError( - 'option_index is required for adopt_option', - code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID', - ) - 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, ''): - raise ValidationError( - 'custom_value is required', - code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED', - ) - chosen_display = custom_value - else: - raise ValidationError( - 'Invalid conflict resolution', - code='SHIPPING.INVALID_CONFLICT_RESOLUTION', - details={'resolution': resolution}, - ) - # 解析历史可能保留同一稳定键的重复记录;一次人工裁决必须原子清空该 Finding 身份。 - conflicts = [ - item for item in conflicts - if not ( - isinstance(item, dict) - and _stored_conflict_key(item) == raw_key - ) - ] - candidate.conflicts_json = conflicts - structured = dict(candidate.structured_result_json or {}) - extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {} - adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {} - decisions = list(adjudication.get('decisions') or []) - updated_decisions = [] - for decision in decisions: - if not isinstance(decision, dict): - continue - same_field = str(decision.get('field') or '') == field_code - same_line = True - if line_index >= 0: - try: - same_line = int(decision.get('line_index')) == line_index - except (TypeError, ValueError): - same_line = False - if same_field and same_line: - updated_decisions.append({ - **decision, - 'status': 'selected', - 'value': chosen_display, - 'resolution_method': 'manual_review', - }) - else: - updated_decisions.append(decision) - adjudication['decisions'] = updated_decisions - adjudication['conflicts'] = list(conflicts) - extraction['field_adjudication'] = adjudication - structured['extraction'] = extraction - candidate.structured_result_json = structured - db.session.flush() + raise ValidationError('Invalid conflict resolution', code='SHIPPING.INVALID_CONFLICT_RESOLUTION', details={'resolution': resolution}) + conflicts = [item for item in conflicts if not (isinstance(item, dict) and _stored_conflict_key(item) == raw_key)] + candidate.conflicts_json = conflicts + structured = dict(candidate.structured_result_json or {}) + extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {} + adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {} + decisions = list(adjudication.get('decisions') or []) + adjudication['decisions'] = [ + {**decision, 'status': 'selected', 'value': chosen_display, 'resolution_method': 'manual_review'} + if isinstance(decision, dict) + and str(decision.get('field') or '') == field_code + and (line_index < 0 or int(decision.get('line_index') or -1) == line_index) + else decision + for decision in decisions + ] + adjudication['conflicts'] = list(conflicts) + extraction['field_adjudication'] = adjudication + structured['extraction'] = extraction + candidate.structured_result_json = structured + db.session.flush() # [STEP 1] 写入 Draft 人工值(两条路径共享)。 scope = 'line' if line_index >= 0 else 'header' @@ -737,16 +498,6 @@ def resolve_review_case_field_conflict( change = _set_value(target_line, field, chosen_display, restore_machine=False) case.current_draft.lines_json = lines - # [STEP 2] 按冲突类型分别处理 conflict_group_key 回写,并 flush。 - if is_vc_conflict: - _resolve_vc_candidate_decision( - candidate=candidate, - conflict_group_key=raw_key[len(_VC_CONFLICT_PREFIX):], - chosen_value=chosen_display, - ) - db.session.flush() - # 非 VC 分支:conflicts 删除 + adjudication decisions 更新已在上半段完成并 flush。 - # [STEP 3] 重算资格并写审计;由路由层 commit。 customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate) recalculate_candidate_qualification( 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 06a9e8b2..e02e7409 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 @@ -417,28 +417,43 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None: - """短缺放行后重投影并提交正式任务当前技术 Gate,不改写库存事实。""" + """ + 短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。 + + 核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断 + 是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。 + """ task_id = getattr(case, 'confirmed_task_id', None) if task_id is None: return task = db.session.get(ShippingNotice, int(task_id)) - execution_id = getattr(task, 'active_process_execution_id', None) if task is not None else None - if execution_id is None: + if task is None: return - from app.models import ShippingProcessExecution - execution = db.session.get(ShippingProcessExecution, int(execution_id)) - if execution is None or int(getattr(execution, 'task_id', 0) or 0) != int(task_id): - return - from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id) - # 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前 - # Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。 - from app.services.shipping_notice.auto_progress_controller import submit_auto_progress + execution_id = getattr(task, 'active_process_execution_id', None) + if execution_id is not None: + from app.models import ShippingProcessExecution + execution = db.session.get(ShippingProcessExecution, int(execution_id)) + if execution is not None and int(getattr(execution, 'task_id', 0) or 0) == int(task_id): + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id) + # 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前 + # Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。 + from app.services.shipping_notice.auto_progress_controller import submit_auto_progress - submit_auto_progress( - task=task, + submit_auto_progress( + task=task, + trigger='inventory_shortage_released', + operator_id=actor_id, + commit=False, + ) + # 单条自动履约必须在提交后由 Worker 创建独立 Notice,不能在 API 事务内同步生成 Excel。 + from app.services.shipping_notice.line_auto_fulfill_coordinator import ( + enqueue_post_ot_auto_fulfill_job, + ) + + enqueue_post_ot_auto_fulfill_job( + task_no=str(task.task_no), trigger='inventory_shortage_released', - operator_id=actor_id, commit=False, ) @@ -802,9 +817,23 @@ def project_review_case_line_decisions( for key, draft_line in draft_lines.items(): proj = projections.get(key) or {} decision = by_key.get(key) + # 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留 + # 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。 + fact = match_facts.get(key) + fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {} + fulfill_proj = dict(proj) + if isinstance(fact, dict): + if fact.get('available_qty') is not None: + fulfill_proj['available_qty'] = fact.get('available_qty') + if fact.get('match_result'): + fulfill_proj['match_result'] = fact.get('match_result') + if fact.get('inventory_status'): + fulfill_proj['inventory_status'] = fact.get('inventory_status') + if fact.get('inventory_source_code'): + fulfill_proj['inventory_source_code'] = fact.get('inventory_source_code') can_fulfill, _block, rq, aq = _assess_line_fulfill_complete( draft_line, - proj, + fulfill_proj, schema_fields=schema_fields, ) required = str(rq) if rq is not None else ( @@ -829,8 +858,6 @@ def project_review_case_line_decisions( getattr(decision, 'decision_source', None) if decision is not None else None ) decision_snap = dict(decision.snapshot_json or {}) if decision is not None else {} - fact = match_facts.get(key) - fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {} auto_failed = bool( decision_snap.get('auto_fulfill_failed') or (fact or {}).get('auto_fulfill_failed') diff --git a/backend/app/services/shipping_notice/order_review_progress_bridge.py b/backend/app/services/shipping_notice/order_review_progress_bridge.py index 0f9b3055..1015a54f 100644 --- a/backend/app/services/shipping_notice/order_review_progress_bridge.py +++ b/backend/app/services/shipping_notice/order_review_progress_bridge.py @@ -117,6 +117,32 @@ def record_review_progress_event( # [STEP 3] 兑现或丢弃 Savepoint,隔离主业务事务。 if wrote: + # Review Gate 变化必须推动同一订单工作项的版本,即使 OT 的 stage/status + # 没变化;否则工作台单调合并会继续保留旧 primary_action。 + task_no = str(getattr(run, 'user_task_no', None) or '').strip() + from app.models import ShippingOrderTask + order_task = ( + ShippingOrderTask.query.filter_by(task_no=task_no).first() + if task_no else None + ) + if order_task is None and getattr(run, 'id', None) is not None: + order_task = ( + ShippingOrderTask.query + .filter_by(extraction_run_id=int(run.id)) + .order_by(ShippingOrderTask.id.desc()) + .first() + ) + if order_task is not None: + from app.services.shipping_notice.order_task_service import sync_order_task_processing_state + sync_order_task_processing_state( + order_task, + force_progress_bump=True, + actor_type='system', + actor_id='review_progress', + reason_code='review_gate_changed', + source='order_review_progress_bridge', + correlation_id=str(case.case_no or '')[:128] or None, + ) if nested.is_active: nested.commit() return True diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index fb6877c2..ea557252 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -1169,6 +1169,8 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: """返回当前有效 Case 的轻量列表;superseded 版本仅保留在历史/审计中。""" # Run 是执行审计容器,不拥有“当前复核版本”语义。历史数据即使遗留开放状态, # 也只能由文件 Stream 的 current_case_id 决定是否出现在 Run 详情。 + from app.services.shipping_notice.order_extraction_workspace_projection import serialize_lifecycle_progress + cases = ( db.session.query(ShippingOrderReviewCase) .join( @@ -1197,6 +1199,8 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]: 'superseded_by_run_no': superseding_run.run_no if superseding_run is not None else None, 'summary': counts, 'items': items, + # 复核首屏只需 Run 级进度;禁止为此读取完整文件、候选与处理项投影。 + 'lifecycle_progress': serialize_lifecycle_progress(run), } diff --git a/backend/app/services/shipping_notice/order_review_reservation_service.py b/backend/app/services/shipping_notice/order_review_reservation_service.py index 7b04fe21..f103b81f 100644 --- a/backend/app/services/shipping_notice/order_review_reservation_service.py +++ b/backend/app/services/shipping_notice/order_review_reservation_service.py @@ -114,22 +114,31 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, effective = str(proj.get('effective_reservation_id') or '').strip() or None line_key = str(proj.get('line_key') or '').strip() or None block_reason = str(proj.get('block_reason') or '').strip() or None - reservation_blocked = ( - not effective - or (block_reason and 'reservation' in block_reason.lower()) - or any( - int(item.get('line_index') or -1) == idx - for item in issues + line_reservation_issue = next( + ( + item for item in issues if item.get('line_index') is not None - ) + and int(item.get('line_index')) == idx + and str(item.get('code') or item.get('reason_code') or '') in _RESERVATION_ISSUE_CODES + ), + None, + ) + reservation_block_reason = ( + str((line_reservation_issue or {}).get('code') or (line_reservation_issue or {}).get('reason_code') or '').strip() + or ('effective_reservation_missing' if not effective else None) + or (block_reason if block_reason and 'reservation' in block_reason.lower() else None) + ) + reservation_blocked = ( + reservation_block_reason is not None ) lines_out.append({ 'line_index': idx, 'line_key': line_key, 'effective_reservation_id': effective, 'can_build': bool(proj.get('can_build', True)), - 'block_reason': block_reason, - 'needs_attention': reservation_blocked and not bool(proj.get('can_build', True)), + # Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。 + 'block_reason': reservation_block_reason, + 'needs_attention': reservation_blocked, }) # 无 line_projections 时仍从草稿行展示当前值,便于编辑入口。 diff --git a/backend/app/services/shipping_notice/order_schema/field_rules.py b/backend/app/services/shipping_notice/order_schema/field_rules.py index 73dccf3e..02d42447 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -225,6 +225,11 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any: for pattern in ( '%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', '%Y%m%d', '%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y', + # Purchase orders also commonly use a two-digit year (for + # example ``06/16/26``). ``strptime`` applies the standard + # POSIX pivot for ``%y``; the normalized result is still an + # ISO date, so downstream validators receive one type. + '%m/%d/%y', '%m-%d-%y', '%m.%d.%y', '%d-%b-%Y', '%d-%B-%Y', ): try: 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 5659d274..16c3bbf8 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 @@ -29,9 +29,6 @@ from app.models import ( from app.services.shipping_notice.candidate_qualification_service import ( recalculate_candidate_qualification, ) -from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import ( - collect_vc_candidate_conflicts, -) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.order_review_confirmation_service import ( confirm_review_case, @@ -214,47 +211,6 @@ def _stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]: return True, None -def _vc_stp_precheck(*, candidate: ShippingOrderCandidate | None) -> tuple[bool, str | None]: - """ - Vendor Comments 三来源建单前再次校验 VC 合并结果(防御 CQ 快照与实际抽取结果漂移)。 - - 核心逻辑: - 1. candidate 为空 → 放行(VC 未启用场景); - 2. collect_vc_candidate_conflicts 结果中若存在 severity == blocking 的原因码 → 阻断; - 3. review_required 的原因码 → 阻断自动建单(允许人工,不允许 STP); - 4. 任何解析异常 → fail-closed 阻断自动建单。 - - Args: - candidate: Case 关联的当前 Candidate。 - - Returns: - (允许建单?, 阻断原因码);允许时 reason 为 None。 - """ - if candidate is None: - return True, None - try: - items = collect_vc_candidate_conflicts(candidate) - except Exception as exc: # noqa: BLE001 — 门禁 fail-closed - _LOGGER.warning('vc_stp_precheck collect_vc_candidate_conflicts failed: %s', exc) - return False, 'vc_source_integration_error' - review_seen = False - for item in items: - if not isinstance(item, dict): - continue - reason = str(item.get('reason') or '').strip() - severity = str(item.get('severity') or 'blocking').strip() - if severity == 'blocking' or reason in { - 'vc_source_region_unbound', - 'vc_source_format_invalid', - }: - return False, reason or 'vc_source_blocking_conflict' - if severity == 'review_required' and not review_seen: - review_seen = True - if review_seen: - return False, 'vc_source_conflict_unresolved' - return True, None - - def _traceability_metadata( *, run: ShippingOrderProcessingRun, @@ -470,40 +426,6 @@ def ensure_stp_auto_create_for_case( 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', } - vc_allowed, vc_block_reason = _vc_stp_precheck(candidate=candidate) - if not vc_allowed: - if case.status in {'unreviewed', 'draft', 'ready'}: - case.status = 'draft' - record_fulfillment_audit( - event_type='stp_auto_create_skipped', - aggregate_type='order_review_case', - aggregate_id=str(case.case_no), - action='stp_vc_conflict', - actor_type='system', - actor_id=None, - result='ignored', - metadata={ - 'run_no': str(resolved_run.run_no), - 'reason_code': vc_block_reason, - 'traceability': _traceability_metadata( - run=resolved_run, case=case, candidate=candidate, validation=validation, - ), - }, - source='stp_auto_create', - strict=True, - ) - db.session.flush() - if commit: - db.session.commit() - return { - 'case_no': case.case_no, - 'status': 'skipped_needs_review', - 'job_id': None, - 'can_auto_create': False, - 'blocking_reason_codes': [vc_block_reason] if vc_block_reason else [], - 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', - } - if not ( validation.get('status') == 'ready' and bool(validation.get('can_auto_create')) diff --git a/backend/app/services/shipping_notice/order_task_service.py b/backend/app/services/shipping_notice/order_task_service.py index ea0fb9de..62021249 100644 --- a/backend/app/services/shipping_notice/order_task_service.py +++ b/backend/app/services/shipping_notice/order_task_service.py @@ -46,6 +46,7 @@ def sync_order_task_processing_state( stage: str | None = None, status: str | None = None, bump_progress: bool = True, + force_progress_bump: bool = False, actor_type: str = 'system', actor_id: str | int | None = None, reason_code: str | None = None, @@ -69,6 +70,7 @@ def sync_order_task_processing_state( stage: 统一 ShippingProcessingStage;None 表示不改。 status: OT 投影 status;None 表示不改。 bump_progress: 是否递增乐观并发版本。 + force_progress_bump: 仅业务事实变化但 stage/status 不变时,是否强制推进版本。 actor_type/actor_id: 操作主体(默认 system)。 reason_code/reason: 变更原因(码 + 可选说明)。 request_id/operation_id/correlation_id: 请求与幂等关联键。 @@ -93,8 +95,9 @@ def sync_order_task_processing_state( if next_status is not None and before_status != next_status: order_task.status = next_status changed = True - if changed and bump_progress: + if (changed or force_progress_bump) and bump_progress: order_task.progress_version = before_version + 1 + changed = True if changed: order_task.updated_at = datetime.utcnow() db.session.flush() @@ -958,7 +961,10 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional 'shipping_notice_id': row.shipping_notice_id, 'candidate_id': row.candidate_id, } - row.shipping_notice_id = int(notice_id) + # 兼容字段只在首张 Notice 尚未建立时回填,后续分批 Notice 以 + # ShippingNotice.order_task_id 的多对一关系为权威,禁止覆盖首条指针。 + if row.shipping_notice_id is None: + row.shipping_notice_id = int(notice_id) row.updated_at = datetime.utcnow() from app.models import ShippingNotice @@ -979,7 +985,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional reason_code='notice_created', before=before, after={ - 'shipping_notice_id': int(notice_id), + 'shipping_notice_id': row.shipping_notice_id, 'candidate_id': row.candidate_id, 'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None, }, diff --git a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py index 6e9e4202..099016f7 100644 --- a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py +++ b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py @@ -22,11 +22,15 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingNotice, + ShippingOrderTask, ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderReviewWaveIdempotency, ShippingOrderReviewWaveLine, + ShippingOrderSnapshot, ) +from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot +from app.services.shipping_notice.tool_common import generate_task_no from app.services.shipping_notice.order_review_fulfillment_decision_service import ( DECISION_FULFILL, _STATUS_BY_DECISION, @@ -71,7 +75,8 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE', details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')}, ) - if line.get('is_shortage'): + is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage' + if line.get('is_shortage') and not is_released_shortage: raise ConflictError( 'Line has inventory shortage', code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', @@ -79,7 +84,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] ) req = _parse_qty(line.get('required_qty')) avail = _parse_qty(line.get('available_qty')) - if req is None or avail is None or avail < req: + if req is None or (avail is None and not is_released_shortage) or (avail is not None and avail < req and not is_released_shortage): raise ConflictError( 'Line cannot fulfill complete quantity with current inventory facts', code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', @@ -164,7 +169,7 @@ def create_post_ot_fulfillment_wave( idempotency_key: 可选幂等键(独立表强约束)。 Returns: - wave_no / task_no / accepted_line_keys / skipped_line_keys / line_fulfillment / + wave_no / task_no / notice_no / accepted_line_keys / skipped_line_keys / line_fulfillment / idempotency_row_id / idempotent_replay。 """ keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] @@ -256,6 +261,7 @@ def create_post_ot_fulfillment_wave( accepted.append(key) wave_no = None + notice = None if accepted: max_wave = ( db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no)) @@ -266,9 +272,67 @@ def create_post_ot_fulfillment_wave( from app.services.shipping_notice.order_review_confirmation_service import ( _persist_wave_lines_for_task, ) + from app.services.shipping_notice.export import _source_notice_for_order_facts + + source_notice = _source_notice_for_order_facts(task) + snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) + snapshot_line_ids = { + int(snapshot.lines[int((by_key[key] or {}).get('line_index'))].id) + for key in accepted + if snapshot is not None + and (by_key[key] or {}).get('line_index') is not None + and 0 <= int((by_key[key] or {}).get('line_index')) < len(snapshot.lines) + } + if len(snapshot_line_ids) != len(accepted): + raise ConflictError( + 'Selected review lines do not map to frozen order lines', + code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING', + ) + order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) if task.order_task_id else None + if order_task is None: + raise ConflictError( + 'Formal notice is not linked to an order task', + code='SHIPPING.REVIEW_POST_OT_WAVE_ORDER_TASK_REQUIRED', + ) + # [STEP 1c] 每个履约波次都是独立 Notice,直接继承客户快照; + # 对外发货通知单号只能随该 Notice 的首个 Excel 在同一事务中分配。 + if task.customer_id is None: + raise ConflictError( + 'Formal notice customer is required before creating a fulfillment wave', + code='SHIPPING.REVIEW_POST_OT_WAVE_CUSTOMER_REQUIRED', + ) + notice = ShippingNotice( + task_no=generate_task_no(), + order_task_id=int(order_task.id), + customer_id=task.customer_id, + customer_name_snapshot=task.customer_name_snapshot, + customer_short_code_snapshot=task.customer_short_code_snapshot, + user_id=task.user_id, + conversation_id=task.conversation_id, + source_type='post_ot_fulfillment_wave', + inventory_source_code=task.inventory_source_code, + inventory_connector_type=task.inventory_connector_type, + inventory_warehouse_id=task.inventory_warehouse_id, + inventory_source_status=task.inventory_source_status, + inventory_source_method=task.inventory_source_method, + inventory_source_config_version=task.inventory_source_config_version, + inventory_routing_fingerprint=task.inventory_routing_fingerprint, + inventory_snapshot_id=task.inventory_snapshot_id, + customer_resolution_status=task.customer_resolution_status, + customer_resolution_method=task.customer_resolution_method, + customer_identity_fingerprint=task.customer_identity_fingerprint, + customer_confirmed_by=task.customer_confirmed_by, + customer_confirmed_at=task.customer_confirmed_at, + ) + db.session.add(notice) + db.session.flush() + notice.customer_resolution_status = 'confirmed' + replace_notice_lines_from_snapshot( + notice_id=int(notice.id), snapshot=snapshot, snapshot_line_ids=snapshot_line_ids, + ) _persist_wave_lines_for_task( case=case, - task=task, + task=notice, line_keys=accepted, wave_no=wave_no, revision_id=None, @@ -282,6 +346,18 @@ def create_post_ot_fulfillment_wave( current = _active_decision(case, key) if current is not None and current.line_status in {'task_created', 'fulfilled'}: continue + # [STEP 2a] 短缺放行的补录库存字段必须保留在活动审计决定中, + # 不能被通用 fulfill 决定覆盖,否则独立 Excel 将丢失放行字段来源。 + if ( + key in accepted + and current is not None + and current.decision_code == 'release_inventory_shortage' + ): + current.line_status = 'task_created' + current.task_id = int(notice.id) + current.wave_no = int(wave_no) if wave_no is not None else None + current.updated_at = now + continue if current is not None: current.is_active = False current.updated_at = now @@ -301,7 +377,7 @@ def create_post_ot_fulfillment_wave( available_qty=avail, reservation_id=line.get('reservation_id'), part_number=line.get('part_number'), - task_id=int(task.id), + task_id=int(notice.id) if key in accepted else int(task.id), wave_no=wave_no if key in accepted else ( int(current.wave_no) if current is not None and current.wave_no is not None else None ), @@ -342,8 +418,8 @@ def create_post_ot_fulfillment_wave( review_case_no=str(case.case_no), run_no=str(case.run.run_no) if case.run is not None else None, task_no=str(task.task_no), - before_json={'line_keys': keys}, - after_json={ + before={'line_keys': keys}, + after={ 'wave_no': wave_no, 'accepted_line_keys': accepted, 'skipped_line_keys': skipped, @@ -354,10 +430,11 @@ def create_post_ot_fulfillment_wave( result = { 'case_no': case.case_no, - 'task_no': task.task_no, - 'task_id': int(task.id), + 'task_no': notice.task_no if notice is not None else task.task_no, + 'task_id': int(notice.id) if notice is not None else int(task.id), 'review_case_id': int(case.id), 'wave_no': wave_no, + 'notice_no': notice.task_no if notice is not None else None, 'accepted_line_keys': accepted, 'skipped_line_keys': skipped, 'decision_source': source, @@ -371,8 +448,8 @@ def create_post_ot_fulfillment_wave( idem_row = ShippingOrderReviewWaveIdempotency( idempotency_key=persist_key, review_case_id=int(case.id), - task_id=int(task.id), - task_no=str(task.task_no), + task_id=int(notice.id) if notice is not None else int(task.id), + task_no=str(notice.task_no if notice is not None else task.task_no), wave_no=wave_no, decision_source=source, line_keys_json=_stable_line_keys(keys), @@ -396,7 +473,10 @@ def create_post_ot_fulfillment_wave( def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: """ - 列出可自动/人工完整履约的行(ready+matched+非短缺+未关闭+未终态)。 + 列出可自动/人工履约的行(ready+matched+未关闭+未终态)。 + + 核心逻辑:库存充足行可直接入 wave;库存不足行只有在已留下 + ``release_inventory_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。 Args: case: 复核 Case。 @@ -415,7 +495,8 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: continue if str(item.get('match_result') or '') != 'matched': continue - if item.get('is_shortage'): + decision_code = str((item.get('decision') or {}).get('decision_code') or '') + if item.get('is_shortage') and decision_code != 'release_inventory_shortage': continue if item.get('user_line_status') == 'auto_fulfill_failed': continue @@ -423,7 +504,10 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]: continue req = _parse_qty(item.get('required_qty')) avail = _parse_qty(item.get('available_qty')) - if req is None or avail is None or avail < req: + is_released_shortage = decision_code == 'release_inventory_shortage' + if req is None or (avail is None and not is_released_shortage) or ( + avail is not None and avail < req and not is_released_shortage + ): continue out.append(str(item.get('line_key') or '')) return [k for k in out if k] diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 951fdb08..f91842f8 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -1164,10 +1164,8 @@ def sync_fulfillment_gates_from_task( idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}', force=True, ) - if not sufficiency_ok: - return - - # [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离 + # [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离。 + # 库存不足仍停在 Gate 16,但滚动履约可为已满足/已审计放行行生成下一份 Excel。 excel_error = excel_gate_error(task) excel_ready = excel_error is None apply_gate_outcome( diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 5203af92..7826e66b 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -366,6 +366,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'recheck_freeze_readiness', 'retry_task_creation', 'retry_inventory_preparation', + 'reload_inventory_result', 'poll_inventory_preparation', 'retry_inventory_field_mapping', 'retry_inventory_matching', @@ -380,7 +381,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'poll_freight_upload_rpa', 'retry_freight_upload_rpa', 'regenerate_manual_upload_todo', - # 仅驱动前端打开人工上传凭据登记;不得通过普通 Gate POST 直接确认。 + # 仅驱动前端打开人工上传确认;不得通过普通 Gate POST 直接确认。 'mark_manual_uploaded', }) @@ -419,9 +420,9 @@ for _code, _ui_handler in { 'open_shortage_review': {'ui_handler': 'shortage_review'}, }.items(): PROCESS_GATE_ACTION_PRESENTATION[_code].update(_ui_handler) -# 人工上传凭据登记由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。 +# 人工上传确认由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。 PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['dispatch'] = 'dialog' -PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_evidence' +PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_confirmation' for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}: PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery' for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}: @@ -468,11 +469,17 @@ def is_business_user_action(action_code: str | None) -> bool: return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES -def inventory_preparation_primary_action(status: str | None) -> str | None: +def inventory_preparation_primary_action( + status: str | None, + blocking_reason_code: str | None = None, +) -> str | None: """裁决库存准备 Gate 面向业务用户的主动作。""" normalized_status = str(status or '').strip().lower() + normalized_reason = str(blocking_reason_code or '').strip().lower() if normalized_status == 'waiting_external': return 'poll_inventory_preparation' + if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}: + return 'reload_inventory_result' if normalized_status in {'blocked_manual', 'blocked_retryable'}: return 'retry_inventory_preparation' return None @@ -817,6 +824,8 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: return True if action == 'retry_inventory_matching' and code == 'inventory_sufficiency': return True + if action == 'reload_inventory_result' and code == 'inventory_preparation': + return True navigation_owners = { 'open_order_review': {'order_freeze_readiness', 'order_field_extraction'}, 'open_profile_review': {'document_profile_routing'}, diff --git a/backend/app/services/shipping_notice/process_gate_dependency.py b/backend/app/services/shipping_notice/process_gate_dependency.py index 6ad2744c..283dc814 100644 --- a/backend/app/services/shipping_notice/process_gate_dependency.py +++ b/backend/app/services/shipping_notice/process_gate_dependency.py @@ -158,7 +158,8 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = { 'inventory_field_mapping': ('inventory_preparation',), 'inventory_matching': ('inventory_field_mapping',), 'inventory_sufficiency': ('inventory_matching',), - 'excel_readiness': ('inventory_sufficiency',), + # 滚动导出仅要求已完成库存匹配;库存不足仍由 inventory_sufficiency 独立阻断未导出行。 + 'excel_readiness': ('inventory_matching',), 'artifact_generation': ('excel_readiness',), 'freight_upload_rpa': ('artifact_generation',), 'manual_upload_handoff': ('freight_upload_rpa',), diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index 95239e0b..5adb1c89 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -181,6 +181,7 @@ def _dispatch_action( 'retry_duplicate_detection': _handle_recheck_task_gates, 'retry_task_creation': _handle_retry_task_creation, 'retry_inventory_preparation': _handle_retry_inventory_preparation, + 'reload_inventory_result': _handle_reload_inventory_result, 'poll_inventory_preparation': _handle_retry_inventory_preparation, 'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping, 'retry_inventory_matching': _handle_retry_inventory_matching, @@ -860,6 +861,58 @@ def _handle_retry_inventory_preparation( return outcome +def _handle_reload_inventory_result( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """ + 重读已产生的库存快照,不重新触发库存 RPA。 + + 核心逻辑:仅复用既有快照查询、身份校验、挂接和库存加载;未命中时保留当前 + RPA 超时阻断,让用户明确选择“重新获取库存”或上传库存文件。 + """ + from app.models import ShippingNotice + from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.process_gate_bridge import ( + inventory_preparation_reason_code, + sync_fulfillment_gates_from_task, + ) + + task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + if task is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': 'inventory_preparation_failed', + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + } + response = _try_reuse_inventory_snapshot( + task, + task_rpa_inventory_source(task) or {}, + mode='reload_result', + ) + if response is None: + return { + 'outcome': 'blocked_retryable', + 'blocking_reason_code': inventory_preparation_reason_code(task), + 'effective_result_json': {'findings': [], 'snapshot_found': False}, + 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + } + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=payload.get('actor_user_id'), + ) + return _tool_outcome( + action_code='reload_inventory_result', + response=response, + blocking_reason_code=inventory_preparation_reason_code(task), + ) + + def _handle_retry_inventory_field_mapping( *, execution: ShippingProcessExecution, @@ -1130,42 +1183,35 @@ def _handle_regenerate_excel( gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """重新生成 Excel Artifact;上传 Gate 的跨阶段恢复先精确作废旧产物。""" + """仅在尚未生成 Excel 时重试首次生成,已有 Artifact 时拒绝重生。""" + from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.fulfillment_workflow import generate_excel from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action - recovery_definition = recovery_plan_for_action( - current_gate=gate.gate_code, - action_code='regenerate_excel_artifact', + task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + existing = ( + ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first() + if task is not None and task.id is not None else None ) - invalidation = None - if recovery_definition is not None: - from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only - - invalidation = invalidate_excel_regeneration_only( - execution=execution, - attempt_id=payload.get('attempt_id'), - actor_id=payload.get('actor_user_id'), - ) + if existing is not None: + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'notice_excel_already_generated', + 'blocking_reason_json': {'message': '同一发货通知单只能生成一个 Excel;请创建新的发货通知单'}, + 'effective_result_json': {'findings': []}, + 'output_snapshot': {'action_code': 'regenerate_excel_artifact', 'rejected': True}, + } response = generate_excel(_task_payload(execution, payload)) outcome = _tool_outcome( action_code='regenerate_excel_artifact', response=response, blocking_reason_code='artifact_generation_failed', ) - if invalidation is not None: - outcome['output_snapshot']['invalidation'] = invalidation - sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) - if recovery_definition is not None and gate.gate_code == 'manual_upload_handoff' and outcome['outcome'] == 'passed': - # Gate 20 是恢复动作的授权载体,不是 Excel 生成的业务终点。新 Artifact - # 生成后仍须回到人工上传交接;否则 complete_gate_attempt 会把 Gate 20 误写为 passed。 - outcome.update({ - 'outcome': 'blocked_manual', - 'blocking_reason_code': 'manual_upload_pending', - 'blocking_reason_json': {'message': '新的发货 Excel 已生成,请登记人工上传凭据'}, - 'effective_result_json': {'findings': [], 'regenerated': True}, - }) + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=payload.get('actor_user_id'), + ) return outcome diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index f550e9d7..673cbf70 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -77,20 +77,15 @@ def _projection_primary_next_action(*, gate_code: str, status: str) -> str | Non return str(value) if value else None -# 库存 RPA / 准备失败原因:统一由业务用户触发「重新获取库存」(retry_inventory_preparation)。 -# 与 error_explainability_contract.EXPLAINABILITY_REASON_META 中 inventory_file_empty 等 -# 的 prescribed action 保持一致;这些原因在 process_gate_contract 中分类为 retryable_tech, -# 但因 inventory_preparation 的 responsible_party='worker',历史投影会按「worker/retry_ 技术 -# 动作屏蔽」规则将其从业务按钮隐藏,导致用户只能看到被降级的人工上传入口。 +# 库存准备失败由业务用户显式处理;RPA 超时/耗尽优先重读已落盘结果,其他失败才重试 RPA。 def _resolve_recovery_next_action( *, blocking: dict[str, Any] | None, full: dict[str, Any], execution: Any, ) -> tuple[str | None, bool]: """ 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - [STEP 1] 库存 RPA 失败(inventory_preparation Gate + retryable_tech 原因码)统一下发 - ``retry_inventory_preparation``(重新获取库存),绕过历史「worker/retry_ 技术动作屏蔽」 - 分支,使业务用户在库存 RPA 失败时可直接重试,而非被降级为人工上传入口。 + [STEP 1] 库存 RPA 超时/耗尽先下发 ``reload_inventory_result``,只重读已有结果; + 其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。 [STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。 [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留 RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。 @@ -102,9 +97,9 @@ def _resolve_recovery_next_action( status = str((blocking or {}).get('status') or '').strip().lower() has_formal_task = bool(execution and getattr(execution, 'task_id', None)) - # [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。 + # [STEP 1] RPA 超时/耗尽时先重读已有结果,其他库存准备失败仍允许重新运行 RPA。 if blocking_gate_code == 'inventory_preparation': - inventory_action = inventory_preparation_primary_action(status) + inventory_action = inventory_preparation_primary_action(status, normalized_reason) if inventory_action: return inventory_action, False @@ -553,7 +548,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, break reason_code = (blocking or {}).get('blocking_reason_code') # [STEP] 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - # 库存 RPA 失败统一下发「重新获取库存」,不再因 worker 责任方被技术动作屏蔽。 + # 库存 RPA 超时/耗尽优先下发「重新读取库存结果」,不触发新的 RPA 请求。 next_action, technical_auto_only = _resolve_recovery_next_action( blocking=blocking, full=full, @@ -586,20 +581,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, target for target in recovery_targets if str(target.get('action_code') or '').strip() == 'retry_inventory_preparation' ] - # [AUTHORITY] 上传阶段的 Excel 重生仅在旧 Artifact 仍是未上传 ready 状态时授权; - # 已有成功/未知外部结果或活动 RecoveryPlan 时,后端不下发按钮。 - if any(str(target.get('action_code') or '').strip() == 'regenerate_excel_artifact' for target in recovery_targets): - if not _excel_regeneration_allowed( - execution=execution, - active_recovery_plans=list(full.get('active_recovery_plans') or []), - ): - recovery_targets = [ - target for target in recovery_targets - if str(target.get('action_code') or '').strip() != 'regenerate_excel_artifact' - ] + # 一个 Notice 只能有一个 Excel;错误导出需要创建新的 Notice,而非替代旧 Artifact。 + recovery_targets = [ + target for target in recovery_targets + if str(target.get('action_code') or '').strip() != 'regenerate_excel_artifact' + ] if blocking: if next_action and is_business_user_action(str(next_action)): allowed_actions.append(str(next_action)) + # 超时或耗尽后默认重读已有结果;保留显式 RPA 重试作为备用操作, + # 让用户在确实没有迟到结果时自行决定是否发起新一轮抓取。 + if ( + str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation' + and str(reason_code or '').strip().lower() + in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'} + and 'retry_inventory_preparation' not in allowed_actions + ): + allowed_actions.append('retry_inventory_preparation') # Gate 20 的人工凭据登记是主动作;货代 RPA 仍允许由用户显式重试。 # 该可选动作来自 Gate 契约,不能由前端根据自动上传开关自行补出。 if ( diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index ae95fb2b..56a7674b 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -114,7 +114,7 @@ def _primary_recovery_action( ) -> str | None: """按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。""" if gate.gate_code == 'inventory_preparation': - return inventory_preparation_primary_action(gate.status) + return inventory_preparation_primary_action(gate.status, gate.blocking_reason_code) # 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。 if gate.gate_code == 'inventory_matching' and execution.task_id: return 'retry_inventory_matching' @@ -236,11 +236,11 @@ def request_gate_action( details={'action_code': action}, ) - # Gate 20 的确认必须走 mark-manual-uploaded:该 API 强制校验截图/PDF 凭据与货代回执号。 - # 禁止复用普通 Gate POST,避免调用方绕过人工上传证据门槛。 + # Gate 20 的确认必须走 Notice 上传确认 API:该 API 按 business_no 与唯一 Artifact + # 校验当前履约事实,禁止普通 Gate POST 绕过该边界。 if action == 'mark_manual_uploaded': raise ValidationError( - 'Manual upload confirmation requires evidence registration', + 'Manual upload confirmation must use the shipping notice endpoint', code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', details={'action_code': action, 'gate_code': gate.gate_code}, ) diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 735be71a..2116c5b2 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -1041,7 +1041,7 @@ def apply_user_projection_fields( 'excel_readiness': 5, 'artifact_generation': 6, 'manual_upload_handoff': 7, - 'upload_receipt_recorded': 8, + 'manual_upload_handoff': 8, } current_order = gate_order.get(gate_code) facts['inventory_milestones'] = { diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index a4e483de..6dae0c38 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -254,6 +254,10 @@ def run_task_auto_progress( task = resolve_task_from_payload({'task_no': task_no}) if task_no else None if not task: return tool_response(status="failed", message=f"未找到任务编号 {task_no}") + # 新 Notice 以自身 customer_id 为唯一客户事实;在创建任何 Gate/Job 前 fail-closed。 + customer_gate = customer_gate_tool_response(task, operation='auto_progress') + if customer_gate is not None: + return customer_gate # P0-3:旧 facade 不再直接跨 Gate 调用库存/匹配/Excel。所有触发统一只提交 # 当前正式 Gate;Worker 在事实落库后才创建下一个 Job。 diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index b3e78008..363f91fb 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -2,8 +2,8 @@ services/shipping_notice/query_service.py 用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 -依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 - ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、 +依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 + ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、 ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、 order_review_projection(任务中心 STP retry 动作投影)。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; @@ -34,7 +34,6 @@ from app import db from app.core.errors import ValidationError from app.models import ( FileAsset, - ShippingCase, ShippingExportArtifact, ShippingExportArtifactLine, ShippingInventoryVerification, @@ -46,10 +45,13 @@ from app.models import ( ShippingOrderProcessingRunIntake, ShippingOrderLine, ShippingOrderReviewCase, + ShippingOrderSnapshot, ShippingOrderReviewStream, ShippingOrderSubmission, ShippingReservation, ShippingNotice, + ShippingNoticeLine, + ShippingNoticeLineInventoryMatch, ShippingTaskEvent, ShippingUploadAttempt, ) @@ -83,6 +85,7 @@ from app.services.shipping_notice.task_order_field_editor import ( current_line_field_values_or_empty, current_order_field_display_or_empty, ) +from app.services.shipping_notice.po_number import normalize_po_number EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @@ -130,12 +133,11 @@ _REVIEW_CASE_STATUS_TODO: dict[str, str] = { } -def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[str, str]]: - """裁决建单前 Review Case 的生命周期查看入口。 +def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]: + """复用统一生命周期投影裁决 Review Case 的当前阶段与入口。 - 只有关联当前有效订单 Candidate 的 Case 才能进入订单生命周期工作台;空 Case、 - 已替代 Candidate 与拒绝/过期 Candidate 仍是解析或处置对象,不能因待办列表存在 - 而获得订单复核、库存准备或通知完成入口。 + 当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。 + 此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。 """ candidate = ( db.session.get(ShippingOrderCandidate, int(case.candidate_id)) @@ -144,11 +146,23 @@ def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[s ) from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate - if not is_current_reviewable_candidate(candidate): - return [] - from app.services.shipping_notice.lifecycle_projection import lifecycle_entries + from app.services.shipping_notice.lifecycle_projection import project_lifecycle - return lifecycle_entries(lifecycle_stage='order_review', has_candidate_context=True) + has_candidate_context = is_current_reviewable_candidate(candidate) + if has_candidate_context: + return project_lifecycle( + current_gate=None, + blocking_reason=None, + has_candidate_context=True, + processing_stage='waiting_review', + ) + return project_lifecycle( + current_gate=None, + blocking_reason=None, + has_candidate_context=False, + has_intake_parse_context=False, + processing_stage='document_parsing', + ) class TaskProjection(str, Enum): @@ -211,33 +225,16 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] def get_task_by_ref(task_ref: str) -> ShippingNotice | None: - """按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。""" + """按 task_no、business_no 或数字主键精确查找 Notice。""" value = str(task_ref or "").strip() if not value: return None task = ShippingNotice.query.filter_by(task_no=value).first() if task: return task - case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first() - if case is not None: - visited: set[int] = set() - while case.id not in visited: - visited.add(int(case.id)) - replacement = ( - db.session.query(ShippingCase) - .filter_by(replaces_case_id=case.id) - .order_by(ShippingCase.id.desc()) - .first() - ) - if replacement is None: - break - case = replacement - return ( - db.session.query(ShippingNotice) - .filter_by(shipping_case_id=case.id) - .order_by(ShippingNotice.document_version.desc(), ShippingNotice.id.desc()) - .first() - ) + task = ShippingNotice.query.filter_by(business_no=value.upper()).first() + if task: + return task if value.isdigit(): return db.session.get(ShippingNotice, int(value)) return None @@ -385,9 +382,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: header = current_header_field_values_or_empty(task) payload: dict[str, Any] = { "task_no": task.task_no, - "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, + "business_no": task.business_no, "current_step": task.current_step, "review_status": task.review_status, "match_status": task.match_status, @@ -396,9 +391,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: "customer_code": header.get('customer_code'), "customer_resolution_status": task.customer_resolution_status, "customer_resolution_method": task.customer_resolution_method, - "customer_id": task.shipping_case.customer_id if task.shipping_case else None, - "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, - "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, + "customer_id": task.customer_id, + "customer_name_snapshot": task.customer_name_snapshot, + "customer_short_code_snapshot": task.customer_short_code_snapshot, "ship_to": header.get('ship_to') or header.get('ship_to_address'), "po_number": header.get('po_number'), "required_date": header.get('required_date'), @@ -535,18 +530,16 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str data = { "id": task.id, "task_no": task.task_no, - "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, + "business_no": task.business_no, "source_type": task.source_type, "source_file_name": task.source_file_name, "source_file_type": task.source_file_type, "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, - "customer_id": task.shipping_case.customer_id if task.shipping_case else None, - "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, - "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, + "customer_id": task.customer_id, + "customer_name_snapshot": task.customer_name_snapshot, + "customer_short_code_snapshot": task.customer_short_code_snapshot, "current_step": task.current_step, "review_status": task.review_status, "match_status": task.match_status, @@ -608,7 +601,6 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "po_number": header.get('po_number'), "required_date": header.get('required_date'), "step_payload": step_payload, - "upload_receipt": task.upload_receipt_json or {}, "export_version": task.export_version, "idempotency_key": task.idempotency_key, "lines": current_line_field_values_or_empty(task), @@ -701,7 +693,6 @@ def _todo_category_from_task_row( ui = resolve_task_ui_state_from_fields( review_status=getattr(row, "review_status", None), pending_human_reason=getattr(row, "pending_human_reason", None), - shipping_case_id=getattr(row, "shipping_case_id", None), customer_resolution_status=getattr(row, "customer_resolution_status", None), order_snapshot_id=getattr(row, "order_snapshot_id", None), inventory_lines_json=getattr(row, "inventory_lines_json", None), @@ -797,6 +788,41 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None: } +def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: + """ + 投影发货通知列表需要的项次、料号、数量与当前库存事实。 + + 核心逻辑:Notice 行定义“本通知包含哪些业务行”;当前库存只读取同 Notice、 + `is_current=true` 的匹配事实。未找到匹配事实时明确返回 null,禁止由前端估算库存。 + """ + if task.id is None: + return [] + matches_by_line_key = { + str(item.line_key): item + for item in ShippingNoticeLineInventoryMatch.query.filter( + ShippingNoticeLineInventoryMatch.task_id == int(task.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ).all() + if item.line_key + } + rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by( + ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(), + ).all() + return [{ + 'line_no': (item.field_values_json or {}).get('line_no') or item.position, + 'part_number': item.part_number, + 'customer_part_number': (item.field_values_json or {}).get('customer_part_number'), + 'reservation_id': item.reservation_id, + 'shipment_qty': str(item.required_qty) if item.required_qty is not None else None, + 'available_qty': matches_by_line_key.get(str(item.line_key or '')).available_qty + if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + 'shortage_qty': matches_by_line_key.get(str(item.line_key or '')).shortage_qty + if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + 'inventory_status': matches_by_line_key.get(str(item.line_key or '')).inventory_status + if matches_by_line_key.get(str(item.line_key or '')) is not None else None, + } for item in rows] + + def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None: """ 将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。 @@ -888,6 +914,7 @@ def _enrich_task_center_fields( data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin) data["recent_event"] = _latest_task_event_summary(task) data["artifact_summary"] = _artifact_summary_for_task(task) + data['notice_line_summary'] = _notice_line_summary_for_task(task) # [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。 from app.services.shipping_notice.ui_state import build_task_ui_state @@ -1055,20 +1082,103 @@ def get_task_visible_to_user( return task +def list_freight_notice_groups_for_task( + task: ShippingNotice, + *, + user_id: int, + is_admin: bool = False, +) -> dict[str, Any]: + """ + 按当前 Notice 所属客户 PO 返回货代上传的 Notice 聚合行。 + + 核心逻辑:一个 business_no 就是一张独立发货 Excel;同一 PO 后续补货产生的 + Notice 必须作为另一组返回。查询只取当前用户可见的 active Notice,且强制排除尚未 + 分配 business_no 的历史/中间对象,前端不得由 PDF 草稿行猜测分组。 + + Args: + task: 当前订单工作台已授权读取的正式 Notice。 + user_id: 当前用户;非管理员仅返回其创建的 Notice。 + is_admin: 管理员只读可见范围。 + + Returns: + 包含 PO 及一行一个 business_no 的货代上传聚合投影。 + """ + po_number = _notice_po_number(task) + if not po_number: + return {'po_number': None, 'items': [], 'reason': 'po_missing'} + + candidates = ShippingNotice.query.filter( + ShippingNotice.deleted_at.is_(None), + ShippingNotice.lifecycle_status == 'active', + ShippingNotice.business_no.isnot(None), + ) + if not is_admin: + candidates = candidates.filter(ShippingNotice.user_id == int(user_id)) + + items: list[dict[str, Any]] = [] + for notice in candidates.order_by(ShippingNotice.created_at.asc(), ShippingNotice.id.asc()).all(): + if _notice_po_number(notice) != po_number: + continue + business_no = str(notice.business_no or '').strip() + if not business_no: + continue + # [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。 + from app.services.shipping_notice.ui_state import build_task_ui_state + actions = (build_task_ui_state(notice).get('actions') or {}) + available_actions = [ + str(action.get('code')).strip() + for action in [actions.get('primary'), *(actions.get('secondary') or [])] + if isinstance(action, dict) and action.get('enabled') is True and str(action.get('code') or '').strip() + ] + items.append({ + 'business_no': business_no, + 'po_number': po_number, + 'upload_status': notice.upload_status, + 'export_file_name': notice.export_file_name, + 'available_actions': available_actions, + 'lines': _notice_line_summary_for_task(notice), + }) + return { + 'po_number': po_number, + 'items': items, + 'reason': None if items else 'no_business_notice', + } + + +def _notice_po_number(notice: ShippingNotice) -> str: + """读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。""" + header = current_header_field_values_or_empty(notice) + for field_code in ('customer_po_number', 'po_number'): + normalized = normalize_po_number(header.get(field_code)) + if normalized: + return normalized + + snapshot = None + if notice.order_snapshot_id: + snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id) + if snapshot: + for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')): + normalized = normalize_po_number(value) + if normalized: + return normalized + + candidate = ( + db.session.get(ShippingOrderCandidate, notice.source_candidate_id) + if notice.source_candidate_id else None + ) + normalized = normalize_po_number(getattr(candidate, 'po_number', None)) + return normalized + + def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool: - """待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。""" + """待办列表客户关键字过滤:匹配 Notice 快照、来源文件名或当前订单头客户名。""" needle = str(customer or "").strip().lower() if not needle: return True - case = task.shipping_case candidates: list[str] = [] - if case is not None: - for value in ( - getattr(case, "customer_name_snapshot", None), - getattr(case, "customer_short_code_snapshot", None), - ): - if value: - candidates.append(str(value)) + for value in (task.customer_name_snapshot, task.customer_short_code_snapshot): + if value: + candidates.append(str(value)) if task.source_file_name: candidates.append(str(task.source_file_name)) header = current_header_field_values_or_empty(task) @@ -1133,7 +1243,19 @@ def serialize_review_case_todo( del is_admin run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None - lifecycle_entries = _review_case_lifecycle_entries(case) + lifecycle = _review_case_lifecycle_projection(case) + lifecycle_stage = str(lifecycle.get('lifecycle_stage') or 'unclassified') + lifecycle_entries = list(lifecycle.get('lifecycle_entries') or []) + from app.services.shipping_notice.lifecycle_projection import LIFECYCLE_STAGES + stage_index = next( + (index for index, item in enumerate(LIFECYCLE_STAGES) + if item.get('code') == lifecycle_stage), + 0, + ) + stage_definition = next( + (item for item in LIFECYCLE_STAGES if item['code'] == lifecycle_stage), + {'code': lifecycle_stage, 'label': '状态待同步'}, + ) source_name = None if document is not None: source_name = str(getattr(document, "filename", None) or "").strip() or None @@ -1191,18 +1313,19 @@ def serialize_review_case_todo( "updated_at": case.updated_at.isoformat() if case.updated_at else None, "created_at": case.created_at.isoformat() if case.created_at else None, "ui_state": { - "stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4}, - # [AUTHORITY] 任务中心、批次中心和工作台均消费该入口;禁止前端按 Case - # 状态或待办类别补造订单复核权限。 - "lifecycle_stage": "order_review" if lifecycle_entries else None, + "stage": {**stage_definition, "index": stage_index + 1, "total": len(LIFECYCLE_STAGES)}, + # [AUTHORITY] 任务中心、批次中心和工作台均消费统一生命周期投影; + # 前端不得按 Case 状态或待办类别补造订单复核权限。 + "lifecycle_stage": lifecycle_stage, "lifecycle_entries": lifecycle_entries, - "checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"}, + "intake_parse_authorized": lifecycle_stage == "intake_parse", + "checkpoint": {"code": lifecycle_stage, "kind": str(CheckpointKind.MUST_HUMAN), "label": stage_definition['label']}, "todo": {"title": current_todo, "message": current_todo}, "actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []}, "reason": {"code": f"review_case_{case.status}", "message": current_todo}, "lifecycle_status": "active", "process_gate": None, - "checkpoint_code": "order_review", + "checkpoint_code": lifecycle_stage, "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "summary": { "title": "待人工复核", @@ -1524,11 +1647,7 @@ def _task_todo_category_sql_expr(): (reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")), ( db.and_( - ShippingNotice.shipping_case_id.isnot(None), - db.or_( - ShippingNotice.customer_resolution_status.is_(None), - ShippingNotice.customer_resolution_status != "confirmed", - ), + ShippingNotice.customer_resolution_status.in_(("pending", "needs_review", "failed", "unresolved")), ), literal("exception"), ), @@ -1633,10 +1752,10 @@ def _todo_tasks_base_query( if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) if customer_needle: - q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingNotice.shipping_case_id).filter( + q = q.filter( db.or_( - ShippingCase.customer_name_snapshot.ilike(customer_like), - ShippingCase.customer_short_code_snapshot.ilike(customer_like), + ShippingNotice.customer_name_snapshot.ilike(customer_like), + ShippingNotice.customer_short_code_snapshot.ilike(customer_like), ShippingNotice.source_file_name.ilike(customer_like), ) ) diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index e96d7a99..08953eab 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -225,6 +225,7 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_STP_AUTO_CREATE, JobType.SHIPPING_LINE_AUTO_FULFILL, JobType.SHIPPING_POST_OT_WAVE_PROGRESS, + JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS, ], ) diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py index 1e387503..46153535 100644 --- a/backend/app/services/shipping_notice/recovery_invalidation_service.py +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -133,7 +133,7 @@ def invalidate_excel_regeneration_only( ).with_for_update().all() for artifact in artifacts: uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).with_for_update().all() - # 成功上传或已登记货代回执是不可逆外部事实,不能用 Excel 重生覆盖。 + # 成功上传或已有外部上传参考是不可逆外部事实,不能用 Excel 重生覆盖。 if artifact.status == 'uploading' or any( upload.status == 'succeeded' or str(upload.freight_ref_no or '').strip() for upload in uploads diff --git a/backend/app/services/shipping_notice/reservation_region.py b/backend/app/services/shipping_notice/reservation_region.py new file mode 100644 index 00000000..62984a02 --- /dev/null +++ b/backend/app/services/shipping_notice/reservation_region.py @@ -0,0 +1,160 @@ +""" +Reservation ID 专用证据区域解析器。 + +用途:从管理员圈选的 Vendor Comments 区域提取 Reservation ID 和可选行号。 +依赖:reservation_id 的统一格式校验。 +逻辑:只消费区域文字,不依赖客户名称、固定坐标或旧的三来源映射;无行号仅标记为未归属,最终由 Schema scope 决定表头写入或明细复核。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any + +from app.services.shipping_notice.document_layout.coordinate_region_text import visual_text_lines +from app.services.shipping_notice.reservation_id import validated_reservation_id + + +_ID_RE = re.compile(r"(? list[ReservationRegionCandidate]: + """从区域原文提取候选;有行号归明细,无行号归订单头。""" + candidates: list[ReservationRegionCandidate] = [] + for raw_line in (str(text or '').splitlines() or [str(text or '')]): + line = raw_line.strip() + # A selected comments area can also contain customer numbers, quantities, + # and dates. Only a value on a Reservation-labelled line is evidence. + if not line or not _RESERVATION_LABEL_RE.search(line): + continue + ids = [validated_reservation_id(m.group(1)) for m in _ID_RE.finditer(line)] + ids = [value for value in ids if value] + if not ids: + continue + line_match = _LINE_RE.search(line) + line_no = None + if line_match: + line_no = int(line_match.group(1) or line_match.group(2)) + scope = 'line' if line_no is not None else 'header' + status = 'mapped' if line_no is not None else 'header' + for value in dict.fromkeys(ids): + candidates.append(ReservationRegionCandidate(value, line_no, scope, line, status)) + return candidates + + +def extract_reservation_from_region_text(text: str) -> list[dict[str, object]]: + """返回 API/预览可直接序列化的统一候选 DTO。""" + return [ + { + 'value': item.value, + 'line_no': item.line_no, + 'scope': item.scope, + 'raw_text': item.raw_text, + 'status': item.status, + } + for item in extract_reservation_from_region(text) + ] + + +def extract_reservation_from_vendor_comments_pages( + pages: list[tuple[int, list[dict[str, Any]]]], +) -> tuple[list[dict[str, object]], str | None]: + """从跨页 Vendor Comments 区块提取 Reservation;仅首个 Terms 标题前的文字有效。 + + 核心逻辑:Reservation 专区已启用时,页面坐标只是提供稳定阅读顺序,不能作为固定 + 页码或矩形取值依据。缺少起止锚点时返回稳定原因,由调用方转人工复核。 + """ + started = False + window_lines: list[str] = [] + for _page_no, glyphs in sorted(pages, key=lambda item: item[0]): + for line in visual_text_lines(glyphs): + if not started: + if _VENDOR_COMMENTS_HEADING_RE.fullmatch(line): + started = True + continue + if _TERMS_AND_CONDITIONS_HEADING_RE.fullmatch(line): + return extract_reservation_from_region_text('\n'.join(window_lines)), None + window_lines.append(line) + if not started: + return [], 'vendor_comments_anchor_missing' + return [], 'terms_and_conditions_anchor_missing' + + +def apply_reservation_region_candidates( + *, candidates: list[dict[str, object]], header_field_id: str | None, + line_field_id: str | None, line_count: int, +) -> ReservationRegionApplication: + """按固定契约将专用区域候选归属到订单头和逻辑明细行。 + + 无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在 + Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或 + 多个不同整单值必须转人工复核,不能静默猜测。 + """ + _ = header_field_id + header_values: list[str] = [] + line_values_by_no: dict[int, list[str]] = {} + reasons: list[str] = [] + for item in candidates: + if not isinstance(item, dict): + continue + value = str(item.get('value') or '') + if not value: + continue + if item.get('scope') == 'header': + header_values.append(value) + continue + if item.get('scope') != 'line' or item.get('line_no') is None: + continue + try: + line_no = int(item['line_no']) + except (TypeError, ValueError): + reasons.append('line_out_of_range') + continue + if line_no < 1 or line_no > line_count: + reasons.append('line_out_of_range') + continue + if line_field_id: + line_values_by_no.setdefault(line_no, []).append(value) + else: + reasons.append('line_field_unavailable') + + unique_headers = list(dict.fromkeys(header_values)) + if len(unique_headers) > 1: + reasons.append('conflicting_header_value') + resolved_lines: dict[int, str] = {} + for line_no, values in line_values_by_no.items(): + unique_values = list(dict.fromkeys(values)) + if len(unique_values) > 1: + reasons.append('conflicting_line_value') + continue + resolved_lines[line_no] = unique_values[0] + return ReservationRegionApplication( + header_value=unique_headers[0] if len(unique_headers) == 1 else None, + line_values=resolved_lines, + needs_review=bool(reasons), + review_reasons=tuple(dict.fromkeys(reasons)), + ) diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 5586b2fa..372b92ed 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -180,6 +180,7 @@ def reserve_available_for_artifact( artifact: ShippingExportArtifact, verification: ShippingInventoryVerification, released_snapshot_line_ids: set[int] | None = None, + selected_snapshot_line_ids: set[int] | None = None, ) -> list[ShippingReservation]: """ 锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。 @@ -193,6 +194,7 @@ def reserve_available_for_artifact( artifact: 已落库但尚未提交的导出 Artifact。 verification: 当前库存核验轮次。 released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。 + selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时不得占用集合外行。 Returns: 本次被 Artifact 占用的预约单。 @@ -226,7 +228,12 @@ def reserve_available_for_artifact( ) if not rows: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') - selected = [item for item in rows if item.id in verification_lines] + selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())} + selected = [ + item for item in rows + if item.id in verification_lines + and (not selected_ids or int(item.snapshot_line_id) in selected_ids) + ] if not selected: raise ConflictError('Current verification has no available reservations', code='SHIPPING.ROLLING_EXPORT_NOT_READY') for reservation in selected: @@ -244,6 +251,7 @@ def current_available_snapshot_line_ids( task: ShippingNotice, *, released_snapshot_line_ids: set[int] | None = None, + selected_snapshot_line_ids: set[int] | None = None, ) -> tuple[ShippingInventoryVerification, set[int]]: """ 取得最新核验中可导出的冻结订单行。 @@ -254,6 +262,7 @@ def current_available_snapshot_line_ids( Args: task: 当前正式发货任务。 released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。 + selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。 Returns: (最新核验轮次, 本次可导出的冻结订单行 ID)。 @@ -288,7 +297,11 @@ def current_available_snapshot_line_ids( ShippingReservation.id.in_(reservation_ids), ShippingReservation.status.in_({'available', 'pending'}), ).all() if reservation_ids else [] - line_ids = {item.snapshot_line_id for item in reservations} + selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())} + line_ids = { + item.snapshot_line_id for item in reservations + if not selected_ids or int(item.snapshot_line_id) in selected_ids + } if not line_ids: raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY') return verification, line_ids diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 3f7dd962..8b4f550e 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -147,7 +147,6 @@ def resolve_task_ui_state_from_fields( *, review_status: str | None, pending_human_reason: str | None, - shipping_case_id: int | None, customer_resolution_status: str | None, order_snapshot_id: int | None, inventory_lines_json: Any, @@ -188,7 +187,7 @@ def resolve_task_ui_state_from_fields( if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED) - if shipping_case_id is not None and customer_resolution_status != "confirmed": + if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}: return _task_ui_state(CP_CUSTOMER_REVIEW) # [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。 @@ -254,7 +253,6 @@ def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState: return resolve_task_ui_state_from_fields( review_status=task.review_status, pending_human_reason=task.pending_human_reason, - shipping_case_id=task.shipping_case_id, customer_resolution_status=task.customer_resolution_status, order_snapshot_id=task.order_snapshot_id, inventory_lines_json=task.inventory_lines_json, diff --git a/backend/app/services/shipping_notice/task_disposition_service.py b/backend/app/services/shipping_notice/task_disposition_service.py index 1af2d521..985aa41e 100644 --- a/backend/app/services/shipping_notice/task_disposition_service.py +++ b/backend/app/services/shipping_notice/task_disposition_service.py @@ -3,7 +3,7 @@ services/shipping_notice/task_disposition_service.py 用途:集中处理发货任务的回收站、作废与归档生命周期,避免混用业务阶段和生命周期。 依赖:ShippingNotice / ShippingTaskEvent、fulfillment_audit.record_fulfillment_audit、 - SQLAlchemy 行锁、ShippingCase 生命周期事实。 + SQLAlchemy 行锁、ShippingNotice 生命周期事实。 逻辑:workspace 批量处置 API 通过本模块锁定任务、重算资格;TaskEvent 与 ShippingAuditEvent 双写稳定 reason_code;编排与回调阶段读取本模块的 active 判定以阻断副作用。 """ @@ -14,8 +14,6 @@ from dataclasses import dataclass from datetime import datetime from typing import Any, Literal -from sqlalchemy.orm import joinedload - from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( @@ -99,7 +97,7 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice: if not normalized_task_no: raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED') task = ( - ShippingNotice.query.options(joinedload(ShippingNotice.shipping_case)) + ShippingNotice.query .filter(ShippingNotice.task_no == normalized_task_no) .with_for_update() .first() @@ -110,11 +108,10 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice: def _has_external_fulfillment(task: ShippingNotice) -> bool: - """识别已提交、正在提交或已有货代回执的任务;这些任务不可在平台单方作废。""" + """识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。""" upload_status = str(task.upload_status or '').strip().lower() return bool( task.freight_ref_no - or task.upload_receipt_json or upload_status in _EXTERNAL_UPLOAD_STATUSES ) @@ -285,7 +282,8 @@ def move_task_to_recycle_bin( # [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。 has_internal_business_record = bool( - task.shipping_case_id + task.business_no + or task.customer_id or task.source_candidate_id or task.match_status or task.export_file_path @@ -421,7 +419,8 @@ def purge_task_permanently( # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 blocking_counts = { - 'shipping_case': int(bool(task.shipping_case_id)), + 'business_number': int(bool(task.business_no)), + 'customer': int(bool(task.customer_id)), 'source_asset': int(bool(task.source_asset_id)), 'source_intake': int(bool(task.source_intake_id)), 'source_candidate': int(bool(task.source_candidate_id)), diff --git a/backend/app/services/shipping_notice/task_supersession_service.py b/backend/app/services/shipping_notice/task_supersession_service.py index 59815325..59a90aa4 100644 --- a/backend/app/services/shipping_notice/task_supersession_service.py +++ b/backend/app/services/shipping_notice/task_supersession_service.py @@ -18,7 +18,7 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID') if not task_is_active(old): return - external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) + external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) if external: existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none() if existing is None: diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index f41da291..3d9da679 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -51,7 +51,6 @@ from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, assert_no_exact_duplicate_notices, ) -from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.candidate_qualification_service import ( assert_customer_confirmed_before_task_create, resolve_confirmed_bill_to_customer_id, @@ -140,35 +139,27 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: checkpoint=CP_TASK_EXISTS, ) - shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id")) # [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。 customer_id = _parse_optional_customer_id(payload.get("customer_id")) assert_customer_confirmed_before_task_create( - shipping_case=shipping_case, customer_id=customer_id, ) task = ShippingNotice( task_no=generate_task_no(), - shipping_case_id=shipping_case.id, + customer_id=customer_id, user_id=payload.get("user_id"), conversation_id=str(payload.get("conversation_id") or "").strip() or None, source_type=str(payload.get("source_type") or "manual"), batch_index=1, batch_total=1, raw_content=str(payload.get("raw_content") or "").strip() or None, - customer_resolution_status=( - 'confirmed' if shipping_case.customer_id is not None else 'pending' - ), - customer_resolution_method=( - 'inherited' if shipping_case.customer_id is not None else None - ), + customer_resolution_status='pending', ) db.session.add(task) log_task_event(task, "task_created", {"source_type": task.source_type}) db.session.flush() _bind_confirmed_customer_after_task_create( task, - shipping_case=shipping_case, customer_id=customer_id, candidate=None, actor_id=payload.get("user_id"), @@ -201,7 +192,6 @@ def _parse_optional_customer_id(raw: Any) -> int | None: def _bind_confirmed_customer_after_task_create( task: ShippingNotice, *, - shipping_case: Any, customer_id: int | None, candidate: ShippingOrderCandidate | None, actor_id: Any, @@ -209,12 +199,8 @@ def _bind_confirmed_customer_after_task_create( """ 创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。 - 核心逻辑:业务单已有客户则标记 inherited;否则用显式 customer_id 或候选 Bill-to 确认。 + 核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。 """ - if getattr(shipping_case, 'customer_id', None) is not None: - task.customer_resolution_status = 'confirmed' - task.customer_resolution_method = task.customer_resolution_method or 'inherited' - return bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate) if bind_id is None: raise ConflictError( diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index b6d3ae13..2a2b3e53 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -92,8 +92,8 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"), CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"), CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"), - CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), - CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), + CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), + CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"), } def _task_lifecycle( @@ -470,9 +470,9 @@ def _build_task_summary( RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。", CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。", - CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", - CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。", - CP_WAITING_UPLOAD: "待人工上传登记:请下载 Excel,在货代平台上传后于本系统登记凭据。", + CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。", + CP_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。", CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。", CP_REJECTED: "任务已驳回,无需继续处理。", CP_UPLOADED: "任务已完成上传。", diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index 96ec4ff3..f9cbd227 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -1,8 +1,8 @@ """ services/shipping_notice/upload_attempt_service.py -用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工回执证据。 -依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、FileAsset、任务状态机。 +用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。 +依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。 逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。 """ @@ -21,7 +21,6 @@ from app.models import ( ShippingNotice, ShippingUploadAttempt, ) -from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced def current_upload_artifact(task: ShippingNotice, artifact_id: int | None = None) -> ShippingExportArtifact: @@ -84,7 +83,7 @@ def has_verified_upload_success(task: ShippingNotice) -> bool: """判断任务是否具备可审计的货代上传成功事实。 业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、 - 单独回执号或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次 + 单独外部参考或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次 已完成分组与停止轮询共用的唯一成功谓词。 """ try: @@ -182,41 +181,36 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa return attempt -def record_manual_upload(task: ShippingNotice, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt: - """登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。""" - asset_no = str(evidence_asset_no or '').strip() - receipt_no = str(freight_ref_no or '').strip() - if not asset_no or not receipt_no: - raise ValidationError( - 'Manual upload receipt number and evidence are required', - code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED', - details={'reason_code': 'close_blocked_missing_receipt'}, - ) +def record_manual_upload(task: ShippingNotice, *, artifact_id: int | None, operator_id: int) -> ShippingUploadAttempt: + """ + 确认指定 Excel 已由人工上传;仅记录目标 Artifact 与服务端操作人,不再采集回执或截图/PDF。 + + Args: + task: 目标发货通知任务,必须处于可履约状态。 + artifact_id: 当前通知单唯一待上传 Excel 的 Artifact 主键;为空时服务端选择唯一可上传 Artifact。 + operator_id: 服务端会话中的操作人主键,禁止由客户端伪造。 + + Returns: + ShippingUploadAttempt: 已成功的人工上传确认尝试。 + + Raises: + ConflictError: 任务或 Artifact 不再允许上传时抛出。 + """ from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked if not task_is_active(task): raise ConflictError('Inactive task cannot be manually uploaded', code='SHIPPING.TASK_LIFECYCLE_CONFLICT') assert_task_not_supersession_blocked(task) artifact = current_upload_artifact(task, artifact_id) - asset = get_asset_for_user(asset_no, operator_id) - if asset.upload_status != 'ready' or asset.deleted_at is not None: - raise ValidationError( - 'Manual upload evidence is unavailable', - code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED', - details={'reason_code': 'close_blocked_missing_receipt'}, - ) attempt = ShippingUploadAttempt( artifact_id=artifact.id, attempt_no=ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() + 1, mode='manual', idempotency_key=f'manual:{artifact.id}:{uuid.uuid4().hex}', - status='running', started_at=datetime.utcnow(), evidence_asset_id=asset.id, operator_id=operator_id, + status='running', started_at=datetime.utcnow(), operator_id=operator_id, ) db.session.add(attempt) db.session.flush() - mark_asset_referenced(asset) - return complete_attempt( - attempt, success=True, callback_id=f'manual:{attempt.id}', freight_ref_no=receipt_no, - ) + return complete_attempt(attempt, success=True, callback_id=f'manual:{attempt.id}') def void_rejected_artifact(task: ShippingNotice, *, artifact_id: int, operator_id: int, reason: str) -> ShippingExportArtifact: diff --git a/backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py b/backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py new file mode 100644 index 00000000..144af933 --- /dev/null +++ b/backend/migrations/versions/hn7o8p9q0r1s_add_notice_business_number.py @@ -0,0 +1,64 @@ +"""为 ShippingNotice 增加独立发货通知业务编号。 + +用途:支持同一 PO 多个发货通知单各自拥有 business_no。 +依赖:shipping_notices、shipping_cases、shipping_business_sequences。 +逻辑:新增可空字段并从旧 Case 回填仅能唯一映射的历史 Notice;无法唯一映射的记录保留空值等待业务迁移。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'hn7o8p9q0r1s' +down_revision = 'hm6n7o8p9q0r' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 Notice 编号字段并安全回填一对一历史映射。""" + inspector = sa.inspect(op.get_bind()) + columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + with op.batch_alter_table('shipping_notices') as batch: + if 'business_no' not in columns: + batch.add_column(sa.Column('business_no', sa.String(length=32), nullable=True)) + if 'business_date' not in columns: + batch.add_column(sa.Column('business_date', sa.Date(), nullable=True)) + if 'business_sequence_value' not in columns: + batch.add_column(sa.Column('business_sequence_value', sa.Integer(), nullable=True)) + if 'business_numbering_rule_version' not in columns: + batch.add_column(sa.Column('business_numbering_rule_version', sa.String(length=32), nullable=True)) + indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} + if 'ix_shipping_notices_business_no' not in indexes: + batch.create_index('ix_shipping_notices_business_no', ['business_no'], unique=False) + uniques = {item['name'] for item in inspector.get_unique_constraints('shipping_notices')} + if 'uq_shipping_notices_business_no' not in uniques: + batch.create_unique_constraint('uq_shipping_notices_business_no', ['business_no']) + + bind = op.get_bind() + bind.execute(sa.text(""" + UPDATE shipping_notices AS n + SET business_no = c.business_no, + business_date = c.business_date, + business_sequence_value = c.sequence_value, + business_numbering_rule_version = c.numbering_rule_version + FROM shipping_cases AS c + WHERE n.shipping_case_id = c.id + AND c.business_no IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM shipping_notices AS other + WHERE other.business_no = c.business_no AND other.id <> n.id + ) + """)) + + +def downgrade() -> None: + """移除 Notice 独立编号字段;旧 Case 编号仍保留。""" + with op.batch_alter_table('shipping_notices') as batch: + batch.drop_constraint('uq_shipping_notices_business_no', type_='unique') + batch.drop_index('ix_shipping_notices_business_no') + batch.drop_column('business_numbering_rule_version') + batch.drop_column('business_sequence_value') + batch.drop_column('business_date') + batch.drop_column('business_no') diff --git a/backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py b/backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py new file mode 100644 index 00000000..fdfb0f5f --- /dev/null +++ b/backend/migrations/versions/ho8p9q0r1s2t_notice_customer_facts.py @@ -0,0 +1,60 @@ +"""将客户身份事实迁移到 ShippingNotice。 + +用途:支持 Notice 在不依赖 ShippingCase 的情况下完成客户确认、业务编号和履约。 +依赖:shipping_notices、shipping_customers、shipping_cases。 +逻辑:新增 Notice 客户字段并从历史 Case 回填;旧 Case 外键暂留只读兼容。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'ho8p9q0r1s2t' +down_revision = 'hn7o8p9q0r1s' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增 Notice 客户字段并回填历史 Case 客户事实。""" + inspector = sa.inspect(op.get_bind()) + columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + with op.batch_alter_table('shipping_notices') as batch: + if 'customer_id' not in columns: + batch.add_column(sa.Column('customer_id', sa.Integer(), nullable=True)) + if 'customer_name_snapshot' not in columns: + batch.add_column(sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True)) + if 'customer_short_code_snapshot' not in columns: + batch.add_column(sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True)) + indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} + if 'ix_shipping_notices_customer_id' not in indexes: + batch.create_index('ix_shipping_notices_customer_id', ['customer_id'], unique=False) + foreign_keys = {item.get('name') for item in inspector.get_foreign_keys('shipping_notices')} + if 'fk_shipping_notices_customer_id' not in foreign_keys: + batch.create_foreign_key( + 'fk_shipping_notices_customer_id', 'shipping_customers', ['customer_id'], ['id'], + ) + + bind = op.get_bind() + bind.execute(sa.text(""" + UPDATE shipping_notices AS n + SET customer_id = c.customer_id, + customer_name_snapshot = c.customer_name_snapshot, + customer_short_code_snapshot = c.customer_short_code_snapshot + FROM shipping_cases AS c + WHERE n.shipping_case_id = c.id + AND n.customer_id IS NULL + AND c.customer_id IS NOT NULL + """)) + + +def downgrade() -> None: + """回滚 Notice 客户字段;历史 Case 字段不受影响。""" + with op.batch_alter_table('shipping_notices') as batch: + batch.drop_constraint('fk_shipping_notices_customer_id', type_='foreignkey') + batch.drop_index('ix_shipping_notices_customer_id') + batch.drop_column('customer_short_code_snapshot') + batch.drop_column('customer_name_snapshot') + batch.drop_column('customer_id') diff --git a/backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py b/backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py new file mode 100644 index 00000000..6dc81b31 --- /dev/null +++ b/backend/migrations/versions/hp9q0r1s2t3u_remove_shipping_case.py @@ -0,0 +1,105 @@ +"""物理移除已废弃的 ShippingCase 聚合层。 + +用途:在历史 Notice 已自持客户与 business_no 后,删除 shipping_cases 表及 Notice 外键。 +依赖:shipping_notices、shipping_customers、shipping_business_sequences。 +逻辑:先检查残留客户/编号事实,再断开 Notice 旧外键并删除历史聚合表;不影响 Review Case 或收料 RPA。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'hp9q0r1s2t3u' +down_revision = 'ho8p9q0r1s2t' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """校验 Notice 已完成迁移后删除 Case 表和兼容字段。""" + bind = op.get_bind() + inspector = sa.inspect(bind) + if not inspector.has_table('shipping_cases'): + return + + # 历史库可能错误标记为已执行 hn/ho,但物理表仍缺少其应新增的列。 + # 最终删表迁移必须先自愈这些可由旧 Case 无损恢复的事实,不能引用缺失列。 + notice_columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + missing_columns = [ + ('business_no', sa.String(length=32)), + ('business_date', sa.Date()), + ('business_sequence_value', sa.Integer()), + ('business_numbering_rule_version', sa.String(length=32)), + ('customer_id', sa.Integer()), + ('customer_name_snapshot', sa.String(length=200)), + ('customer_short_code_snapshot', sa.String(length=6)), + ] + missing_notice_fields = {name for name, _ in missing_columns if name not in notice_columns} + with op.batch_alter_table('shipping_notices') as batch: + for name, column_type in missing_columns: + if name in missing_notice_fields: + batch.add_column(sa.Column(name, column_type, nullable=True)) + + # 重新读取反射信息,确保修复后的 PostgreSQL/SQLite 结构都用于后续约束和校验。 + inspector = sa.inspect(bind) + notice_columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + case_columns = {item['name'] for item in inspector.get_columns('shipping_cases')} + copied_fields = [ + ('business_no', 'business_no'), + ('business_date', 'business_date'), + ('business_sequence_value', 'sequence_value'), + ('business_numbering_rule_version', 'numbering_rule_version'), + ('customer_id', 'customer_id'), + ('customer_name_snapshot', 'customer_name_snapshot'), + ('customer_short_code_snapshot', 'customer_short_code_snapshot'), + ] + assignments = [ + f"{notice_field} = COALESCE(n.{notice_field}, c.{case_field})" + for notice_field, case_field in copied_fields + if notice_field in missing_notice_fields and case_field in case_columns + ] + if assignments: + bind.execute(sa.text(f""" + UPDATE shipping_notices AS n + SET {', '.join(assignments)} + FROM shipping_cases AS c + WHERE c.id = n.shipping_case_id + """)) + + # Notice 是最终事实;旧 Case 若仍有未迁移编号或客户,拒绝静默丢失。 + residual = bind.execute(sa.text(""" + SELECT COUNT(*) + FROM shipping_notices AS n + JOIN shipping_cases AS c ON c.id = n.shipping_case_id + WHERE (c.business_no IS NOT NULL AND n.business_no IS NULL) + OR (c.customer_id IS NOT NULL AND n.customer_id IS NULL) + """)).scalar_one() + if int(residual or 0): + raise RuntimeError( + f'shipping_case migration incomplete: {int(residual)} Notice rows still miss copied facts' + ) + + notice_indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')} + notice_fks = inspector.get_foreign_keys('shipping_notices') + with op.batch_alter_table('shipping_notices') as batch: + for fk in notice_fks: + referred = str(fk.get('referred_table') or '') + columns = set(fk.get('constrained_columns') or []) + if referred == 'shipping_cases' and 'shipping_case_id' in columns: + if fk.get('name'): + batch.drop_constraint(fk['name'], type_='foreignkey') + if 'ix_shipping_notices_shipping_case_id' in notice_indexes: + batch.drop_index('ix_shipping_notices_shipping_case_id') + if 'shipping_case_id' in notice_columns: + batch.drop_column('shipping_case_id') + + # PostgreSQL 的 UNIQUE 约束拥有同名底层索引,不能先以 index 操作删除; + # DROP TABLE 会一并清理 Case 表上的普通索引和约束索引。 + op.drop_table('shipping_cases') + + +def downgrade() -> None: + """不自动恢复已删除的历史 Case 数据。""" + raise RuntimeError('ShippingCase removal migration is irreversible') diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index fd2a67b1..2fe061df 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -251,7 +251,7 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction db.session.flush() extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - customer = getattr(getattr(task, 'shipping_case', None), 'customer', None) + customer = getattr(task, 'customer', None) if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by( extraction_id=extraction.id, role='bill_to', ).one_or_none() is None: diff --git a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py index 5448d3e3..08e34f3e 100644 --- a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py +++ b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py @@ -16,7 +16,7 @@ from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingCase, + ShippingNotice, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -74,14 +74,14 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app): @pytest.mark.parametrize('reference_kind', [ - 'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', + 'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', ]) def test_business_and_audit_references_block_delete(app, reference_kind: str): """每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。""" with app.app_context(): customer = _customer() - if reference_kind == 'case': - db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id)) + if reference_kind == 'notice': + db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id)) elif reference_kind == 'sequence': db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) elif reference_kind == 'external_ref': @@ -194,14 +194,14 @@ def test_delete_unused_customer_cascades_configurable_identity_evidence(app): @pytest.mark.parametrize('reference_kind', [ - 'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', + 'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', ]) def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str): """永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。""" with app.app_context(): customer = _customer('BLK') - if reference_kind == 'case': - db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id)) + if reference_kind == 'notice': + db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id)) elif reference_kind == 'sequence': db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) elif reference_kind == 'external_ref': @@ -267,13 +267,13 @@ def test_delete_blocks_reference_created_after_preview(app): preview = get_customer_lifecycle_impact(customer.id) assert preview['can_delete'] is True - db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id)) + db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id)) db.session.commit() with pytest.raises(ConflictError) as exc_info: delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None) assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED' - assert exc_info.value.details['blockers']['business_cases'] == 1 + assert exc_info.value.details['blockers']['shipping_notices'] == 1 assert db.session.get(ShippingCustomer, customer.id) is not None diff --git a/backend/tests/services/admin/test_shipping_customer_merge_service.py b/backend/tests/services/admin/test_shipping_customer_merge_service.py index a4d308b8..0d311e3f 100644 --- a/backend/tests/services/admin/test_shipping_customer_merge_service.py +++ b/backend/tests/services/admin/test_shipping_customer_merge_service.py @@ -16,7 +16,7 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingBusinessSequence, - ShippingCase, + ShippingNotice, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, @@ -71,8 +71,8 @@ def test_merge_moves_future_configuration_and_preserves_history(app): normalized_value='same@example.com', status='approved', source='manual', ), ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'), - ShippingCase( - case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601', + ShippingNotice( + task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601', customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code, ), ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1), @@ -82,7 +82,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app): target_id = target.id preview = get_customer_merge_impact(source_id, target_id) - assert preview['historical_references']['business_cases'] == 1 + assert preview['historical_references']['shipping_notices'] == 1 # 合并预检同时展示旧识别证据与阶段一可配置证据的迁移统计。 assert preview['migrate'] == { 'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0, @@ -105,10 +105,10 @@ def test_merge_moves_future_configuration_and_preserves_history(app): assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0 assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2 assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1 - historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one() - assert historical_case.customer_id == source_id - assert historical_case.business_no == 'SRC26071601' - assert historical_case.customer_short_code_snapshot == 'SRC' + historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one() + assert historical_notice.customer_id == source_id + assert historical_notice.business_no == 'SRC26071601' + assert historical_notice.customer_short_code_snapshot == 'SRC' assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1 merge = db.session.get(ShippingCustomerMerge, result['merge_id']) assert merge is not None and merge.source_customer_id_snapshot == source_id diff --git a/backend/tests/services/admin/test_shipping_customer_service.py b/backend/tests/services/admin/test_shipping_customer_service.py index fdb722c4..cf69f314 100644 --- a/backend/tests/services/admin/test_shipping_customer_service.py +++ b/backend/tests/services/admin/test_shipping_customer_service.py @@ -13,7 +13,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent +from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice from app.services.admin.shipping_customer_service import ( create_customer, create_identifier, @@ -219,7 +219,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app): """列表返回业务单和识别证据数量,避免管理端逐客户补查。""" with app.app_context(): customer = _create_customer() - db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id'])) + db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id'])) db.session.add(ShippingCustomerIdentifier( customer_id=customer['id'], identifier_type='name_alias', @@ -231,5 +231,5 @@ def test_customer_list_returns_preaggregated_reference_counts(app): db.session.commit() result = list_customers({'page': 1, 'page_size': 20}) - assert result['items'][0]['case_count'] == 1 + assert result['items'][0]['notice_count'] == 1 assert result['items'][0]['identifier_count'] == 1 diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index 44c3f945..d0ff6695 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -11,7 +11,6 @@ from __future__ import annotations from app import db from app.models import ( FileAsset, - ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingIdentityDefinition, @@ -328,7 +327,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers( customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active') db.session.add(customer) db.session.flush() - db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id)) + db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id)) db.session.commit() customer_id = customer.id @@ -364,7 +363,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias', normalized_value='SOURCEALIAS', status='approved', source='manual', ), - ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'), + ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'), ]) db.session.commit() source_id = source.id @@ -397,7 +396,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history( with app.app_context(): assert db.session.get(ShippingCustomer, source_id).status == 'merged' assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1 - assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id + assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client): @@ -517,11 +516,10 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli _create_users() wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active') correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active') - case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending') - db.session.add_all([wrong, correct, case]) + db.session.add_all([wrong, correct]) db.session.flush() task = ShippingNotice( - task_no='SN-CORRECTION-API', shipping_case_id=case.id, + task_no='SN-CORRECTION-API', source_type='manual', customer_resolution_status='pending', ) db.session.add(task) @@ -529,7 +527,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli from app.services.shipping_notice.customer_identity_gate import confirm_task_customer confirm_task_customer(task, customer_id=wrong.id, actor_id=None) - old_business_no = task.shipping_case.business_no + old_business_no = task.business_no correct_id = correct.id forbidden = client.post( @@ -549,7 +547,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli assert payload['old_business_no'] == old_business_no assert payload['new_business_no'].startswith('NEW') with app.app_context(): - old_case = ShippingCase.query.filter_by(business_no=old_business_no).one() - replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one() - assert old_case.status == 'voided' + old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one() + replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one() + assert old_notice.lifecycle_status == 'voided' assert replacement.business_no == payload['new_business_no'] diff --git a/backend/tests/test_order_document_profile_creation_service.py b/backend/tests/test_order_document_profile_creation_service.py index 0ded8915..fe09beeb 100644 --- a/backend/tests/test_order_document_profile_creation_service.py +++ b/backend/tests/test_order_document_profile_creation_service.py @@ -55,6 +55,8 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi assert created['profile_code'] != 'CLIENT_SUPPLIED_CODE' assert created['draft_revision']['revision_no'] == 1 assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a' + # 主表身份必须同时冻结在 Profile 定义和两类共同视觉样本上。 + assert created['definition']['main_table_id'] == 'sample-table' assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1 assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1 assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1 @@ -115,6 +117,27 @@ def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatc assert signature['run_type'] == 'layout_signature' +def test_runtime_adapter_does_not_route_plain_pdf_by_stale_xfa_capability(monkeypatch): + """关键断言:普通 PDF 的残留 XFA capability 不得改变正式值源路由。""" + from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset + + monkeypatch.setattr(xfa_dataset, 'xfa_enabled', lambda: True) + stale_plain_pdf_layout = { + 'document_kind': 'plain_pdf', + 'xfa_capability': {'structure_analysis_ready': True}, + } + assert xfa_dataset.owns_layout(stale_plain_pdf_layout) is False + + supported_xfa_layout = { + 'document_kind': 'xfa_hybrid', + 'xfa_capability': { + 'document_kind': 'xfa_hybrid', + 'structure_analysis_ready': True, + }, + } + assert xfa_dataset.owns_layout(supported_xfa_layout) is True + + def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch): """关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。""" from hashlib import sha256 diff --git a/backend/tests/test_order_document_profile_publish_check_service.py b/backend/tests/test_order_document_profile_publish_check_service.py index 18f52ea0..ae2a7bfa 100644 --- a/backend/tests/test_order_document_profile_publish_check_service.py +++ b/backend/tests/test_order_document_profile_publish_check_service.py @@ -46,7 +46,11 @@ def _signature_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun: profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'], definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'], run_type='layout_signature', status='passed', - summary_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'}, + summary_json={ + 'signature_checksum': 'sig-checksum', + 'matcher_policy_version': 'profile-layout-matcher', + 'evidence_contract_version': validation_service.LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION, + }, result_snapshot_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'}, operation_id='signature-validation', ) @@ -160,6 +164,37 @@ def test_report_blocks_when_signature_missing(app, monkeypatch): assert 'signature_required' in keys or 'overlap_validation_required' in keys +def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch): + """页面提交旧签名 ID 时,发布检查必须忽略它并通过统一入口重建当前签名。""" + with app.app_context(): + monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None) + schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-legacy-signature-create') + lease = _lease(draft['id']); run = _passing_run(draft) + legacy = _signature_run(draft) + legacy.summary_json = { + key: value for key, value in legacy.summary_json.items() + if key != 'evidence_contract_version' + } + db.session.commit() + fresh = _signature_run(draft) + overlap = _overlap_run(draft) + calls: list[int] = [] + + def _resolve(profile, _revision, **_kwargs): + calls.append(profile.id) + return fresh + + monkeypatch.setattr(validation_service, 'resolve_profile_identity_signature', _resolve) + monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'}) + report = checks.create_report( + draft['id'], data={'validation_run_id': run.id, 'matching_signature_run_id': legacy.id, 'overlap_validation_run_id': overlap.id}, + actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-legacy-signature-report', + ) + + assert calls == [draft['id']] + assert report['matching_signature_run_id'] == fresh.id + + def test_report_blocks_when_overlap_failed(app, monkeypatch): """关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。""" with app.app_context(): @@ -202,8 +237,8 @@ def test_report_invalidates_when_signature_cleared(app, monkeypatch): assert refreshed['status'] == 'invalidated' -def test_consume_report_blocks_editor_self_approval(app, monkeypatch): - """职责分离:最近映射编辑者不得消费自己的发布检查报告。""" +def test_consume_report_allows_editor_self_approval(app, monkeypatch): + """业务规则:管理员可确认发布自己编辑的订单模板草稿。""" with app.app_context(): monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None) monkeypatch.setattr( @@ -244,15 +279,9 @@ def test_consume_report_blocks_editor_self_approval(app, monkeypatch): operation_id='pc-sod-report', ) keys = [str(item['key']) for item in report['warning_items']] - with pytest.raises(ValidationError) as error: - checks.consume_report( - draft['id'], - report['report_no'], - data={'confirmed_warning_keys': keys}, - actor_id=editor.id, - browser_session_id='publish-check-tab', - lease_token=lease['lease_token'], - operation_id='pc-sod-consume', - ) - assert error.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID' - assert (error.value.details or {}).get('key') == 'editor_cannot_approve_own_version' + published = checks.consume_report( + draft['id'], report['report_no'], data={'confirmed_warning_keys': keys}, + actor_id=editor.id, browser_session_id='publish-check-tab', + lease_token=lease['lease_token'], operation_id='pc-sod-consume', + ) + assert published['status'] == 'published' diff --git a/backend/tests/test_order_document_profile_validation_service.py b/backend/tests/test_order_document_profile_validation_service.py index 83ffb906..e4e39292 100644 --- a/backend/tests/test_order_document_profile_validation_service.py +++ b/backend/tests/test_order_document_profile_validation_service.py @@ -85,6 +85,71 @@ def test_frozen_sample_layout_survives_source_document_retention_cleanup(monkeyp assert validation_service._load_sample_layout(sample) == frozen_layout +def test_frozen_sample_layout_hydrates_coordinate_evidence_reference(monkeypatch): + """压缩 Layout 仍须通过其 FileAsset 引用恢复坐标证据,供签名和发布校验使用。""" + sample = SimpleNamespace(document_id=992, layout_version_id=772) + frozen_layout = {'status': 'ready', 'coordinate_evidence_ref': {'asset_no': 'evidence-asset'}} + document = SimpleNamespace(id=992) + hydrated_layout = { + **frozen_layout, + 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 100}}}, + } + + def _get(model, identity): + if model.__name__ == 'ShippingDocumentLayoutVersion' and identity == 772: + return SimpleNamespace(payload_json=frozen_layout) + if model.__name__ == 'ShippingOrderDocument' and identity == 992: + return document + return None + + monkeypatch.setattr(validation_service.db.session, 'get', _get) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.lifecycle._hydrate_coordinate_evidence', + lambda *, payload, document: hydrated_layout, + ) + + assert validation_service._load_sample_layout(sample) == hydrated_layout + + +def test_profile_identity_signature_rejects_pre_hydration_signature(monkeypatch): + """旧证据契约生成的签名不能在修复后继续参与发布唯一性校验。""" + profile = SimpleNamespace( + id=93, + matching_signature_run_id=94, + matching_signature_checksum='old-signature', + matching_signature_version='order-profile-layout-signature', + ) + revision = SimpleNamespace(definition_checksum='definition-checksum') + legacy_run = SimpleNamespace( + profile_id=93, + run_type='layout_signature', + status='passed', + definition_checksum='definition-checksum', + summary_json={}, + result_snapshot_json={'signature_checksum': 'old-signature'}, + ) + monkeypatch.setattr(validation_service.db.session, 'get', lambda *_args: legacy_run) + + with pytest.raises(Exception) as error: + validation_service.resolve_profile_identity_signature(profile, revision, auto_run=False) + + assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE' + + +def test_match_thresholds_preserve_explicit_zero_score_and_margin(): + """模板允许唯一命中不设分数/间距下限时,发布校验不得把 0 覆盖为默认门槛。""" + thresholds = validation_service._match_thresholds({ + 'document_match': { + 'minimum_score': 0.0, + 'minimum_margin': 0.0, + 'scoring_thresholds': {'evidence_coverage_minimum': 0.7}, + }, + }) + + assert thresholds['minimum_score'] == 0.0 + assert thresholds['minimum_margin'] == 0.0 + + def test_failed_current_sample_run_remains_queryable(app): """关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。""" with app.app_context(): diff --git a/backend/tests/test_order_extraction_pdf_po_split.py b/backend/tests/test_order_extraction_pdf_po_split.py index b9a86f17..d72342ae 100644 --- a/backend/tests/test_order_extraction_pdf_po_split.py +++ b/backend/tests/test_order_extraction_pdf_po_split.py @@ -8,7 +8,10 @@ from __future__ import annotations from types import SimpleNamespace -from app.services.shipping_notice.order_extraction_workflow import _build_approved_profile_order_result +from app.services.shipping_notice.order_extraction_workflow import ( + _build_approved_profile_order_result, + _reservation_region_candidates, +) SCHEMA = {'schema_version_id': 1, 'checksum': 'schema'} @@ -18,6 +21,14 @@ DEFINITION = {'fields': [ {'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'required': True}, ]} +RESERVATION_DEFINITION = { + 'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1}, + 'fields': DEFINITION['fields'] + [ + {'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header'}, + {'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line'}, + ], +} + def _row(po: str, part: str) -> dict: return {'status': 'parsed', 'issues': [], 'fields': [ @@ -27,6 +38,32 @@ def _row(po: str, part: str) -> dict: ]} +def _page_glyphs(*lines: str) -> list[dict]: + """构造跨页 Reservation 路由回归所需的最小坐标文字。""" + glyphs = [] + for row_index, line in enumerate(lines): + for column_index, char in enumerate(line): + glyphs.append({ + 'text': char, + 'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12}, + 'source_index': len(glyphs), + 'boundary_before': 'space' if char == ' ' else 'none', + }) + return glyphs + + +def _two_page_layout() -> dict: + return { + 'coordinate_evidence': { + 'pages': {'1': {'width': 800, 'height': 600}, '2': {'width': 800, 'height': 600}}, + 'page_glyphs': { + '1': _page_glyphs('Vendor Comments:', 'Reservation#33008'), + '2': _page_glyphs('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999'), + }, + }, + } + + def test_approved_pdf_rejects_multiple_pos_in_one_pdf(): """同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。""" orders, reason = _build_approved_profile_order_result( @@ -47,3 +84,75 @@ def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven(): ) assert reason is None assert len(orders or []) == 1 + + +def test_approved_pdf_writes_unnumbered_reservation_to_header_and_line_value_to_its_row(): + """同一证据区可同时提供整单默认 Reservation 与指定行覆盖值。""" + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=RESERVATION_DEFINITION, + table={'rows': [_row('PO-1', 'P-1'), _row('PO-1', 'P-2')]}, + reservation_region_candidates=[ + {'value': '33008', 'scope': 'header', 'line_no': None, 'raw_text': 'Reservation#33008'}, + {'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'}, + ], + ) + + assert reason is None + order = (orders or [])[0] + assert any( + item['field_id'] == 'header-reservation' and item['observations'][0]['value'] == '33008' + for item in order['header_fields'] + ) + assert any( + item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '3000098851' + for item in order['lines'][0]['fields'] + ) + assert not any(item['field_id'] == 'line-reservation' for item in order['lines'][1]['fields']) + + +def test_approved_pdf_marks_conflicting_reservation_region_for_review(): + """同一逻辑行的不同 Reservation 不得被任意选择。""" + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]}, + reservation_region_candidates=[ + {'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'}, + {'value': '3000098852', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098852 for line#1'}, + ], + ) + + assert reason is None + assert (orders or [])[0]['reservation_region_status'] == 'needs_review' + + +def test_enabled_reservation_region_reads_vendor_comments_across_pages(): + """已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。""" + result = _reservation_region_candidates( + raw_profile={'definition': RESERVATION_DEFINITION}, layout=_two_page_layout(), + ) + + assert result['reason'] is None + assert [item['value'] for item in result['candidates']] == ['33008', '3000098851'] + + +def test_profile_without_reservation_region_does_not_scan_vendor_comments(): + """未标注专区的模板必须保持既有行为,不得扫描正文中的 Reservation。""" + result = _reservation_region_candidates( + raw_profile={'definition': DEFINITION}, layout=_two_page_layout(), + ) + + assert result == {'candidates': [], 'reason': None} + + +def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing(): + """专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。""" + orders, reason = _build_approved_profile_order_result( + unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA, + definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]}, + reservation_region_reason='terms_and_conditions_anchor_missing', + ) + + assert reason is None + assert (orders or [])[0]['reservation_region_status'] == 'needs_review' + assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing'] diff --git a/backend/tests/test_post_ot_fulfillment_wave_p0.py b/backend/tests/test_post_ot_fulfillment_wave_p0.py index edf6acc4..378e28c0 100644 --- a/backend/tests/test_post_ot_fulfillment_wave_p0.py +++ b/backend/tests/test_post_ot_fulfillment_wave_p0.py @@ -8,6 +8,8 @@ tests/test_post_ot_fulfillment_wave_p0.py from __future__ import annotations +import ast +import inspect from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -16,6 +18,99 @@ import pytest from app.core.errors import ConflictError +def test_create_post_ot_wave_uses_standard_fulfillment_audit_snapshot_keywords(): + """履约波次审计必须使用统一的 before/after 状态摘要参数。""" + from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc + + function_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0] + audit_calls = [ + node + for node in ast.walk(function_node) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == 'record_fulfillment_audit' + ] + + assert len(audit_calls) == 1 + keyword_names = {keyword.arg for keyword in audit_calls[0].keywords} + assert {'before', 'after'} <= keyword_names + assert not {'before_json', 'after_json'} & keyword_names + + +def test_released_shortage_line_is_eligible_for_post_ot_wave(): + """短缺放行仅完成审批,后续必须允许该行进入独立发货通知波次。""" + from app.services.shipping_notice.post_ot_fulfillment_wave_service import _assert_fact_allows_fulfill + + required, available = _assert_fact_allows_fulfill({ + 'line_key': 'L-RELEASED', + 'inventory_status': 'ready', + 'match_result': 'matched', + 'is_shortage': True, + 'required_qty': '3', + 'available_qty': '0', + 'decision': {'decision_code': 'release_inventory_shortage'}, + }) + + assert str(required) == '3' + assert str(available) == '0' + + +def test_list_eligible_post_ot_lines_keeps_released_shortage_only(): + """库存不足明细必须先有放行审计决定,才能成为 wave 候选。""" + from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc + + case = SimpleNamespace(id=1) + with patch.object(svc, 'project_review_case_line_decisions', return_value={'lines': [ + { + 'line_key': 'released', 'line_status': 'released_shortage', + 'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True, + 'required_qty': '3', 'available_qty': '0', + 'decision': {'decision_code': 'release_inventory_shortage'}, + }, + { + 'line_key': 'unreleased', 'line_status': 'pending_decision', + 'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True, + 'required_qty': '3', 'available_qty': '0', + 'decision': None, + }, + ]}): + assert svc.list_eligible_post_ot_line_keys(case) == ['released'] + + +def test_post_ot_wave_creates_a_distinct_notice_with_only_selected_lines(app): + """波次必须产生独立 Notice,且其 NoticeLine 只能包含本次勾选项次。""" + from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot + + selected = [SimpleNamespace( + id=101, position=0, line_no='10', part_number='PN-10', + reservation_id='RES-10', qty='2', field_values_json={}, + )] + snapshot = SimpleNamespace(lines=[ + *selected, + SimpleNamespace( + id=102, position=1, line_no='20', part_number='PN-20', + reservation_id='RES-20', qty='3', field_values_json={}, + ), + ]) + added: list = [] + + with app.app_context(): + with ( + patch('app.services.shipping_notice.notice_line_service.db.session.query') as query, + patch('app.services.shipping_notice.notice_line_service.db.session.add_all', side_effect=added.extend), + patch('app.services.shipping_notice.notice_line_service.db.session.flush'), + ): + query.return_value.filter_by.return_value.delete.return_value = 0 + count = replace_notice_lines_from_snapshot( + notice_id=9, + snapshot=snapshot, + snapshot_line_ids={101}, + ) + + assert count == 1 + assert [(row.notice_id, row.snapshot_line_id, row.line_key) for row in added] == [(9, 101, '10')] + + def test_create_post_ot_wave_idempotent_replay_returns_original(app): """同 key 且参数一致必须返回原 wave,不二次建波。""" from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc @@ -143,7 +238,12 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app): with app.app_context(): with ( patch.object(coord, 'line_auto_fulfill_enabled', return_value=True), - patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']), + patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']), + patch.object( + coord, + 'project_review_case_line_decisions', + return_value={'lines': [{'line_key': 'L1', 'line_status': 'ready_to_fulfill'}]}, + ), patch.object(coord, 'create_post_ot_fulfillment_wave', side_effect=_boom), patch.object(coord.db.session, 'rollback', side_effect=lambda: calls.append('rollback')), patch.object(coord.db.session, 'flush', side_effect=lambda: calls.append('flush')), @@ -159,6 +259,32 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app): schedule_mock.assert_not_called() +def test_coordinate_auto_fulfill_requires_manual_selection_for_multiple_lines(app): + """多条开放明细不得由系统自动合并为同一张发货通知单。""" + from app.services.shipping_notice import line_auto_fulfill_coordinator as coord + + case = SimpleNamespace(id=3, case_no='RC-MULTI', confirmed_task_id=8) + with app.app_context(): + with ( + patch.object(coord, 'line_auto_fulfill_enabled', return_value=True), + patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1', 'L2']), + patch.object( + coord, + 'project_review_case_line_decisions', + return_value={'lines': [ + {'line_key': 'L1', 'line_status': 'released_shortage'}, + {'line_key': 'L2', 'line_status': 'ready_to_fulfill'}, + ]}, + ), + patch.object(coord, 'create_post_ot_fulfillment_wave') as create_mock, + ): + out = coord.coordinate_post_ot_auto_fulfill(case=case, trigger='inventory_shortage_released') + + assert out['status'] == 'idle' + assert out['reason'] == 'manual_wave_selection_required' + create_mock.assert_not_called() + + def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app): """无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。""" from app.services.shipping_notice import line_auto_fulfill_coordinator as coord diff --git a/backend/tests/test_shipping_business_numbering.py b/backend/tests/test_shipping_business_numbering.py index 708a0bf6..56a782b7 100644 --- a/backend/tests/test_shipping_business_numbering.py +++ b/backend/tests/test_shipping_business_numbering.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_business_numbering.py -用途:验证货代业务编号格式、上海日期、两位流水上限及业务单版本继承。 -依赖:ShippingCase/Customer/Sequence、business_numbering_service、customer_identity_gate。 -逻辑:直接调用领域服务,覆盖幂等、01-99、修订共享与强制新建独立编号。 +用途:验证货代业务编号格式、上海日期、两位流水上限及 Notice 独立编号。 +依赖:ShippingNotice/Customer/Sequence、business_numbering_service、customer_identity_gate。 +逻辑:直接调用领域服务,覆盖幂等、01-99 与替代 Notice 独立编号。 """ from datetime import datetime, timezone @@ -12,9 +12,9 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent from app.services.shipping_notice.business_numbering_service import ( - assign_business_number, + assign_notice_business_number, format_business_no, shanghai_business_date, ) @@ -22,25 +22,23 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref -def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): - """创建待客户确认的业务单、任务和启用客户。""" +def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): + """创建待客户确认的 Notice 和启用客户。""" customer = ShippingCustomer( standard_name=f"编号测试客户 {short_code}", short_code=short_code, status="active", ) - case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending") - db.session.add_all([customer, case]) + db.session.add(customer) db.session.flush() task = ShippingNotice( task_no=task_no, - shipping_case_id=case.id, customer_resolution_status="pending", source_type="manual", ) db.session.add(task) db.session.commit() - return task, case, customer + return task, customer def test_number_format_and_shanghai_date_boundary(app): @@ -55,53 +53,89 @@ def test_number_format_and_shanghai_date_boundary(app): def test_confirmation_assigns_idempotent_business_number(app): """重复确认同一客户不得重复占用流水,正式编号保持不变。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() first = confirm_task_customer(task, customer_id=customer.id, actor_id=None) - first_no = first.shipping_case.business_no + first_no = first.business_no second = confirm_task_customer(first, customer_id=customer.id, actor_id=None) assert first_no - assert second.shipping_case.business_no == first_no + assert second.business_no == first_no assert ShippingBusinessSequence.query.one().current_value == 1 - assert second.shipping_case.customer_short_code_snapshot == "WYC" + assert second.customer_short_code_snapshot == "WYC" assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1 -def test_revision_inherits_and_force_case_uses_next_sequence(app): - """同一业务单修订继承编号,独立业务单确认同客户时占用下一流水。""" +def test_each_notice_gets_a_distinct_business_number_for_same_customer(app): + """同一客户 PO 的不同发货通知必须各自占用独立业务流水。""" with app.app_context(): - task, case, customer = _seed_case() + customer = ShippingCustomer( + standard_name='通知单波次客户', short_code='WVC', status='active', + ) + db.session.add(customer) + db.session.flush() + first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed') + second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed') + db.session.add_all([first, second]) + db.session.flush() + first.customer_id = customer.id + second.customer_id = customer.id + db.session.flush() + + first_no = assign_notice_business_number(first) + second_no = assign_notice_business_number(second) + + assert first_no != second_no + assert first.business_no == first_no + assert second.business_no == second_no + + +def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app): + """新 Notice 必须自持客户快照与编号,不能要求 ShippingCase 作为前置容器。""" + with app.app_context(): + customer = ShippingCustomer( + standard_name='Notice 自持客户', short_code='NHC', status='active', + ) + task = ShippingNotice( + task_no='SN-NOTICE-SELF-CUSTOMER', + customer_resolution_status='pending', + source_type='manual', + ) + db.session.add_all([customer, task]) + db.session.commit() + + confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7) + + assert confirmed.customer_id == customer.id + assert confirmed.customer_name_snapshot == 'Notice 自持客户' + assert confirmed.customer_short_code_snapshot == 'NHC' + assert confirmed.business_no + assert confirmed.customer_resolution_status == 'confirmed' + + +def test_replacement_notice_uses_next_sequence(app): + """替代 Notice 保留原号审计并为新 Notice 分配下一业务号。""" + with app.app_context(): + task, customer = _seed_notice() confirm_task_customer(task, customer_id=customer.id, actor_id=None) revision = ShippingNotice( task_no="SN-NUMBER-REV", - shipping_case_id=case.id, supersedes_task_id=task.id, - customer_resolution_status="confirmed", - source_type="manual", - ) - forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending") - db.session.add_all([revision, forced_case]) - db.session.flush() - forced_task = ShippingNotice( - task_no="SN-NUMBER-FORCED", - shipping_case_id=forced_case.id, customer_resolution_status="pending", source_type="manual", ) - db.session.add(forced_task) + db.session.add(revision) db.session.commit() - confirm_task_customer(forced_task, customer_id=customer.id, actor_id=None) - assert revision.shipping_case.business_no == case.business_no - assert forced_task.shipping_case.business_no[:-2] == case.business_no[:-2] - assert case.business_no.endswith("01") - assert forced_task.shipping_case.business_no.endswith("02") + confirm_task_customer(revision, customer_id=customer.id, actor_id=None) + assert revision.business_no[:-2] == task.business_no[:-2] + assert task.business_no.endswith("01") + assert revision.business_no.endswith("02") def test_daily_sequence_blocks_one_hundredth_case(app): """客户当日已有 99 笔时,第 100 笔必须阻断且不写业务号。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() business_date = shanghai_business_date() db.session.add(ShippingBusinessSequence( business_type="shipping_notice", @@ -110,19 +144,19 @@ def test_daily_sequence_blocks_one_hundredth_case(app): current_value=99, )) db.session.commit() - case.customer_id = customer.id + task.customer_id = customer.id with pytest.raises(ConflictError) as exc_info: - assign_business_number(case) + assign_notice_business_number(task) assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED" - assert case.business_no is None + assert task.business_no is None assert ShippingBusinessSequence.query.one().current_value == 99 def test_numbering_failure_rolls_back_customer_confirmation(app): """流水耗尽导致确认失败时,业务单客户和任务确认状态不得半落库。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() db.session.add(ShippingBusinessSequence( business_type="shipping_notice", customer_id=customer.id, @@ -135,43 +169,41 @@ def test_numbering_failure_rolls_back_customer_confirmation(app): confirm_task_customer(task, customer_id=customer.id, actor_id=None) db.session.rollback() db.session.expire_all() - persisted_case = db.session.get(ShippingCase, case.id) persisted_task = db.session.get(ShippingNotice, task.id) - assert persisted_case.customer_id is None - assert persisted_case.business_no is None + assert persisted_task.customer_id is None + assert persisted_task.business_no is None assert persisted_task.customer_resolution_status == "pending" -def test_business_number_query_returns_latest_revision(app): - """使用正式业务号查询时应返回同业务单最新修订任务。""" +def test_business_number_query_returns_exact_notice(app): + """使用正式业务号查询时必须返回该 Notice,不能跳到替代版本。""" with app.app_context(): - task, case, customer = _seed_case() + task, customer = _seed_notice() confirm_task_customer(task, customer_id=customer.id, actor_id=None) revision = ShippingNotice( task_no="SN-NUMBER-QUERY-REV", - shipping_case_id=case.id, supersedes_task_id=task.id, document_version=2, - customer_resolution_status="confirmed", + customer_resolution_status="pending", source_type="manual", ) db.session.add(revision) db.session.commit() - resolved = get_task_by_ref(case.business_no) - assert resolved.id == revision.id - assert extract_task_no_from_text(f"请继续处理 {case.business_no}") == case.business_no + resolved = get_task_by_ref(task.business_no) + assert resolved.id == task.id + assert extract_task_no_from_text(f"请继续处理 {task.business_no}") == task.business_no def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app): """客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。""" with app.app_context(): - task, case, customer = _seed_case() - case.customer_id = customer.id + task, customer = _seed_notice() + task.customer_id = customer.id customer.short_code = "W1" # 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。 with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info: - assign_business_number(case) + assign_notice_business_number(task) assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID" - assert case.business_no is None + assert task.business_no is None db.session.rollback() diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index 3c8c1ecc..648495cc 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -12,8 +12,12 @@ from pydantic import ValidationError from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import ( + coordinate_profile_character_candidates, _text_in_region, + _text_in_horizontal_region, + reconstruction_exclusion_regions, reconstruct_coordinate_profile_rows, + reconstruct_coordinate_profile_rows_with_strategy, reconstruct_table_from_positioned_text, resolve_line_start_field_code, suggest_header_layouts, @@ -65,6 +69,87 @@ def _adaptive_layouts() -> list[dict]: ] +def test_coordinate_profile_character_candidates_share_page_first_union_contract(): + """三条解析链路应得到同一套整页优先、纵向并集字符候选。""" + page_characters = [ + {'text': 'H', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}, + {'text': 'D', 'bbox': {'x0': 10, 'y0': 160, 'x1': 20, 'y1': 170}}, + {'text': 'X', 'bbox': {'x0': 300, 'y0': 160, 'x1': 310, 'y1': 170}}, + ] + table_characters = [{'text': 'legacy', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}] + characters, page_bbox = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5}, + page_size={'width': 400, 'height': 400}, page_characters=page_characters, + table_characters=table_characters, + raw_table_bbox={'x0': 0, 'y0': 120, 'x1': 200, 'y1': 180}, + table_id='table-1', page_no=1, + ) + assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 400.0, 'y1': 400.0} + assert [item['text'] for item in characters or []] == ['H', 'D'] + + +def test_coordinate_profile_character_candidates_use_annotation_page_frame_on_taller_runtime_page(): + """分页训练表区在未分页长页中必须保持原始 PDF 点坐标,不能按新页高拉伸。""" + characters, page_bbox = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .2, 'x1': 1.0, 'y1': .3}, + reference_page_frame={'width': 200, 'height': 100}, + page_size={'width': 200, 'height': 200}, + page_characters=[ + {'text': 'line', 'bbox': {'x0': 10, 'y0': 21, 'x1': 30, 'y1': 29}}, + {'text': 'wrong', 'bbox': {'x0': 10, 'y0': 41, 'x1': 35, 'y1': 49}}, + ], + table_characters=None, table_id='page-1', page_no=1, + ) + + # 关键断言:训练页 .2-.3 对应 y=20..30,而不是长页 y=40..60。 + assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 200.0} + assert [item['text'] for item in characters or []] == ['line'] + + +def test_coordinate_profile_character_candidates_fallback_when_page_crop_is_empty(): + """空的页级裁剪不能覆盖仍可用的当前表字符证据。""" + characters, _ = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5}, + page_size={'width': 100, 'height': 100}, + page_characters=[{'text': 'header', 'bbox': {'x0': 80, 'y0': 80, 'x1': 90, 'y1': 90}}], + table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}], + table_id='table-1', page_no=1, + ) + assert [item['text'] for item in characters or []] == ['10'] + + +def test_coordinate_profile_character_candidates_do_not_reuse_table_on_other_page(): + """续页没有自己的页级候选时,不能重复消费首页表字符。""" + characters, _ = coordinate_profile_character_candidates( + table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5}, + page_size={'width': 100, 'height': 100}, + page_characters=[], + table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}], + table_id='table-1', page_no=2, allow_table_fallback=False, + ) + assert characters is None + + +def test_reconstruction_exclusions_do_not_treat_header_layouts_as_deleted_text(): + """表头框是语义/预览证据,默认不得在明细起行前删除相交字符。""" + exclusions = reconstruction_exclusion_regions({ + 'exclusion_regions': [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}], + 'header_layouts': [{'region': {'x0': .0, 'y0': .2, 'x1': 1, 'y1': .4}}], + }) + + assert exclusions == [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}] + + +def test_horizontal_region_keeps_a_character_that_intersects_its_right_edge(): + """字段边界切过字形时必须保留该字,避免料号末尾标点被静默截断。""" + glyphs = [ + (0, PositionedCharacter(text='A', bbox=LayoutBBox(x0=80, y0=20, x1=84, y1=30))), + (1, PositionedCharacter(text='-', bbox=LayoutBBox(x0=99.9, y0=20, x1=103, y1=30))), + ] + + assert _text_in_horizontal_region(glyphs, LayoutBBox(x0=80, y0=10, x1=100, y1=40)) == 'A -' + + def test_table_region_text_prefers_explicit_pdf_space_boundary(): """明细自由文本列应恢复 PDF 原始词边界,同时不依赖降低全局几何阈值。""" glyphs = [ @@ -308,6 +393,114 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts(): assert rows[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'} +def test_coordinate_profile_rows_require_multi_field_signature_for_new_records(): + """孤立数字不能启动明细;同一视觉行的业务字段组合才可启动。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('0', 10)], + [('20', 10), ('PART-A', 65), ('5', 160)], + ), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}}, + {'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']}, + ], + ) + + # 关键断言:表头/噪声中的孤立 0 不得成为第 1 条明细,真实组合只产生 1 条。 + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '20', 'part_number': 'PART-A', 'qty': '5', + }] + + +def test_coordinate_profile_rows_can_start_without_line_number_when_business_fields_agree(): + """客户行号缺失时,料号与数量等独立业务字段可在任意列位置联合起行。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('PART-A', 10), ('5', 160)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}}, + {'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']}, + ], + ) + + # 关键断言:起行不依赖列序或必须存在的行号字段。 + assert [row.fields for row in rows] == [{'part_number': 'PART-A', 'qty': '5'}] + + +def test_coordinate_profile_rows_ignore_non_line_schema_fields_for_record_start(): + """明细起行只消费 Schema scope=line,header 字段不能提供联合起行证据。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('Vendor', 10), ('PART-A', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}}, + {'field_code': 'vendor', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'vendor', 'scope': 'header', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + # 只有一个 line 字段有效;header 字段不能把该视觉行提升为明细。 + assert rows == [] + + +def test_adaptive_record_start_uses_only_schema_line_fields_without_business_name_whitelist(): + """自适应模式同样按 Schema line 字段联合起行,不能把表头文本当行号。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('0rd', 10), ('Shipping In', 65)], [('20', 10), ('PART-A', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + row_reconstruction_mode='adaptive_record_columns', + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '20', 'customer_part_number': 'PART-A', + }] + + +def test_schema_string_line_anchor_rejects_header_text(): + """string 类型起行字段仍须满足通用行号形态,不能接受表头文本。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('0rd', 10), ('PART-A', 65)], [('B', 10), ('PART-B', 65)], [('20', 10), ('PART-C', 65)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}}, + ]}], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '20', 'part_number': 'PART-C', + }] + + def test_line_number_can_be_used_as_a_configured_coordinate_anchor(): """用户选择项次字段时,坐标模板可用 line_no 启动明细。""" rows = reconstruct_coordinate_profile_rows( @@ -719,6 +912,133 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l }, ] + +def test_dynamic_x_columns_recovers_a_shifted_record_hidden_by_static_header_exclusion(): + """表头随单头高度移动时,动态候选须以起行/列校验恢复被旧表头框遮住的首条明细。""" + rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=_glyphs( + [('LN', 10), ('Quantity', 50), ('Part Number', 120)], + [('1', 10), ('113', 50), ('PART-A', 120)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 60}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': .9}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .5, 'x1': .15, 'y1': .7}}, + {'field_code': 'qty', 'region': {'x0': .15, 'y0': .5, 'x1': .4, 'y1': .7}}, + {'field_code': 'part_number', 'region': {'x0': .4, 'y0': .5, 'x1': 1, 'y1': .7}}, + ], + }], + exclusion_regions=[{'x0': 0, 'y0': .2, 'x1': 1, 'y1': .75}], + dynamic_exclusion_regions=[], + line_start_field_code='customer_po_line_no', + ) + + assert strategy.status == 'selected' + assert strategy.row_mode == 'dynamic_x_columns' + assert [row.fields for row in rows] == [ + {'customer_po_line_no': '1', 'qty': '113', 'part_number': 'PART-A'}, + ] + + +def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor(): + """动态行整体上移时,跨视觉行字段须随同一锚点平移而非复用首行前缀。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('1', 10), ('113', 50), ('WTP-D4-', 120)], + [('A08AR12000001', 120)], + [('D4-A08AR12000001', 120)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 120}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .15, 'y1': .80}}, + {'field_code': 'qty', 'region': {'x0': .15, 'y0': .70, 'x1': .4, 'y1': .80}}, + {'field_code': 'customer_part_number', 'region': {'x0': .4, 'y0': .70, 'x1': 1, 'y1': .90}}, + {'field_code': 'part_number', 'region': {'x0': .4, 'y0': .92, 'x1': 1, 'y1': 1}}, + ], + }], + line_start_field_code='customer_po_line_no', + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields for row in rows] == [{ + 'customer_po_line_no': '1', 'qty': '113', + 'customer_part_number': 'WTP-D4-A08AR12000001', + 'part_number': 'D4-A08AR12000001', + }] + + +def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor(): + """固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('1', 10), ('CUSTOMER-1', 60)], [('VENDOR-1', 60)], + [('2', 10), ('CUSTOMER-2', 60)], [('VENDOR-2', 60)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 140}, + table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .60, 'x1': .2, 'y1': .70}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .60, 'x1': 1, 'y1': .68}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': .70, 'x1': 1, 'y1': .78}}, + ], + }], + line_start_field_code='customer_po_line_no', + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert [row.fields for row in rows] == [ + {'customer_po_line_no': '1', 'customer_part_number': 'CUSTOMER-1', 'part_number': 'VENDOR-1'}, + {'customer_po_line_no': '2', 'customer_part_number': 'CUSTOMER-2', 'part_number': 'VENDOR-2'}, + ] + + +def test_coordinate_profile_strategy_prefers_fixed_for_wrapped_part_fields(): + """跨视觉行字段必须使用字段框完整值,不能被 adaptive 前缀覆盖。""" + schema = [ + {'field_code': code, 'scope': 'line', 'enabled': True, 'data_type': 'string'} + for code in ('customer_po_line_no', 'customer_part_number', 'part_number') + ] + rows, strategy = reconstruct_coordinate_profile_rows_with_strategy( + characters=_glyphs( + [('1', 10), ('WTP-B3-', 55)], + [('A08AR11000001', 55)], + [('B3-A08AR11000001', 55)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 70}, + table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .4}}, + {'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .7, 'y1': .65}}, + {'field_code': 'part_number', 'region': {'x0': .2, 'y0': .65, 'x1': .7, 'y1': .9}}, + ], + }], + schema_field_metadata=schema, + line_start_field_code='customer_po_line_no', + ) + + assert strategy.status == 'selected' + assert strategy.row_mode == 'fixed_subrows' + assert rows[0].fields['customer_part_number'] == 'WTP-B3-A08AR11000001' + assert rows[0].fields['part_number'] == 'B3-A08AR11000001' + assert rows[0].issues == [] + deleted = reconstruct_coordinate_profile_rows( characters=_glyphs( [('10', 10), ('B3-A08AR10000018-A7', 120)], diff --git a/backend/tests/test_shipping_customer_auto_resolution.py b/backend/tests/test_shipping_customer_auto_resolution.py index cd811c40..23543943 100644 --- a/backend/tests/test_shipping_customer_auto_resolution.py +++ b/backend/tests/test_shipping_customer_auto_resolution.py @@ -2,7 +2,7 @@ backend/tests/test_shipping_customer_auto_resolution.py 用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。 -依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice/Case、customer_auto_resolution。 +依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。 逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 """ @@ -14,7 +14,6 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( FileAsset, - ShippingCase, ShippingCustomer, ShippingCustomerShadowResolution, ShippingIdentityDefinition, @@ -122,11 +121,10 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"): candidate_key="document:1", validation_status="ready", selected=True, structured_result_json={"business_summary": {"customer_name": "unstable name"}}, ) - case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending") - db.session.add_all([candidate, case]) + db.session.add(candidate) db.session.flush() task = ShippingNotice( - task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id, + task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id, user_id=user.id, source_type="email_attachment", customer_resolution_status="pending", ) @@ -216,8 +214,8 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): assert result["rule_version"] == AUTO_RESOLUTION_VERSION assert task.customer_resolution_status == "confirmed" assert task.customer_resolution_method == "auto_rule" - assert task.shipping_case.customer_id == customer.id - assert task.shipping_case.business_no.startswith("WYC") + assert task.customer_id == customer.id + assert task.business_no.startswith("WYC") assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one() assert event.detail_json['rule_set']['checksum'] @@ -240,13 +238,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False disabled = try_auto_confirm_task_customer(task) assert disabled["status"] == "disabled" - assert task.shipping_case.business_no is None + assert task.business_no is None _allow_auto_confirmation(app) unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): @@ -261,7 +259,7 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): assert result["status"] == "ambiguous" assert len(result["candidate_customer_ids"]) == 2 assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): @@ -271,7 +269,6 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() task_id = task.id - case_id = task.shipping_case_id result = try_auto_confirm_task_customer(task) assert result["status"] == "auto_confirmed" @@ -279,10 +276,9 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): db.session.expire_all() persisted_task = db.session.get(ShippingNotice, task_id) - persisted_case = db.session.get(ShippingCase, case_id) assert persisted_task.customer_resolution_status == "pending" - assert persisted_case.customer_id is None - assert persisted_case.business_no is None + assert persisted_task.customer_id is None + assert persisted_task.business_no is None assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 @@ -300,7 +296,7 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic assert result["status"] == "insufficient_labeled_samples" assert result["quality_gate"]["labeled_sample_count"] == 0 assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None def test_business_evidence_never_auto_confirms(app): @@ -405,61 +401,48 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app assert result["quality_gate"]["labeled_sample_count"] == 1 assert result["quality_gate"]["accuracy"] == 0 assert task.customer_resolution_status == "pending" - assert task.shipping_case.business_no is None + assert task.business_no is None -def test_numbered_customer_correction_voids_old_number_and_replaces_case(app): - """客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。""" +def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app): + """客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。""" with app.app_context(): wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") - case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending") - db.session.add_all([wrong, correct, case]) + db.session.add_all([wrong, correct]) db.session.flush() first = ShippingNotice( - task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1, - source_type="manual", customer_resolution_status="pending", - ) - db.session.add(first) - db.session.flush() - latest = ShippingNotice( - task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2, - supersedes_task_id=first.id, source_type="manual", upload_status="pending", - customer_resolution_status="pending", inventory_source_code="DSV", + task_no="SN-CORRECTION-V1", document_version=1, + source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV", inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}], match_status="fulfillable", line_results_json=[{"sku": "A"}], export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx", ) - db.session.add(latest) + db.session.add(first) db.session.commit() confirm_task_customer(first, customer_id=wrong.id, actor_id=None) - old_case_id = case.id - old_business_no = case.business_no + old_business_no = first.business_no result = correct_numbered_task_customer( - latest, + first, customer_id=correct.id, reason="自动识别客户错误", actor_id=None, ) - old_case = db.session.get(ShippingCase, old_case_id) - replacement = db.session.get(ShippingCase, result["new_case_id"]) - assert old_case.business_no == old_business_no - assert old_case.status == "voided" - assert old_case.numbering_status == "voided" - assert replacement.replaces_case_id == old_case.id + replacement = db.session.get(ShippingNotice, result["new_notice_id"]) + assert first.business_no == old_business_no + assert first.lifecycle_status == "voided" + assert replacement.supersedes_task_id == first.id assert replacement.business_no.startswith("NEW") assert replacement.business_no != old_business_no - assert latest.shipping_case_id == replacement.id - assert first.shipping_case_id == replacement.id - assert latest.customer_resolution_method == "admin_correction" - assert latest.inventory_source_status is None - assert latest.inventory_lines_json is None - assert latest.export_file_path is None - assert latest.source_type == "manual" - assert get_task_by_ref(old_business_no).id == latest.id - assert get_task_by_ref(replacement.business_no).id == latest.id + assert replacement.customer_resolution_method == "admin_correction" + assert replacement.inventory_source_status is None + assert replacement.inventory_lines_json is None + assert replacement.export_file_path is None + assert replacement.source_type == "manual" + assert get_task_by_ref(old_business_no).id == first.id + assert get_task_by_ref(replacement.business_no).id == replacement.id assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2 metrics = get_auto_resolution_metrics() assert metrics["corrected_task_count"] == 2 @@ -471,11 +454,10 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a with app.app_context(): wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active") correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active") - case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending") - db.session.add_all([wrong, correct, case]) + db.session.add_all([wrong, correct]) db.session.flush() task = ShippingNotice( - task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id, + task_no="SN-CORRECTION-BLOCK", source_type="manual", customer_resolution_status="pending", ) db.session.add(task) @@ -493,4 +475,4 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None) assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED" db.session.rollback() - assert db.session.query(ShippingCase).count() == 1 + assert db.session.query(ShippingNotice).count() == 1 diff --git a/backend/tests/test_shipping_customer_identity_gate.py b/backend/tests/test_shipping_customer_identity_gate.py index b5813c90..410338ae 100644 --- a/backend/tests/test_shipping_customer_identity_gate.py +++ b/backend/tests/test_shipping_customer_identity_gate.py @@ -3,7 +3,7 @@ backend/tests/test_shipping_customer_identity_gate.py 用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 -逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。 +逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。 """ from __future__ import annotations @@ -15,7 +15,7 @@ from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError -from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent, User +from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, confirm_task_customer, @@ -31,7 +31,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.task_workflow import retry_task -def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: +def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: """创建待确认任务、启用客户和任务用户。""" sequence = db.session.query(User).count() user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') @@ -39,14 +39,9 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') db.session.add_all([user, customer]) db.session.flush() - case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None - if case: - db.session.add(case) - db.session.flush() task = ShippingNotice( task_no=f'SN-GATE-{user.id}', user_id=user.id, - shipping_case_id=case.id if case else None, - customer_resolution_status='pending' if case else None, + customer_resolution_status='pending' if customer_pending else None, lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}], inventory_source_status='user_confirmed', inventory_source_code='DSV', ) @@ -111,12 +106,12 @@ def test_pending_customer_blocks_retry_before_clearing_review_state(app): assert task.error_message == '标准客户尚未确认' -def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): - """客户确认同步同业务单全部任务,并在同事务生成正式业务号。""" +def test_confirm_customer_does_not_assign_notice_number_before_excel(app): + """客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。""" with app.app_context(): task, customer, user = _seed_task() revision = ShippingNotice( - task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id, + task_no='SN-GATE-REV', user_id=user.id, supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending', ) db.session.add(revision) @@ -124,24 +119,60 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) db.session.refresh(revision) - case = db.session.get(ShippingCase, task.shipping_case_id) assert updated.customer_resolution_status == 'confirmed' - assert revision.customer_resolution_status == 'confirmed' + assert revision.customer_resolution_status == 'pending' assert updated.customer_resolution_method == 'manual' - assert case.customer_id == customer.id - assert case.customer_name_snapshot == customer.standard_name - assert case.customer_short_code_snapshot == customer.short_code - assert case.business_no.startswith(customer.short_code) - assert len(case.business_no) == len(customer.short_code) + 8 - assert case.sequence_value == 1 - assert case.numbering_status == 'assigned' + assert updated.customer_id == customer.id + assert updated.customer_name_snapshot == customer.standard_name + assert updated.customer_short_code_snapshot == customer.short_code + assert updated.business_no is None + assert updated.business_date is None + assert updated.business_sequence_value is None assert customer_identity_is_confirmed(updated) is True - assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2 - assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2 + assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1 + assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0 -def test_inactive_customer_reblocks_and_missing_case_is_blocked(app): - """已确认客户停用后重新阻断;缺少业务单的任务也必须阻断。""" +def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch): + """PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。""" + with app.app_context(): + task, customer, user = _seed_task() + original_query = db.session.query + lock_arguments: list[dict] = [] + + class NoticeQuerySpy: + """保留真实 Query 行为,仅记录客户确认路径的行锁参数。""" + + def __init__(self, query): + self._query = query + + def filter(self, *criteria): + self._query = self._query.filter(*criteria) + return self + + def with_for_update(self, **kwargs): + lock_arguments.append(kwargs) + self._query = self._query.with_for_update(**kwargs) + return self + + def one(self): + return self._query.one() + + def traced_query(*entities, **kwargs): + query = original_query(*entities, **kwargs) + if len(entities) == 1 and entities[0] is ShippingNotice: + return NoticeQuerySpy(query) + return query + + monkeypatch.setattr(db.session, 'query', traced_query) + + confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) + + assert lock_arguments == [{'of': ShippingNotice}] + + +def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): + """已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。""" with app.app_context(): task, customer, user = _seed_task() confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) @@ -151,11 +182,11 @@ def test_inactive_customer_reblocks_and_missing_case_is_blocked(app): assert_customer_identity_gate(task, operation='match_inventory') assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' - missing_case, _other_customer, _other_user = _seed_task(with_case=False) - with pytest.raises(AppError) as missing_case_error: - assert_customer_identity_gate(missing_case, operation='match_inventory') - assert missing_case_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' - assert customer_identity_is_confirmed(missing_case) is False + unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False) + with pytest.raises(AppError) as unconfirmed_error: + assert_customer_identity_gate(unconfirmed, operation='match_inventory') + assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' + assert customer_identity_is_confirmed(unconfirmed) is False def test_workspace_customer_search_and_confirmation_api(app, client): diff --git a/backend/tests/test_shipping_customer_migrations.py b/backend/tests/test_shipping_customer_migrations.py index 883463c2..59109963 100644 --- a/backend/tests/test_shipping_customer_migrations.py +++ b/backend/tests/test_shipping_customer_migrations.py @@ -95,3 +95,113 @@ def test_shipping_customer_migrations_upgrade_and_downgrade(): finally: for module, original_op in zip(modules, original_ops, strict=True): module.op = original_op + + +def _shipping_case_removal_schema(engine: sa.Engine, *, migrated: bool) -> None: + """构造最终删表迁移所需的最小 Notice/Case 历史结构。""" + metadata = sa.MetaData() + sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_cases', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(32), nullable=True), + ) + sa.Table( + 'shipping_notices', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('task_no', sa.String(64), nullable=False), + sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(32), nullable=True), + ) + metadata.create_all(engine) + with engine.begin() as connection: + connection.execute(sa.text("INSERT INTO shipping_cases (id, customer_id, business_no) VALUES (1, 7, 'CUS26082301')")) + if migrated: + connection.execute(sa.text( + "INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) " + "VALUES (1, 'SN-MIGRATED', 1, 7, 'CUS26082301')" + )) + else: + connection.execute(sa.text( + "INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) " + "VALUES (1, 'SN-UNMIGRATED', 1, NULL, NULL)" + )) + + +def test_shipping_case_removal_migration_requires_notice_facts_and_drops_legacy_table(): + """最终迁移只能删除已回填 Notice 的 Case;未回填事实必须显式失败。""" + module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case') + for migrated in (True, False): + engine = sa.create_engine('sqlite:///:memory:') + _shipping_case_removal_schema(engine, migrated=migrated) + with engine.begin() as connection: + original_op = module.op + module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True})) + try: + if migrated: + module.upgrade() + inspector = sa.inspect(connection) + assert 'shipping_cases' not in inspector.get_table_names() + assert 'shipping_case_id' not in {item['name'] for item in inspector.get_columns('shipping_notices')} + else: + with pytest.raises(RuntimeError, match='migration incomplete'): + module.upgrade() + finally: + module.op = original_op + + +def test_shipping_case_removal_repairs_fact_columns_skipped_by_inconsistent_revision(): + """版本表已越过前置迁移但 Notice 仍为旧结构时,最终迁移应先恢复事实列再删 Case。""" + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_cases', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(32), nullable=True), + sa.Column('business_date', sa.Date(), nullable=True), + sa.Column('sequence_value', sa.Integer(), nullable=True), + sa.Column('numbering_rule_version', sa.String(32), nullable=True), + sa.Column('customer_name_snapshot', sa.String(200), nullable=True), + sa.Column('customer_short_code_snapshot', sa.String(6), nullable=True), + ) + sa.Table( + 'shipping_notices', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('task_no', sa.String(64), nullable=False), + sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True), + ) + metadata.create_all(engine) + with engine.begin() as connection: + connection.execute(sa.text("INSERT INTO shipping_customers (id) VALUES (7)")) + connection.execute(sa.text( + "INSERT INTO shipping_cases " + "(id, customer_id, business_no, business_date, sequence_value, numbering_rule_version, " + "customer_name_snapshot, customer_short_code_snapshot) " + "VALUES (1, 7, 'CUS26082301', '2026-08-23', 1, 'V1', 'Customer', 'CUS')" + )) + connection.execute(sa.text( + "INSERT INTO shipping_notices (id, task_no, shipping_case_id) " + "VALUES (1, 'SN-LEGACY', 1)" + )) + + module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case') + with engine.begin() as connection: + original_op = module.op + module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True})) + try: + module.upgrade() + inspector = sa.inspect(connection) + columns = {item['name'] for item in inspector.get_columns('shipping_notices')} + assert {'business_no', 'customer_id', 'business_date', 'business_sequence_value'} <= columns + row = connection.execute(sa.text( + "SELECT business_no, customer_id, business_sequence_value " + "FROM shipping_notices WHERE id = 1" + )).one() + assert row == ('CUS26082301', 7, 1) + assert 'shipping_cases' not in inspector.get_table_names() + finally: + module.op = original_op diff --git a/backend/tests/test_shipping_customer_shadow_resolution.py b/backend/tests/test_shipping_customer_shadow_resolution.py index ad776bbe..fb458911 100644 --- a/backend/tests/test_shipping_customer_shadow_resolution.py +++ b/backend/tests/test_shipping_customer_shadow_resolution.py @@ -14,7 +14,7 @@ import pytest from app import db from app.models import ( - FileAsset, ShippingCase, ShippingCustomer, ShippingCustomerShadowMatch, + FileAsset, ShippingCustomer, ShippingCustomerShadowMatch, ShippingCustomerShadowResolution, ShippingCustomerSite, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchema, @@ -154,9 +154,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app): ) _intake, candidate = _seed_candidate(sender='spoof@example.net') _attach_value(candidate, version, field, 'buyer@wyc.example.com') - case = ShippingCase(case_no='CASE-SHADOW') - db.session.add(case) - resolution = refresh_candidate_shadow_resolution(candidate) assert resolution.status == 'unique_candidate' @@ -164,7 +161,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app): assert resolution.identity_rule_set_id == rule_set['id'] assert resolution.evidence_json[0]['context_field_id'] == field.id assert resolution.evidence_json[0]['source']['kind'] == 'field_value' - assert case.customer_id is None and case.business_no is None def test_schema_uuid_drift_keeps_stable_customer_identity_rule_matching(app): diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index 968a7b0d..db506b0b 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -93,6 +93,25 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app): assert current_layout_snapshot(document)['marker'] == 'v1' +def test_ready_pdf_layout_requires_coordinate_evidence_asset(app, monkeypatch): + """关键断言:PDF 坐标证据资产保存失败时,布局不得伪装为 ready。""" + with app.app_context(): + document = _document() + monkeypatch.setattr(layout_lifecycle, '_persist_coordinate_evidence_asset', lambda **_: None) + snapshot = { + **_snapshot(), + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '
x
'}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'page_glyphs': {'1': [{'text': 'x'}]}, + 'tables': {'table-1': [{'text': 'x'}]}, + }, + } + version = record_inline_layout_snapshot(document, snapshot) + assert version.status == 'failed' + assert 'shipping_document_layout_coordinate_evidence_persist_failed' in version.issues_json + + def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app): """坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。""" with app.app_context(): diff --git a/backend/tests/test_shipping_document_layout_native_pdf.py b/backend/tests/test_shipping_document_layout_native_pdf.py index 822a018d..d3d8170c 100644 --- a/backend/tests/test_shipping_document_layout_native_pdf.py +++ b/backend/tests/test_shipping_document_layout_native_pdf.py @@ -115,6 +115,53 @@ def test_attach_native_pdf_page_images_renders_only_missing_pages(): assert attached[1].characters is chars_b +def test_extract_native_pdf_pages_closes_pdfium_handles_before_returning(): + """PDFium 句柄必须在数据复制后显式关闭,不能留给 weakref finalizer 在进程退出时回收。""" + closed: list[str] = [] + + class FakeTextPage: + def count_chars(self): + return 0 + + def close(self): + closed.append('text') + + class FakePage: + def get_size(self): + return 200, 100 + + def get_textpage(self): + return FakeTextPage() + + def get_rotation(self): + return 0 + + def close(self): + closed.append('page') + + class FakeDocument: + def __init__(self, _content): + self.page = FakePage() + + def __len__(self): + return 1 + + def __getitem__(self, _index): + return self.page + + def close(self): + closed.append('document') + + with patch( + 'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument', + FakeDocument, + ): + pages = extract_native_pdf_pages(b'%PDF', render_images=False) + + assert len(pages) == 1 + assert closed == ['text', 'page', 'document'] + + def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): """PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。""" class FakeTextPage: @@ -135,6 +182,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): assert loose is True return (10 + index * 4, 80, 13 + index * 4, 88) + def close(self): + """模拟 PDFium text page 的显式释放接口。""" + class FakePage: """模拟无需渲染的单页 PDF。""" @@ -150,6 +200,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): """样本不旋转。""" return 0 + def close(self): + """模拟 PDFium page 的显式释放接口。""" + class FakeDocument: """模拟 PDFium 文档的页数和索引访问。""" @@ -164,6 +217,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph(): """返回唯一页面。""" return FakePage() + def close(self): + """模拟 PDFium document 的显式释放接口。""" + with patch( 'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument', FakeDocument, @@ -242,6 +298,35 @@ def test_native_pdf_text_fallback_accepts_po_header_synonyms_without_false_page_ assert 'PURCHASE' not in tables[0]['html'] +def test_native_pdf_text_fallback_skips_separator_between_header_and_first_data_row(): + """表头下的起始横线不能截断无框采购订单的首条明细。""" + characters = [] + for y, entries in [ + (10, [('Item', 10), ('Material', 55), ('Qty', 135)]), + (22, [('________________________________________', 10)]), + (34, [('00010', 10), ('PART-A', 55), ('2', 135)]), + (46, [('________________________________________', 10)]), + (58, [('Total:', 90), ('2', 135)]), + ]: + for value, x0 in entries: + for index, char in enumerate(value): + characters.append(PositionedCharacter( + text=char, source_index=len(characters), + bbox=LayoutBBox(x0=x0 + index * 4, y0=y, x1=x0 + index * 4 + 3, y1=y + 8), + )) + page = NativePdfPage( + page_no=1, width=180, height=100, rotation=0, characters=characters, + image=np.full((200, 360), 255, dtype=np.uint8), + ) + + tables = build_native_pdf_text_table_fallbacks(b'%PDF', native_pages=[page]) + + # 起始横线后仍须保留首条业务数据;合计行和表尾横线不属于候选表。 + assert len(tables) == 1 + assert '00010' in tables[0]['html'] + assert 'Total:' not in tables[0]['html'] + + def test_native_pdf_unique_text_builds_traceable_needs_review_layout(): """唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。""" mineru = _candidate('
PartQty
') diff --git a/backend/tests/test_shipping_document_layout_runtime.py b/backend/tests/test_shipping_document_layout_runtime.py index 4f95781b..9a0b0c46 100644 --- a/backend/tests/test_shipping_document_layout_runtime.py +++ b/backend/tests/test_shipping_document_layout_runtime.py @@ -65,6 +65,7 @@ def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(a app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False, ) with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', @@ -107,6 +108,7 @@ def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False, ) native_pages = [object()] timings: dict[str, int] = {} @@ -157,6 +159,7 @@ def test_runtime_empty_mineru_tables_use_pdfium_provider_fallback(app): app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False, ) empty_candidate = _candidate().model_copy(update={'pages': [ _candidate().pages[0].model_copy(update={'tables': []}), diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index 79231f52..b734085e 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -30,6 +30,16 @@ from app.models import ( ) from app.services.shipping_notice import document_profile_quality_service as quality from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot +from app.services.file_assets import storage as file_asset_storage_module + + +@pytest.fixture(autouse=True) +def _memory_file_asset_storage(monkeypatch): + """测试外置坐标证据使用内存对象,保持 FileAsset/MinIO 契约而不依赖服务。""" + objects: dict[str, bytes] = {} + monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'upload_bytes', lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data))) + monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'get_bytes', lambda storage_key: objects[storage_key]) + monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None)) @pytest.mark.parametrize( @@ -52,8 +62,8 @@ def test_blind_test_order_field_comparison_rejects_different_values(): ) -def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source(): - """盲测仅在模板显式启用自适应模式时改用整页字符,默认表格模式必须保持不变。""" +def test_quality_region_uses_page_glyphs_for_every_reconstruction_mode(): + """盲测与预览/正式解析必须从当前页同一字符事实开始重建。""" evidence = { 'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {'1': [{'text': 'PAGE'}]}, @@ -62,13 +72,36 @@ def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_sourc assert quality._region_characters_for_quality( region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'), evidence=evidence, raw_table=raw_table, table_id='table-1', - ) == [{'text': 'TABLE'}] + ) == [{'text': 'PAGE'}] assert quality._region_characters_for_quality( region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'), evidence=evidence, raw_table=raw_table, table_id='table-1', ) == [{'text': 'PAGE'}] +def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages(): + """关键断言:第二页只有合同正文时,不能重复重建第一页的订单明细。""" + evidence = { + 'tables': {'table-1': [{'text': 'TABLE'}]}, + 'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'TERMS'}]}, + } + region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False)) + raw_table = {'table_id': 'table-1', 'page_no': 1} + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}] + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None + + +def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region(): + """关键断言:显式跨页区域只能使用后续页自己的 page glyphs。""" + evidence = { + 'tables': {'table-1': [{'text': 'PAGE-1'}]}, + 'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'PAGE-2'}]}, + } + region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=True)) + raw_table = {'table_id': 'table-1', 'page_no': 1} + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) == [{'text': 'PAGE-2'}] + + def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]: """创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。""" user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin') @@ -244,10 +277,8 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a ) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id) assert executed['latest_run']['status'] == 'passed', executed['latest_run'] - with pytest.raises(Exception) as self_approval: - quality.approve_suite(suite_id=suite['id'], actor_id=user.id) - assert getattr(self_approval.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY' - approved = quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id) + # 业务规则:具备管理员权限即可批准,不再要求必须由其他管理员批准。 + approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id) assert approved['status'] == 'approved' assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) qualification = quality.qualification_summary(profile) @@ -334,6 +365,7 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app): layout_version = documents[1].current_layout_version payload = dict(layout_version.payload_json) + payload.pop('coordinate_evidence_ref', None) payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}} layout_version.payload_json = payload db.session.commit() @@ -344,7 +376,6 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app): if item['document_id'] == documents[1].id ) assert candidate['review_mode'] == 'preparing' - assert candidate['confirmable'] is False assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing'] @@ -365,27 +396,6 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) - def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None): - """模拟从原始 PDF 恢复整页字符,验证盲测不依赖 MinerU table_id。""" - assert page_nos is None - recovered = dict(layout) - recovered['coordinate_evidence'] = { - 'pages': {'1': {'width': 200, 'height': 60}}, - 'page_glyphs': {'1': [ - {'text': char, 'bbox': { - 'x0': x0 + char_index * 5, 'y0': 20, - 'x1': x0 + char_index * 5 + 4, 'y1': 30, - }} - for text, x0 in [('PN-1', 30), ('3', 150)] - for char_index, char in enumerate(text) - ]}, - 'sources': {'pages': {'1': 'pdf_coordinate'}}, - 'tables': {}, - } - return recovered - - monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates) - available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples'] candidate_option = next(item for item in available if item['document_id'] == document.id) assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID @@ -393,11 +403,13 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): assert candidate_option['confirmable'] is False assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing'] - candidate = quality.preview_independent_sample( - suite_id=suite['id'], document_id=document.id, - table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id, - ) - assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}] + with pytest.raises(Exception) as diagnostic_preview: + quality.preview_independent_sample( + suite_id=suite['id'], document_id=document.id, + table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id, + ) + assert getattr(diagnostic_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID' + candidate = {'rows': []} with pytest.raises(Exception) as bypassed_review: quality.add_sample( suite_id=suite['id'], document_id=document.id, @@ -405,7 +417,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): expected_rows=candidate['rows'], actor_id=user.id, ) assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID' - assert candidate['confirmable'] is False + assert diagnostic_preview.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID' with pytest.raises(Exception) as diagnostic_confirmation: quality.confirm_sample_reviews( suite_id=suite['id'], document_id=document.id, @@ -414,7 +426,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch): layout_version_id=current_version.id, layout_payload_checksum=current_version.payload_checksum, actor_id=user.id, ) - assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE' + assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID' def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch): @@ -431,29 +443,6 @@ def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch): db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) - def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None): - """模拟正在预热时直接从原 PDF 恢复整页坐标,空布局不得阻断复核。""" - assert layout == {'status': 'pending', 'tables': [], 'issues': []} - assert page_nos is None - return { - **layout, - 'coordinate_evidence': { - 'pages': {'1': {'width': 200, 'height': 60}}, - 'page_glyphs': {'1': [ - {'text': char, 'bbox': { - 'x0': x0 + char_index * 5, 'y0': 20, - 'x1': x0 + char_index * 5 + 4, 'y1': 30, - }} - for text, x0 in [('PN-1', 30), ('3', 150)] - for char_index, char in enumerate(text) - ]}, - 'sources': {'pages': {'1': 'pdf_coordinate'}}, - 'tables': {}, - }, - } - - monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates) - available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples'] candidate_option = next(item for item in available if item['document_id'] == document.id) assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID @@ -484,26 +473,6 @@ def test_document_candidate_identity_expires_after_background_layout_completion( for item in available ) - def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None): - """文档级复核使用整页证据,不依赖后台刚生成的表格身份。""" - assert page_nos is None - recovered = dict(layout) - recovered['coordinate_evidence'] = { - 'pages': {'1': {'width': 200, 'height': 60}}, - 'page_glyphs': {'1': [ - {'text': char, 'bbox': { - 'x0': x0 + char_index * 5, 'y0': 20, - 'x1': x0 + char_index * 5 + 4, 'y1': 30, - }} - for text, x0 in [('PN-1', 30), ('3', 150)] - for char_index, char in enumerate(text) - ]}, - 'sources': {'pages': {'1': 'pdf_coordinate'}}, - 'tables': {}, - } - return recovered - - monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates) with pytest.raises(Exception) as stale_preview: quality.preview_independent_sample( suite_id=suite['id'], document_id=document.id, @@ -600,8 +569,9 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid record_inline_layout_snapshot(document, { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1}], - 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}}, + 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, }) + db.session.flush() db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) for document in documents: @@ -671,7 +641,7 @@ def test_coordinate_blind_preview_skips_header_only_regions(app): record_inline_layout_snapshot(document, { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1}], - 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}}, + 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, }) db.session.commit() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) @@ -680,6 +650,56 @@ def test_coordinate_blind_preview_skips_header_only_regions(app): assert candidate['rows'] == [] +def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app): + """盲测候选必须和编辑器预览一样排除表头视觉区域。""" + with app.app_context(): + profile, user, documents = _published_profile_with_samples() + profile.definition_json = { + 'document_match': {'required_anchors': []}, + 'table_regions': [{ + 'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'header_layouts': [{ + 'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, + 'field_regions': [], + }], + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': 1}, + 'field_regions': [ + {'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', + 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}, + ], + }], + }], 'order_field_layouts': [], + } + glyphs = [ + {'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 10, 'x1': 23 + index * 4, 'y1': 20}} + for index, char in enumerate('Item') + ] + [ + {'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}} + for index, char in enumerate('20') + ] + [ + {'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}} + for index, char in enumerate('PART-A') + ] + record_inline_layout_snapshot(documents[1], { + 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1}], + 'coordinate_evidence': { + 'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + db.session.commit() + candidate = quality._candidate_for_sample( + profile=profile, document_id=documents[1].id, table_id='table-1', + ) + assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}] + + def test_profile_checksum_change_invalidates_approved_quality_credential(app): """关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。""" with app.app_context(): diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py index bf7d9055..3d89d9d1 100644 --- a/backend/tests/test_shipping_excel_template.py +++ b/backend/tests/test_shipping_excel_template.py @@ -19,7 +19,7 @@ from app import db from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ) from app.services.shipping_notice import excel_template @@ -152,12 +152,10 @@ def _workbook_upload() -> FileStorage: def test_filename_pattern_supports_business_number_and_split_business_variables(): """业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。""" - shipping_case = ShippingCase( - case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC', - business_date=date(2026, 6, 2), sequence_value=1, + task = ShippingNotice( + task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201', + customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1, ) - task = ShippingNotice(task_no='TASK-FILENAME', inventory_source_code='DBS') - task.shipping_case = shipping_case template = ShippingExcelTemplate( template_code='FILENAME', display_name='Filename', definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'}, @@ -333,8 +331,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id), ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id), ]) + confirmed_customer = ShippingCustomer( + standard_name='Export ACME', short_code='EAC', status='active', + ) + db.session.add(confirmed_customer) + db.session.flush() task = ShippingNotice( task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB', + customer_id=confirmed_customer.id, + customer_resolution_status='confirmed', # 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。 inventory_warehouse_id=None, inventory_lines_json=[{ _inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9', @@ -348,6 +353,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): lines=[(1, part.id, 'PN-1', 1, '1000000001')], ) + assert task.business_no is None path, filename, artifact = generate_shipment_excel(task) db.session.commit() @@ -363,10 +369,13 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path): assert artifact.order_schema_version_id == version.id assert artifact.inventory_parsing_profile_id == parsing.id assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0 + assert task.business_no is not None + assert task.business_no.startswith('EAC') - # 已存在待上传 Artifact 时仍保持原有幂等保护,和 Warehouse ID 无关。 - with pytest.raises(ValueError, match='当前任务存在待上传的发货 Excel'): + # 一个 Notice 已有 Excel 后必须创建新 Notice,禁止同号追加第二个 Artifact。 + with pytest.raises(ConflictError) as second_export: generate_shipment_excel(task) + assert second_export.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED' def test_header_mapping_rejects_line_order_field(app): @@ -401,17 +410,13 @@ def test_export_date_system_fact_uses_business_timezone(app): assert isinstance(value, date) -def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app): - """Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。""" +def test_excel_pull_request_number_uses_notice_business_number(app): + """Excel Pull Request Number 直接使用 Notice business_no,不因导出日期重编号。""" with app.app_context(): - shipping_case = ShippingCase( - case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1, - ) - task = ShippingNotice(task_no='TASK-EXCEL-NO') - task.shipping_case = shipping_case + task = ShippingNotice(task_no='TASK-EXCEL-NO', business_no='IVMX26080801', business_sequence_value=1) - assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101' - assert shipping_case.business_no == 'IVMX26080801' + assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26080801' + assert task.business_no == 'IVMX26080801' def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app): diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index ca754496..5e944dab 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -16,8 +16,11 @@ from app.services.shipping_notice.generic_parse_plan import compile_generic_pars from app.services.shipping_notice.order_extraction_workflow import ( _apply_stp_route_adjudication, _coordinate_profile_rows, + _physical_table_targets_profile_region, _profile_table_candidates, _route_reason_for_issue, + _selected_coordinate_transform, + _virtual_page_without_rows_is_nonblocking, _should_attempt_generic_extraction, route_deterministic_unit, ) @@ -38,6 +41,37 @@ def _field(code: str, *, scope: str = 'line', required: bool = False, collection } +def test_physical_table_outside_profile_region_is_not_a_parse_target(): + """页脚等非目标物理表不得进入模板明细重建并污染已成功的订单表。""" + regions = [{ + 'region_id': 'order-lines', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': .02, 'y0': .40, 'x1': .94, 'y1': .46}, + 'line_layouts': [{}], + }] + page = {'width': 612, 'height': 792} + + assert _physical_table_targets_profile_region( + raw_table={'table_id': 'order-lines', 'page_no': 1, 'bbox': {'x0': 15, 'y0': 235, 'x1': 570, 'y1': 345}}, + table_regions=regions, page_size=page, + ) is True + assert _physical_table_targets_profile_region( + raw_table={'table_id': 'footer-summary', 'page_no': 1, 'bbox': {'x0': 16, 'y0': 659, 'x1': 569, 'y1': 721}}, + table_regions=regions, page_size=page, + ) is False + + +def test_empty_virtual_page_does_not_block_a_successful_target_table(): + """无物理表的续页仅用于补漏;没有行时不得覆盖已成功的目标表。""" + assert _virtual_page_without_rows_is_nonblocking( + raw_table={'table_id': 'page-2', 'page_no': 2}, + fixed_rows=[], adaptive_rows=[], + ) is True + assert _virtual_page_without_rows_is_nonblocking( + raw_table={'table_id': 'page-2', 'page_no': 2}, + fixed_rows=[{'status': 'needs_review', 'issues': ['field_invalid']}], adaptive_rows=[], + ) is False + + def _good_candidate() -> dict: return { 'page_no': 1, @@ -340,6 +374,43 @@ def test_should_attempt_generic_extraction_allows_no_special_profile_feature(): ) is True +def test_legacy_profile_does_not_apply_matcher_inferred_coordinate_transform(): + """已发布 legacy 模板的正式字段解析必须沿用盲测验证过的绝对坐标。""" + inferred = { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': .03, + 'anchor_ids': ['title'], 'reason_codes': [], + } + transform = _selected_coordinate_transform( + raw_profile={ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'definition': {'coordinate_model': {'type': 'legacy'}}, + }, + profile_match={ + 'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'candidates': [{ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'coordinate_transform': inferred, + }], + }, + ) + + # 关键断言:自动推断的位移只服务于匹配,不得改变 legacy 模板的正式字段坐标。 + assert transform is None + assert _selected_coordinate_transform( + raw_profile={ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'definition': {'coordinate_model': {'type': 'anchor_frame'}}, + }, + profile_match={ + 'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'candidates': [{ + 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64, + 'coordinate_transform': inferred, + }], + }, + ) == inferred + + def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkeypatch): """自适应模板的完整业务行不得按子布局数量误判跨页,成功匹配必须上送路由审计。""" profile = { @@ -419,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey assert result['match']['status'] == 'unique_match' assert result['match']['profile_code'] == 'ODP-PRODUCTION' # 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。 - assert seen_table_ids == ['native-text-table-p1-1'] + assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1'] def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): @@ -429,6 +500,7 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): region=SimpleNamespace(model_dump=lambda: {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}), termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False), line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines', + model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages', 'line_layouts': [{}]}, ) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile', @@ -463,6 +535,7 @@ def test_coordinate_profile_rows_forward_selected_match_transform_without_recomp region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}), termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False), line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines', + model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages'}, ) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile', diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py index cceaa7e6..66e9d5f0 100644 --- a/backend/tests/test_shipping_notice_business_case.py +++ b/backend/tests/test_shipping_notice_business_case.py @@ -1,25 +1,23 @@ """ backend/tests/test_shipping_notice_business_case.py -用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。 -依赖:app fixture、ShippingNotice/ShippingCase、business_case_service。 -逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。 +用途:验证 Notice 建单和替代关系不依赖 ShippingCase。 +依赖:app fixture、ShippingNotice、task_workflow。 +逻辑:直接调用领域服务并断言 Notice 独立事实,不触发解析和库存副作用。 """ +from app import db import pytest -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.models import ShippingCustomer, ShippingNotice 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: - """构造最小货代任务,供业务单关系断言使用。""" +def _task(task_no: str, *, supersedes_task_id: int | None = None) -> ShippingNotice: + """构造最小 Notice,供替代关系断言使用。""" return ShippingNotice( task_no=task_no, - shipping_case_id=case_id, supersedes_task_id=supersedes_task_id, source_type='manual', ) @@ -33,76 +31,32 @@ def _active_customer(*, short_code: str = 'CASE') -> ShippingCustomer: return customer -def test_normal_and_force_create_use_different_cases(app): - """普通建单和强制新建必须各自创建独立业务单。""" +def test_notices_are_independent_without_business_case(app): + """不同 Notice 无需中间聚合实体,业务事实由自身保存。""" with app.app_context(): - normal = resolve_shipping_case_for_new_task(created_by_id=None) - forced = resolve_shipping_case_for_new_task( - duplicate_resolution_type='force_create', - created_by_id=None, - ) - assert normal.id != forced.id - assert normal.business_no is None - assert forced.business_no is None + first = _task('SN-NOTICE-INDEPENDENT-1') + second = _task('SN-NOTICE-INDEPENDENT-2') + db.session.add_all([first, second]) + db.session.commit() + assert first.id != second.id + assert first.business_no is None + assert second.business_no is None -def test_revision_inherits_existing_parent_case(app): - """修订任务必须继承父任务已有业务单,不能创建新业务单。""" +def test_replacement_links_to_parent_notice(app): + """替代 Notice 仅链接原 Notice,不继承或依赖 Case。""" with app.app_context(): - case = resolve_shipping_case_for_new_task(created_by_id=None) - parent = _task('SN-CASE-PARENT-1', case_id=case.id) + parent = _task('SN-NOTICE-PARENT-1') db.session.add(parent) db.session.flush() - - resolved = resolve_shipping_case_for_new_task( - supersedes_task_id=parent.id, - duplicate_resolution_type='revision', - ) - assert resolved.id == case.id - assert ShippingCase.query.count() == 1 + replacement = _task('SN-NOTICE-REPLACEMENT-1', supersedes_task_id=parent.id) + db.session.add(replacement) + db.session.commit() + assert replacement.supersedes_task_id == parent.id -def test_revision_rejects_parent_without_business_case(app): - """修订父任务缺少业务单时必须阻断,禁止隐式补建。""" - with app.app_context(): - parent = _task('SN-CASE-LEGACY-1') - db.session.add(parent) - db.session.flush() - - with pytest.raises(ConflictError) as exc_info: - resolve_shipping_case_for_new_task( - supersedes_task_id=parent.id, - duplicate_resolution_type='revision', - ) - assert exc_info.value.code == 'SHIPPING_NOTICE.REVISION_CASE_MISSING' - assert ShippingCase.query.count() == 0 - - -def test_revision_chain_reuses_root_case(app): - """连续修订版本必须沿用同一业务单聚合。""" - with app.app_context(): - case = resolve_shipping_case_for_new_task(created_by_id=None) - parent = _task('SN-CASE-CHAIN-1', case_id=case.id) - db.session.add(parent) - db.session.flush() - revision_case = resolve_shipping_case_for_new_task( - supersedes_task_id=parent.id, - duplicate_resolution_type='revision', - ) - revision = _task('SN-CASE-CHAIN-2', case_id=revision_case.id, supersedes_task_id=parent.id) - db.session.add(revision) - db.session.flush() - - next_case = resolve_shipping_case_for_new_task( - supersedes_task_id=revision.id, - duplicate_resolution_type='revision', - ) - assert next_case.id == case.id - assert ShippingCase.query.count() == 1 - - -def test_create_task_assigns_case_and_serializes_it(app): - """真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。""" +def test_create_task_assigns_notice_customer_and_serializes_it(app): + """真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。""" with app.app_context(): customer = _active_customer(short_code='CRT') result = create_task({ @@ -111,11 +65,9 @@ def test_create_task_assigns_case_and_serializes_it(app): 'customer_id': customer.id, }) task = ShippingNotice.query.filter_by(task_no=result['task_id']).one() - assert task.shipping_case_id is not None assert task.customer_resolution_status == 'confirmed' - assert result['data']['shipping_case_id'] == task.shipping_case_id - assert result['data']['case_no'] == task.shipping_case.case_no - assert task.shipping_case.customer_id == customer.id + assert task.customer_id == customer.id + assert result['data']['customer_id'] == customer.id def test_create_task_rejects_without_customer(app): diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 71217e83..7ff68aa7 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -13,7 +13,7 @@ import pytest from app import db from app.models import ( - ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, + ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink, ShippingOrderCustomerMatch, @@ -101,7 +101,7 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: """为直接构造的 RPA 回调任务补齐已确认客户。 - 核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户, + 核心逻辑:测试不经建单工作流时,显式绑定激活客户, 使回调测试只验证 RPA 契约,而不绕过客户身份门禁。 """ customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none() @@ -111,47 +111,17 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: ) db.session.add(customer) db.session.flush() - case = ShippingCase( - case_no=f'CASE-{task.task_no}', customer=customer, - customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, - ) - task.shipping_case = case + task.customer = customer + task.customer_name_snapshot = customer.standard_name + task.customer_short_code_snapshot = customer.short_code task.customer_resolution_status = 'confirmed' task.customer_resolution_method = 'test_fixture' - db.session.add_all([case, task]) + db.session.add(task) db.session.flush() # 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。 task._test_customer_confirmed = True -@pytest.fixture(autouse=True) -def _confirmed_customer_for_rpa_flows(app, monkeypatch): - """为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。""" - from app.services.shipping_notice import task_workflow - - original = task_workflow.resolve_shipping_case_for_new_task - - def _resolve_confirmed_case(**kwargs): - case = original(**kwargs) - if case.customer_id is not None: - return case - customer = db.session.query(ShippingCustomer).filter_by(short_code="RPA").one_or_none() - if customer is None: - customer = ShippingCustomer( - standard_name="RPA 流程测试客户", - short_code="RPA", - status="active", - ) - db.session.add(customer) - db.session.flush() - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - return case - - monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) - - @pytest.fixture(autouse=True) def _freeze_test_rpa_batch_callback_contract(monkeypatch): """兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。""" diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index d3e03450..3e7b88ee 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -19,6 +19,7 @@ from app.services.shipping_notice.query_service import ( resolve_task_from_payload, serialize_task, task_export_error_message, + list_freight_notice_groups_for_task, ) from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT @@ -300,6 +301,116 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app): assert "can_handle" not in no_viewer +def test_serialize_task_summary_projects_only_current_notice_line_facts(app): + """同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。""" + with app.app_context(): + from app import db + from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch + from app.services.shipping_notice.query_service import serialize_task_summary + + first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11) + second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11) + db.session.add_all([first, second]); db.session.flush() + db.session.add_all([ + ShippingNoticeLine( + notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST', + reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'}, + ), + ShippingNoticeLine( + notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND', + reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'}, + ), + ShippingNoticeLineInventoryMatch( + task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready', + available_qty='20', shortage_qty='0', is_current=True, + ), + ShippingNoticeLineInventoryMatch( + task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready', + available_qty='9', shortage_qty='0', is_current=True, + ), + ]) + db.session.commit() + + data = serialize_task_summary(first, viewer_user_id=11) + + assert data['business_no'] == 'WVC26082301' + assert data['notice_line_summary'] == [{ + 'line_no': '00010', 'part_number': 'PART-FIRST', 'customer_part_number': None, + 'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20', + 'shortage_qty': '0', 'inventory_status': 'ready', + }] + + +def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app): + """货代上传聚合必须按同 PO 的 business_no 拆组,并排除无业务号及他人 Notice。""" + with app.app_context(): + from app import db + from app.models import ShippingNoticeLine + from app.services.shipping_notice import query_service + + def with_po(task_no, business_no, user_id): + return ShippingNotice(task_no=task_no, business_no=business_no, source_type='manual', user_id=user_id) + + first = with_po('SN-GROUP-1', 'WYC26082401', 11) + second = with_po('SN-GROUP-2', 'WYC26082402', 11) + no_business = with_po('SN-GROUP-3', None, 11) + other = with_po('SN-GROUP-4', 'WYC26082499', 99) + db.session.add_all([first, second, no_business, other]); db.session.flush() + db.session.add_all([ + ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}), + ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}), + ]) + db.session.commit() + + original_header_reader = query_service.current_header_field_values_or_empty + # customer_po_number 是当前动态 Schema 的正式 PO 字段;聚合必须不依赖旧兼容投影。 + query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-GROUP'} + try: + result = list_freight_notice_groups_for_task(first, user_id=11) + finally: + query_service.current_header_field_values_or_empty = original_header_reader + assert result['po_number'] == 'PO-GROUP' + assert [item['business_no'] for item in result['items']] == ['WYC26082401', 'WYC26082402'] + # 单条菜单必须消费服务端授权投影,前端不得按上传状态自行猜测可执行动作。 + assert 'available_actions' in result['items'][0] + assert result['items'][0]['lines'][0]['part_number'] == 'PART-A' + assert result['items'][1]['lines'][0]['part_number'] == 'PART-B' + + +def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app): + """当前 Extraction 不可读时,货代上传聚合仍必须以冻结快照中的客户 PO 对齐同一发货批次。""" + with app.app_context(): + from app import db + from app.models import ShippingOrderSnapshot + from app.services.shipping_notice import query_service + + first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11) + second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11) + db.session.add_all([first, second]); db.session.flush() + for task in (first, second): + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=task.id, + schema_version_id=1, + order_data_version=1, + header_values_json={}, + customer_po_number='ZNB-16754796', + ) + db.session.add(snapshot); db.session.flush() + task.order_snapshot_id = snapshot.id + db.session.commit() + + original_header_reader = query_service.current_header_field_values_or_empty + query_service.current_header_field_values_or_empty = lambda _task: {} + try: + result = list_freight_notice_groups_for_task(first, user_id=11) + finally: + query_service.current_header_field_values_or_empty = original_header_reader + + assert result['po_number'] == '16754796' + assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412'] + + def test_list_my_todos_and_count_buckets(app): """list_my_todos 按 bucket 分类;count 徽标与 pending 一致。""" with app.app_context(): @@ -458,8 +569,8 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil assert original.case_no not in review_case_nos -def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app): - """历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。""" +def test_open_review_case_without_current_candidate_enters_intake_parse(app): + """无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。""" with app.app_context(): from app import db from app.services.shipping_notice.order_review_service import ensure_run_review_cases @@ -476,7 +587,8 @@ def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app): pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50) hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no) - assert hit['ui_state']['lifecycle_stage'] is None + assert hit['ui_state']['lifecycle_stage'] == 'intake_parse' + assert hit['ui_state']['intake_parse_authorized'] is True assert hit['ui_state']['lifecycle_entries'] == [] @@ -681,7 +793,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app): row = SimpleNamespace( review_status=task.review_status, pending_human_reason=task.pending_human_reason, - shipping_case_id=task.shipping_case_id, customer_resolution_status=task.customer_resolution_status, order_snapshot_id=task.order_snapshot_id, current_order_extraction_id=task.current_order_extraction_id, diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index e90f2f72..f6617e61 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -4,6 +4,25 @@ from app.services.shipping_notice.reservation_id import ( normalize_reservation_id, validated_reservation_id, ) +from app.services.shipping_notice.reservation_region import ( + apply_reservation_region_candidates, + extract_reservation_from_region_text, + extract_reservation_from_vendor_comments_pages, +) + + +def _glyph_lines(*lines: str) -> list[dict]: + """构造按视觉阅读顺序排列的最小页面文字证据。""" + glyphs = [] + for row_index, line in enumerate(lines): + for column_index, char in enumerate(line): + glyphs.append({ + 'text': char, + 'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12}, + 'source_index': len(glyphs), + 'boundary_before': 'space' if char == ' ' else 'none', + }) + return glyphs def test_match_numeric_reservation_id(): @@ -37,6 +56,91 @@ def test_reservation_contract_only_accepts_five_or_ten_digits(): assert not is_valid_reservation_id("12345678901", numeric_only=True) +def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present(): + """专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。""" + assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{ + 'value': '3000098851', 'line_no': 1, 'scope': 'line', + 'raw_text': 'Reservation#3000098851 for line#1', 'status': 'mapped', + }] + + +def test_reservation_region_assigns_reservation_without_line_to_header(): + """无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。""" + assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{ + 'value': '33008', 'line_no': None, 'scope': 'header', + 'raw_text': 'MDW hub order.Reservation#33008', 'status': 'header', + }] + + +def test_reservation_region_ignores_unrelated_numeric_noise(): + """备注区的普通客户号、数量等数字没有 Reservation 标签时不得被误写入订单。""" + assert extract_reservation_from_region_text("End Customer: D1\nQuantity: 1000143920") == [] + + +def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading(): + """专区启用后跨页累计 Vendor Comments,首次 Terms 标题后的值必须被排除。""" + candidates, reason = extract_reservation_from_vendor_comments_pages([ + (1, _glyph_lines('Vendor Comments:', 'Reservation#33008')), + (2, _glyph_lines('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999')), + ]) + + assert reason is None + assert [item['value'] for item in candidates] == ['33008', '3000098851'] + + +def test_vendor_comments_window_requires_start_and_end_headings(): + """缺少任一边界时不能把全文中的 Reservation 当作专区证据。""" + candidates, reason = extract_reservation_from_vendor_comments_pages([ + (1, _glyph_lines('Reservation#33008')), + ]) + + assert candidates == [] + assert reason == 'vendor_comments_anchor_missing' + + +def test_reservation_region_applies_header_and_line_override_together(): + """整单值是默认值,指定行的 Reservation 仅覆盖对应明细。""" + applied = apply_reservation_region_candidates( + candidates=extract_reservation_from_region_text( + "MDW hub order.Reservation#33008\nReservation#3000098851 for line#1" + ), + header_field_id='header-reservation', + line_field_id='line-reservation', + line_count=2, + ) + + assert applied.header_value == '33008' + assert applied.line_values == {1: '3000098851'} + assert applied.needs_review is False + + +def test_reservation_region_marks_only_conflicts_and_invalid_line_references_for_review(): + """重复同一值可去重;同一行冲突或越界才阻断自动建单。""" + applied = apply_reservation_region_candidates( + candidates=extract_reservation_from_region_text( + "Reservation#3000098851 for line#1\nReservation#3000098852 for line#1\n" + "Reservation#3000098853 for line#3" + ), + header_field_id='header-reservation', + line_field_id='line-reservation', + line_count=2, + ) + + assert applied.needs_review is True + assert set(applied.review_reasons) == {'conflicting_line_value', 'line_out_of_range'} + + +def test_reservation_region_requires_review_when_numbered_value_has_no_line_target(): + """Schema 未启用行级字段时,不能静默丢弃带行号的覆盖值。""" + applied = apply_reservation_region_candidates( + candidates=extract_reservation_from_region_text("Reservation#3000098851 for line#1"), + header_field_id='header-reservation', line_field_id=None, line_count=1, + ) + + assert applied.needs_review is True + assert applied.review_reasons == ('line_field_unavailable',) + + def test_reservation_gate_blocks_empty_and_malformed_order_lines(): """空订单或畸形行都不能被视为 Reservation 门禁通过。""" from app.services.shipping_notice.reservation_gate import reservation_gate_issues diff --git a/backend/tests/test_shipping_notice_state_machine.py b/backend/tests/test_shipping_notice_state_machine.py index 3c6eaefe..db8cb73a 100644 --- a/backend/tests/test_shipping_notice_state_machine.py +++ b/backend/tests/test_shipping_notice_state_machine.py @@ -79,7 +79,6 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None: upload_status="uploaded", review_status=None, pending_human_reason=None, - shipping_case_id=None, customer_resolution_status=None, order_snapshot_id=None, inventory_lines_json=None, diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index 63725e0f..fa52d7c7 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -14,7 +14,7 @@ import pytest from app import db from app.models import ( ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule, - ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, + ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot, ShippingOrderSnapshotLine, @@ -107,34 +107,6 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation db.session.flush() -@pytest.fixture(autouse=True) -def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch): - """为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。""" - from app.services.shipping_notice import task_workflow - - original = task_workflow.resolve_shipping_case_for_new_task - - def _resolve_confirmed_case(**kwargs): - case = original(**kwargs) - if case.customer_id is not None: - return case - customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none() - if customer is None: - customer = ShippingCustomer( - standard_name="Tool 流程测试客户", - short_code="TST", - status="active", - ) - db.session.add(customer) - db.session.flush() - case.customer_id = customer.id - case.customer_name_snapshot = customer.standard_name - case.customer_short_code_snapshot = customer.short_code - return case - - monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) - - def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret" diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index b1596abd..a124d7c6 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -122,6 +122,85 @@ def _coordinate_definition() -> dict: } +def test_reservation_region_requires_header_and_allows_optional_line_scope_schema(): + """无行号值必须有 Header 落点;启用 Line 后同一区域还可承载行级 Reservation。""" + schema = SimpleNamespace(definition_json={'fields': [{ + 'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', + 'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'], + }, { + 'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'], + }, { + 'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }, { + 'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }]}) + definition = _coordinate_definition() + definition['reservation_id_region'] = { + 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3}, + 'page_scope': 'exact_page', 'page_no': 1, + } + + normalized = service._normalize_definition(definition, schema_version=schema) + + assert normalized['reservation_id_region']['page_no'] == 1 + + +def test_reference_page_frames_are_preserved_by_coordinate_definition_normalization(): + """模板规范化必须保留标注页物理尺寸,不能只保存浏览器百分比坐标。""" + schema = SimpleNamespace(definition_json={'fields': [ + { + 'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'], + }, + ]}) + definition = _coordinate_definition() + definition['reference_page_frames'] = { + '1': {'width': 609, 'height': 791, 'origin': 'pdf_top_left', 'box': 'cropbox'}, + } + + normalized = service._normalize_definition(definition, schema_version=schema) + + assert normalized['reference_page_frames']['1']['width'] == 609.0 + assert normalized['reference_page_frames']['1']['height'] == 791.0 + assert normalized['coordinate_model']['type'] == 'legacy' + + +def test_reference_page_frames_read_annotation_coordinate_evidence(): + """参考页框必须来自冻结 Layout 的 PDF 坐标证据,而不是前端提交。""" + frames = service._reference_page_frames({ + 'coordinate_evidence': {'pages': {'1': {'width': 609, 'height': 791}}}, + }) + + assert frames == { + '1': {'width': 609.0, 'height': 791.0, 'origin': 'pdf_top_left', 'box': 'cropbox'}, + } + + +def test_reservation_region_rejects_schema_without_header_scope(): + """无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。""" + schema = SimpleNamespace(definition_json={'fields': [{ + 'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', + 'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'], + }]}) + definition = _coordinate_definition() + definition['reservation_id_region'] = { + 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3}, + 'page_scope': 'exact_page', 'page_no': 1, + } + + with pytest.raises(Exception) as caught: + service._normalize_definition(definition, schema_version=schema) + + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID' + + def test_visual_sample_preview_reads_common_ocr_value_before_xfa_path_is_selected(app, monkeypatch): """XFA 草稿未选 datasets path 时,仍从共同 PDF 坐标证据显示 PO 样本值。""" glyphs = [ @@ -365,6 +444,45 @@ def test_preview_page_region_text_uses_unique_xfa_widget_when_coordinate_text_is assert result['status'] == 'needs_review' +def test_preview_page_region_text_does_not_use_partial_xfa_widget_value(app, monkeypatch): + """局部框与大 Widget 仅相交时,不能把整段 /V 当作框内视觉样本。""" + document = SimpleNamespace(id=112, asset_id=501, filename='hybrid.pdf') + layout = { + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': []}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout) + monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False) + monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [ + SimpleNamespace( + page_no=1, + normalized_bbox={'x0': .40, 'y0': .10, 'x1': .80, 'y1': .60}, + value='TEMP-S000218922 FRAME MPN:D4-A08AR12000001 Customer', + ), + ], raising=False) + monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'D4-A08AR12000001', raising=False) + + with app.app_context(): + result = service.read_preview_page_region_text( + 1, + data={ + 'document_id': 112, + 'region': {'x0': .50, 'y0': .30, 'x1': .70, 'y1': .40}, + 'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=', + }, + page_no=1, + actor_id=1, + ) + + assert result['text'] == 'D4-A08AR12000001' + assert result['source'] == 'xfa_rendered_ocr' + + def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch): """任意视觉框命中多个带值 Widget 时不得将其中之一冒充样本值。""" document = SimpleNamespace(id=110, asset_id=501, filename='hybrid.pdf') @@ -392,6 +510,39 @@ def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch assert result['source'] == 'acroform_widget_ambiguous' +def test_preview_page_region_text_reads_xfa_canvas_crop_when_server_rendering_has_no_value(app, monkeypatch): + """XFA 可见值必须从管理员当前 PDF.js 画布裁剪图回读,不能以服务端 PDFium 空结果丢弃标注。""" + document = SimpleNamespace(id=111, asset_id=501, filename='hybrid.pdf') + layout = { + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': []}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout) + monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None) + monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: []) + monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'HC07', raising=False) + + with app.app_context(): + result = service.read_preview_page_region_text( + 1, + data={ + 'document_id': 111, + 'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35}, + 'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=', + }, + page_no=1, + actor_id=1, + ) + + assert result['text'] == 'HC07' + assert result['source'] == 'xfa_rendered_ocr' + + def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field(app, monkeypatch): """共同视觉预览忽略旧浏览器重复提交的已绑定未绑定布局,仍返回 PO 样本值。""" glyphs = [ @@ -952,6 +1103,36 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app): ] +def test_order_field_layout_rejects_address_bound_to_number_anchor(app): + """关键断言:地址字段不能保存为订单编号的 Number 标签,避免错误锚点进入运行时。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].append({ + 'field_id': 'ship-to-address', 'field_code': 'ship_to_address', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }) + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'ship_to_address_layout', 'field_id': '', 'field_code': 'ship_to_address', + 'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1, + 'anchor': {'anchor_id': 'order_field_1_1_anchor', 'text': 'Number'}, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }] + + with pytest.raises(Exception) as caught: + service.save_draft({ + 'profile_code': 'SHIP_TO_NUMBER', 'display_name': 'Ship to number mismatch', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID' + assert getattr(caught.value, 'details', {}).get('reason') == 'order_field_anchor_semantic_mismatch' + assert getattr(caught.value, 'details', {}).get('field_code') == 'ship_to_address' + + def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app): """订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。""" with app.app_context(): @@ -2119,6 +2300,86 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke assert preview['source_row_indices'] == [[], [0]] +def test_profile_region_preview_does_not_promote_unanchored_header_to_data(app, monkeypatch): + """页级证据没有有效起行锚点时,预览必须保持无明细并进入 Review 语义。""" + with app.app_context(): + schema = _schema_version() + profile = SimpleNamespace(profile_code='STRICT_PREVIEW', version=1, schema_version=schema) + document = SimpleNamespace(id=308) + definition = _coordinate_definition() + definition['table_regions'][0]['line_layouts'][0]['field_regions'] = [{ + 'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }] + layout = { + 'tables': [{'table_id': 'header-only', 'page_no': 1}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'tables': {'header-only': [ + {'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}}, + ]}, + 'page_glyphs': {'1': [ + {'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}}, + ]}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr( + db.session, 'get', + lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None, + ) + preview = service.preview_profile_region( + 22, data={'document_id': 308, 'table_id': 'header-only', 'definition': definition}, actor_id=1, + ) + + assert preview['rows'] == [['customer_po_line_no']] + assert preview['row_roles'] == ['header'] + assert preview['status'] == 'needs_review' + + +def test_profile_region_preview_excludes_configured_header_regions_from_line_rows(app, monkeypatch): + """已配置的表头区域不得作为坐标明细行;真实起行值仍必须保留。""" + with app.app_context(): + schema = _schema_version() + profile = SimpleNamespace(profile_code='HEADER_BOUNDARY', version=1, schema_version=schema) + document = SimpleNamespace(id=309) + definition = _coordinate_definition() + table = definition['table_regions'][0] + table['header_layouts'] = [{ + 'layout_id': 'header_1', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .2}, + 'field_regions': [], + }] + table['line_layouts'][0]['field_regions'] = [{ + 'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line', + 'region': {'x0': 0, 'y0': .21, 'x1': .3, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate'], + }] + table['line_layouts'][0]['region'] = {'x0': 0, 'y0': .2, 'x1': 1, 'y1': 1} + layout = { + 'tables': [{'table_id': 'header-and-data', 'page_no': 1}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 100}}, + 'tables': {'header-and-data': [ + {'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}}, + {'text': 'Vendor', 'source_index': 1, 'bbox': {'x0': 30, 'y0': 5, 'x1': 45, 'y1': 10}}, + {'text': '10', 'source_index': 2, 'bbox': {'x0': 5, 'y0': 30, 'x1': 15, 'y1': 40}}, + ]}, + }, + } + monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document) + monkeypatch.setattr(service, '_document_layout', lambda _document: layout) + monkeypatch.setattr(db.session, 'get', lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None) + preview = service.preview_profile_region( + 23, data={'document_id': 309, 'table_id': 'header-and-data', 'definition': definition}, actor_id=1, + ) + + assert preview['rows'] == [['customer_po_line_no'], ['10']] + assert preview['source_row_indices'] == [[], [0]] + + def test_profile_region_preview_uses_schema_field_order(app, monkeypatch): """局部候选字段必须按绑定 Schema 顺序返回,不受字段标注先后影响。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index 1cee35c8..5d93848d 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -2420,6 +2420,89 @@ def test_run_summary_omits_legacy_progress_projection(app): assert 'progress' not in payload +def test_run_summary_exposes_user_lifecycle_progress_from_current_activity(app): + """Run 摘要必须提供五阶段用户态进度与当前步骤,供复核台首屏直接展示。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-PROGRESS') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + run.status = 'processing' + run.phase = 'deterministic_parsing' + run.progress_version = 4 + run.last_activity_at = datetime.utcnow() + db.session.commit() + + payload = serialize_order_extraction_run(run) + progress = payload['lifecycle_progress'] + + assert progress['lifecycle_stage'] == 'intake_parse' + assert progress['lifecycle_status'] == 'running' + assert progress['current_step_code'] == 'document_queued' + assert progress['current_step_i18n_key'] == 'chat.shippingProcessing.progress.step.document_queued' + assert isinstance(progress['completed_step_codes'], list) + assert progress['last_activity_at'] + assert progress['health_status'] == 'normal' + assert 'input_snapshot' not in str(progress) + assert 'provider' not in str(progress).lower() + + +def test_run_summary_lifecycle_progress_maps_completed_events_and_current_step(app): + """事件事实映射为稳定用户步骤,并保留已完成步骤顺序。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='LIFECYCLE-EVENTS') + 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') + ensure_order_extraction_plan(run) + unit = run.extraction_plan.units[0] + unit.status = 'extracting' + unit.started_at = datetime.utcnow() + unit.last_activity_at = datetime.utcnow() + latest_sequence = ( + db.session.query(ShippingOrderExtractionProgressEvent.sequence_no) + .filter_by(run_id=run.id) + .order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc()) + .first() + ) + sequence_base = int(latest_sequence[0]) if latest_sequence else 0 + for sequence, code in enumerate(('layout_parsing_completed', 'profile_matching'), start=1): + db.session.add(ShippingOrderExtractionProgressEvent( + run_id=run.id, + unit_id=unit.id, + document_id=document.id, + sequence_no=sequence_base + sequence, + event_code=code, + # 真实写入契约把该完成事实保留为 running,投影仍必须识别为已完成。 + status='running', + visibility='workspace', + summary_json={}, + idempotency_key=f'lifecycle-events-{sequence}', + )) + db.session.commit() + + progress = serialize_order_extraction_run(run)['lifecycle_progress'] + assert progress['current_step_code'] == 'profile_matching' + assert progress['completed_step_codes'] == ['layout_parsing_completed'] + + +def test_run_summary_lifecycle_progress_marks_failed_without_worker_details(app): + """失败 Run 只显示稳定失败态和脱敏字段,不泄漏内部错误正文。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-FAILED') + 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') + transition_order_extraction_run(run, target_status='failed', error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', error_message='secret worker trace') + payload = serialize_order_extraction_run(run) + progress = payload['lifecycle_progress'] + assert progress['lifecycle_status'] == 'failed' + assert progress['health_status'] == 'failed' + assert 'secret worker trace' not in str(progress) + + def test_user_run_summary_never_exposes_worker_error_text(app): """Workspace status cards expose a stable error code, never Provider or Worker details.""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_field_extraction.py b/backend/tests/test_shipping_order_field_extraction.py index 5f14313e..706cd505 100644 --- a/backend/tests/test_shipping_order_field_extraction.py +++ b/backend/tests/test_shipping_order_field_extraction.py @@ -37,7 +37,9 @@ def _glyphs(*lines: tuple[str, float, float]) -> list[dict]: return result -def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfile: +def _profile( + *, layout: dict, page_scope: str = 'first_page', reference_page_frames: dict[str, dict] | None = None, +) -> OrderCoordinateProfile: """构造包含一个独立 header 字段的最小合法 v2 Profile。""" return OrderCoordinateProfile.model_validate({ 'profile_code': 'ORDER-FIELD-TEST', 'version': 1, @@ -48,6 +50,7 @@ def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinate 'scope': 'header', 'page_scope': page_scope, **layout, }], + 'reference_page_frames': reference_page_frames or {}, }) @@ -60,15 +63,38 @@ def _schema(**overrides: object) -> dict[str, dict]: }} -def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict: +def _evidence( + *, pages: dict[str, list[dict]], source: str = 'pdf_coordinate', page_size: tuple[float, float] = (200, 200), +) -> dict: """构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。""" return { - 'pages': {page: {'width': 200, 'height': 200} for page in pages}, + 'pages': {page: {'width': page_size[0], 'height': page_size[1]} for page in pages}, 'page_glyphs': pages, 'sources': {'pages': {page: source for page in pages}}, } +def test_fixed_order_field_uses_annotation_page_frame_when_runtime_page_is_taller(): + """同内容由分页页变为长页时,固定字段仍须读取标注页的 PDF 点坐标。""" + profile = _profile( + layout={'fallback_value_region': {'x0': .10, 'y0': .20, 'x1': .90, 'y1': .30}}, + reference_page_frames={'1': {'width': 200, 'height': 100}}, + ) + + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence( + pages={'1': _glyphs(('45001', 40, 21))}, page_size=(200, 200), + ), + allow_fixed_region_confirmation=True, + )[0] + + # 关键断言:不能把训练页 y=20..30 重投影到长页 y=40..60。 + assert result.status == 'confirmed' + assert result.value == '45001' + + def test_visual_row_prefers_explicit_pdf_space_boundary_over_geometry_threshold(): """真实词间距低于旧阈值时,PDF 文本流的明确空格仍应恢复,不能输出粘连地址。""" row = [ @@ -350,6 +376,25 @@ def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrenc assert result.value == '45001' +def test_unique_anchor_outside_saved_reference_region_is_still_readable(): + """同版式样本唯一命中标签时,旧参考框不得阻断盲测/正式读取。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'ship_to', 'text': 'Ship to', 'match_mode': 'exact', + 'region': {'x0': .55, 'y0': .10, 'x1': .63, 'y1': .12}, + 'position_locked': True, + }, + 'value_region': {'x0': .8, 'y0': 0, 'x1': 4.0, 'y1': 1.0}, + 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('Ship to:ACME', 20, 20))}, + ))[0] + + assert result.status == 'confirmed' + assert result.value == 'ACME' + + def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence(): """历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。""" profile = _profile(layout={ @@ -439,6 +484,24 @@ def test_fallback_and_ocr_never_become_confirmed(): assert ocr_result.status == 'needs_review' +def test_profile_confirmed_fixed_region_is_confirmed_with_native_coordinates(): + """唯一确认模板中的无标签固定区域可作为原生 PDF 正式字段证据。""" + profile = _profile(layout={ + 'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2}, + }) + + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence(pages={'1': _glyphs(('45001', 30, 20))}), + allow_fixed_region_confirmation=True, + )[0] + + # 关键断言:此放宽仅由已确认的模板调用方显式开启,原生坐标和字段校验仍是必要条件。 + assert result.status == 'confirmed' + assert result.issues == [] + + def test_multiline_stops_at_next_label_and_type_failure_requires_review(): """地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。""" address = _profile(layout={ @@ -478,6 +541,21 @@ def test_common_purchase_order_slash_date_is_normalized(): assert result.value.isoformat() == '2026-06-20' +def test_common_purchase_order_short_slash_date_is_normalized(): + """采购单常见两位年份日期应按冻结 date Schema 归一化。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'date', 'text': 'DATE'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema( + field_code='order_date', value_type='date', validator_keys=['iso_date'], + ), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/16/26', 20, 20))}))[0] + + # 关键断言:视觉样本的两位年份转换为统一 ISO 日期,而不是未读取。 + assert result.status == 'confirmed' + assert result.value.isoformat() == '2026-06-16' + + def test_date_does_not_extend_beyond_value_frame(): """值框边界是标注预览的唯一证据,日期也不得跨框补全。""" profile = _profile(layout={ @@ -547,6 +625,27 @@ def test_absolute_value_region_uses_canvas_boundary_instead_of_anchor_projection assert result.value == '66 Hou-Kang Street' +def test_absolute_single_line_value_region_moves_with_its_unique_anchor(): + """单头整体上移时,绝对客户值框必须跟随已唯一命中的自身标签。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'bill_to', 'text': 'BILL TO', + 'region': {'x0': .10, 'y0': .30, 'x1': .30, 'y1': .35}, + }, + 'absolute_value_region': {'x0': .10, 'y0': .38, 'x1': .90, 'y1': .44}, + 'value_mode': 'single_line', + }) + result = extract_order_fields( + profile=profile, schema_fields=_schema(field_code='bill_to_customer'), + coordinate_evidence=_evidence(pages={'1': _glyphs( + ('BILL TO', 20, 40), ('Hyve Solutions Corporation', 20, 56), ('44201 Nobel Drive', 20, 72), + )}), + )[0] + + assert result.status == 'confirmed' + assert result.value == 'Hyve Solutions Corporation' + + def test_tight_value_region_keeps_edge_glyphs_without_reading_adjacent_text(): """紧贴 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 ab1ddfa9..2dfd134a 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -155,6 +155,29 @@ def test_anchor_frame_matches_bounded_vertical_translation_without_changing_lega assert legacy_result.candidates[0].coordinate_transform is None +def test_legacy_profile_automatically_uses_unique_document_match_label_for_bounded_translation(): + """新管理台不配置坐标模型时,唯一的模板身份标签仍可自动校正小幅整体平移。""" + definition = _profile('PO_AUTO_FRAME')['definition'] + definition['document_match']['required_anchors'][0].update({ + 'label_region': {'x0': .05, 'y0': .02, 'x1': .265, 'y1': .10}, + 'value_region': {'x0': .42, 'y0': .02, 'x1': .85, 'y1': .10}, + }) + profile = OrderCoordinateProfile.model_validate(definition) + pages = {'1': {'width': 200, 'height': 280}} + glyphs = {'1': [ + {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 25.8, 'x1': 13 + index * 4, 'y1': 35.8}} + for index, char in enumerate('PLANT NAME:') + ]} + + transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs) + + assert reasons == [] + assert transform == { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.05, + 'anchor_ids': ['plant_name'], 'reason_codes': [], + } + + def test_affine_anchor_frame_requires_explicit_opt_in_and_three_stable_anchors(): """仿射只允许显式治理的多锚点 Profile 使用,默认平移模板不改变行为。""" definition = _anchor_frame_profile()['definition'] diff --git a/backend/tests/test_shipping_order_review_field_conflict.py b/backend/tests/test_shipping_order_review_field_conflict.py index d51a97e5..e94920cf 100644 --- a/backend/tests/test_shipping_order_review_field_conflict.py +++ b/backend/tests/test_shipping_order_review_field_conflict.py @@ -96,6 +96,35 @@ def test_project_review_case_field_conflicts_empty_without_candidate(): assert project_review_case_field_conflicts(case) == [] +def test_project_review_case_keeps_open_legacy_single_value_conflict_visible(monkeypatch): + """资格层仍阻断的遗留单值 Finding 不得被投影静默丢弃。""" + candidate = SimpleNamespace( + conflicts_json=[{ + 'conflict_key': '0:unit_price', + 'field': 'unit_price', + 'line_index': 0, + 'severity': 'blocking', + 'reason': 'field_conflict', + 'values': ['1731.60'], + }], + 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 + + monkeypatch.setattr(svc, '_candidate_for_case', lambda _case: candidate) + monkeypatch.setattr(svc, 'current_open_candidate_conflicts', lambda _candidate: list(candidate.conflicts_json)) + + items = project_review_case_field_conflicts(case) + + assert len(items) == 1 + assert items[0]['field_code'] == 'unit_price' + assert items[0]['conflict_key'] == '0:unit_price' + + @pytest.mark.pure_unit def test_project_review_case_field_conflicts_uses_complete_finding_source_evidence(): """正文补充真冲突必须直接展示 PDF/邮件值与来源,不能因缺 Observation 而消失。""" diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index c01a1ab5..452ce7b8 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -591,6 +591,42 @@ def test_reservation_summary_reads_machine_value_before_async_validation(): assert result['lines'][0]['effective_reservation_id'] == '33874' +def test_reservation_summary_does_not_leak_inventory_block_reason(): + """Reservation 面板不得展示同一明细的库存路由阻断原因。""" + case = SimpleNamespace( + run=SimpleNamespace(input_snapshot_json={ + 'schema': {'definition': {'fields': [{ + 'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', + }]}}}, + ), + current_draft=SimpleNamespace( + validation_result_json={ + 'status': 'needs_review', + 'line_projections': [{ + 'line_key': 'line-1', + 'effective_reservation_id': None, + 'can_build': False, + 'block_reason': 'no_inventory_source_candidates', + }], + 'issues': [{ + 'code': 'effective_reservation_missing', + 'line_index': 0, + 'owning_gate_code': 'reservation_validation', + 'severity': 'blocking', + }], + }, + lines_json=[], + ), + ) + + result = project_review_case_reservation(case) + + # 关键断言:库存路由码只能留在库存 Gate,Reservation 行应显示自身缺失原因。 + assert result['lines'][0]['block_reason'] == 'effective_reservation_missing' + assert result['lines'][0]['block_reason'] != 'no_inventory_source_candidates' + assert result['lines'][0]['needs_attention'] is True + + def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app): """同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。""" with app.app_context(): @@ -1026,11 +1062,20 @@ def test_review_read_api_returns_safe_owner_scoped_projection(app): token = issue_local_access_token(user) headers = {'Authorization': f'Bearer {token}'} run_response = client.get(f'/api/workspace/shipping-notice/order-extraction-runs/{run.run_no}/review', headers=headers) + queue_response = client.get(f'/api/workspace/shipping-notice/order-review-queue/{run.run_no}', headers=headers) case_response = client.get(f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', headers=headers) # 关键断言:列表和详情仅给 owner 返回 Case/Draft 安全投影,不输出原始文本或对象存储信息。 assert run_response.status_code == 200 + assert queue_response.status_code == 200 assert case_response.status_code == 200 + # 关键断言:慢切换读取必须返回查找/投影边界,供浏览器 HAR 精确定位,不泄露业务内容。 + assert 'review_lookup' in run_response.headers.get('Server-Timing', '') + assert 'review_projection' in run_response.headers.get('Server-Timing', '') + assert 'queue_lookup' in queue_response.headers.get('Server-Timing', '') + assert 'queue_projection' in queue_response.headers.get('Server-Timing', '') + assert 'case_lookup' in case_response.headers.get('Server-Timing', '') + assert 'case_projection' in case_response.headers.get('Server-Timing', '') assert case.case_no in str(run_response.get_json()) body = case_response.get_json() assert 'extracted_text' not in str(body) diff --git a/backend/tests/test_shipping_order_task_progress_audit.py b/backend/tests/test_shipping_order_task_progress_audit.py index 587056b6..9e379e5e 100644 --- a/backend/tests/test_shipping_order_task_progress_audit.py +++ b/backend/tests/test_shipping_order_task_progress_audit.py @@ -19,11 +19,13 @@ from app.services.shipping_notice.progress_audit_contract import ( def test_order_task_progress_audit_event_types_frozen(): - """契约冻结:OT 进度三类事件码齐全。""" + """契约冻结:OT 进度及投影一致性事件码齐全。""" assert ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES == frozenset({ 'order_task_created', 'order_task_updated', 'order_task_progress_changed', + 'shipping_processing_projection_inconsistent', + 'shipping_processing_task_ownership_mismatch', }) @@ -114,3 +116,29 @@ def test_sync_order_task_processing_state_noop_skips_audit(app): ).count() assert after_count == before_count assert int(ot.progress_version or 1) == version + + +def test_sync_order_task_processing_state_can_bump_for_review_projection(app): + """Review Gate 变化即使不改 stage/status,也必须推进 Projection 版本。""" + with app.app_context(): + ot = _seed_user_and_task('OT-PROGRESS-AUDIT-3') + version = int(ot.progress_version or 1) + sync_order_task_processing_state( + ot, + force_progress_bump=True, + reason_code='review_gate_changed', + source='test_review_projection', + ) + db.session.commit() + + assert int(ot.progress_version or 1) == version + 1 + event = ( + ShippingAuditEvent.query.filter_by( + event_type='order_task_progress_changed', + aggregate_id=ot.task_no, + ) + .order_by(ShippingAuditEvent.id.desc()) + .first() + ) + assert event is not None + assert event.reason_code == 'review_gate_changed' diff --git a/backend/tests/test_shipping_order_task_status_consistency.py b/backend/tests/test_shipping_order_task_status_consistency.py index 79816896..dbc0c086 100644 --- a/backend/tests/test_shipping_order_task_status_consistency.py +++ b/backend/tests/test_shipping_order_task_status_consistency.py @@ -186,7 +186,7 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): notice_before = ShippingNotice.query.count() with patch( - 'app.services.shipping_notice.order_review_confirmation_service.resolve_shipping_case_for_new_task', + 'app.services.shipping_notice.order_task_service.link_notice_to_order_task', side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'), ): with pytest.raises(ConflictError) as exc_info: diff --git a/backend/tests/test_shipping_pdf_automark.py b/backend/tests/test_shipping_pdf_automark.py index 72613973..44b88cf0 100644 --- a/backend/tests/test_shipping_pdf_automark.py +++ b/backend/tests/test_shipping_pdf_automark.py @@ -601,6 +601,33 @@ def test_automark_exposes_acroform_widget_as_independent_visual_candidate(): assert 'value_binding' not in widget_candidate['binding'] +def test_automark_merges_same_field_same_geometry_sources(): + """关键断言:同字段同页同坐标的 PDF 与 Widget 候选只生成一个画布框。""" + from app.services.shipping_notice import order_document_profile_pdf_automark_service as service + + candidates = [ + { + 'candidate_id': 'pdf-1', 'candidate_kind': 'field_binding', + 'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': { + 'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4}, + }}, + 'evidence_sources': ['pdf_coordinate'], 'needs_review': True, + }, + { + 'candidate_id': 'widget-1', 'candidate_kind': 'field_binding', + 'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': { + 'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4}, + }}, + 'evidence_sources': ['acroform_widget'], 'needs_review': True, + }, + ] + + merged = service._merge_duplicate_field_binding_candidates(candidates) + + assert len(merged) == 1 + assert merged[0]['evidence_sources'] == ['pdf_coordinate', 'acroform_widget'] + + def test_automark_keeps_unmatched_acroform_widget_as_unbound_visual_candidate(monkeypatch): """Widget 技术名未匹配 Schema 时仍可供人工框选,禁止自动猜业务字段。""" from app.services.shipping_notice import order_document_profile_pdf_automark_service as service @@ -727,7 +754,11 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text(): coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []} widget_geometry = { 'table_region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .8}, - 'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .25, 1]}], + # 动态 XFA 的表头控件有展示值时,Widget 聚类会把表头带误判为候选行。 + 'subrow_layouts': [{ + 'row_offset': 0, 'column_boundaries': [0, .25, 1], + 'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2}, + }], 'header_regions': [], 'status': 'needs_review', } with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch( @@ -751,6 +782,8 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text(): assert field['field_code'] == 'line_no' assert field['region'] == {'x0': .1, 'y0': .15, 'x1': .3, 'y1': .2} assert field['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate'] + # 已确认的表头带不得同时作为可保存的 Widget 明细行。 + assert widget_candidate['payload']['subrow_layouts'] == [] def test_automark_marks_opencv_and_native_structure_conflict_for_review(): diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py index ccf2b1d3..30b4d005 100644 --- a/backend/tests/test_shipping_process_gate_contract.py +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -82,6 +82,16 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate(): ) is True +def test_inventory_preparation_allows_reload_existing_result_without_rpa(): + """RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。""" + assert action_belongs_to_gate( + gate_code='inventory_preparation', action_code='reload_inventory_result', + ) is True + assert action_belongs_to_gate( + gate_code='inventory_matching', action_code='reload_inventory_result', + ) is False + + def test_inventory_sufficiency_actions_keep_business_specific_labels(): """库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。""" assert action_presentation('open_shortage_review') == { @@ -140,7 +150,7 @@ def test_gate_action_presentation_declares_ui_dispatch_without_frontend_action_c 'label_key': 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded', 'kind': 'current_gate', 'dispatch': 'dialog', - 'ui_handler': 'manual_upload_evidence', + 'ui_handler': 'manual_upload_confirmation', } assert action_presentation('confirm_customer') == { 'code': 'confirm_customer', @@ -433,6 +443,43 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch): assert summary['allowed_actions'] == ['retry_inventory_preparation'] +def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch): + """RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-INVENTORY-TIMEOUT', status='blocked', + current_gate_code='inventory_preparation', + primary_next_action_code='retry_inventory_preparation', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=99, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-INVENTORY-TIMEOUT', 'status': 'blocked', + 'primary_next_action_code': 'retry_inventory_preparation', + 'responsible_party': 'worker', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + 'current_gate': { + 'gate_code': 'inventory_preparation', 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_rpa_timeout', + 'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 3, + }, + }, + ) + + summary = projection.project_user_gate_summary(execution) + + assert summary['next_action_code'] == 'reload_inventory_result' + assert summary['primary_action']['code'] == 'reload_inventory_result' + assert summary['allowed_actions'] == [ + 'reload_inventory_result', + 'retry_inventory_preparation', + ] + + def test_user_gate_summary_exposes_manual_gate_evidence_and_rpa_retry(app, monkeypatch): """Gate 20 保持凭据登记主动作,并显式下发可选 RPA 重试。""" from types import SimpleNamespace @@ -507,8 +554,8 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action( assert summary['primary_action']['target_anchor'] == 'manual_upload' -def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, monkeypatch): - """跨 Gate Excel 恢复必须采用 RecoveryPlan 的位置,不能继承 Gate 20 的上传位置。""" +def test_manual_upload_handoff_hides_excel_regeneration_for_single_notice(app, monkeypatch): + """同一 Notice 只能有一个 Excel,上传阶段不得投影重生入口。""" from types import SimpleNamespace from app.services.shipping_notice import process_gate_projection as projection @@ -533,16 +580,10 @@ def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, m }, }, ) - monkeypatch.setattr(projection, '_excel_regeneration_allowed', lambda **_: True) - summary = projection.project_user_gate_summary(execution) - regeneration = next( - item for item in summary['action_presentation'] - if item['code'] == 'regenerate_excel_artifact' - ) - assert regeneration['target_surface'] == 'fulfillment_prep' - assert regeneration['target_anchor'] == 'excel_artifact' + assert 'regenerate_excel_artifact' not in summary['allowed_actions'] + assert all(item['code'] != 'regenerate_excel_artifact' for item in summary['action_presentation']) def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, monkeypatch): diff --git a/backend/tests/test_shipping_process_gate_recovery_action_contract.py b/backend/tests/test_shipping_process_gate_recovery_action_contract.py index 9a00ee8f..7f7dc663 100644 --- a/backend/tests/test_shipping_process_gate_recovery_action_contract.py +++ b/backend/tests/test_shipping_process_gate_recovery_action_contract.py @@ -1,10 +1,9 @@ """ tests/test_shipping_process_gate_recovery_action_contract.py -用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 失败统一下发 -「重新获取库存」(retry_inventory_preparation),不再因 inventory_preparation -Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽」规则 -降级为人工上传入口 (upload_inventory_file)。 +用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 超时/耗尽优先下发 +「重新读取库存结果」(reload_inventory_result),其他失败下发「重新获取库存」 +(retry_inventory_preparation),不再被历史 worker 技术动作屏蔽规则降级为人工上传入口。 依赖:process_gate_projection._resolve_recovery_next_action。 逻辑:pure_unit 纯单测(不建 Flask/DB);以阻断原因码 / Gate 状态为输入, @@ -59,12 +58,10 @@ def test_inventory_file_empty_blocked_manual_resolves_to_retry(): @pytest.mark.parametrize('reason', [ 'inventory_file_empty', 'inventory_preparation_failed', - 'inventory_rpa_timeout', 'inventory_rpa_login_failed', 'inventory_rpa_export_failed', 'inventory_file_identity_mismatch', 'inventory_file_missing', - 'inventory_rpa_exhausted', ]) def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason): """全部库存 RPA 失败原因(无论 blocked_manual / blocked_retryable)均下发「重新获取库存」。""" @@ -79,14 +76,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason): @pytest.mark.pure_unit -def test_inventory_rpa_exhausted_falls_back_to_manual_upload(): - """历史耗尽码仍允许用户手动重新获取库存。""" +@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted']) +def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason): + """超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。""" full, blocking = _mk( {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', - 'blocking_reason_code': 'inventory_rpa_exhausted'}, + 'blocking_reason_code': reason}, ) action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None) - assert action == 'retry_inventory_preparation' + assert action == 'reload_inventory_result' @pytest.mark.pure_unit @@ -225,6 +223,84 @@ def test_inventory_preparation_waiting_keeps_refresh_action(): assert action == 'poll_inventory_preparation' +def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch): + """重新读取库存结果只复用快照,不能触发新的库存 RPA。""" + from app.models import ShippingNotice + from app.services.shipping_notice import process_gate_executor as executor + + task = SimpleNamespace(task_no='SN-RELOAD-1') + execution = SimpleNamespace(task_id=7) + calls: list[tuple[str, object]] = [] + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', + lambda _task: {'source_code': 'DSV360_AWSDU'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot', + lambda received_task, source, *, mode: calls.append((mode, (received_task, source))) or {'status': 'ok'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa', + lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_rpa_timeout', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_kwargs: calls.append(('sync', _kwargs)), + ) + + with app.app_context(): + outcome = executor._handle_reload_inventory_result( + execution=execution, + gate=SimpleNamespace(gate_code='inventory_preparation'), + payload={'actor_user_id': 3}, + ) + + assert outcome['outcome'] == 'passed' + assert calls[0][0] == 'reload_result' + assert calls[1][0] == 'sync' + + +def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch): + """无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。""" + from app.models import ShippingNotice + from app.services.shipping_notice import process_gate_executor as executor + + task = SimpleNamespace(task_no='SN-RELOAD-MISSING') + execution = SimpleNamespace(task_id=7) + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', + lambda _task: {'source_code': 'DSV360_AWSDU'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot', + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa', + lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code', + lambda _task: 'inventory_rpa_timeout', + ) + + with app.app_context(): + outcome = executor._handle_reload_inventory_result( + execution=execution, + gate=SimpleNamespace(gate_code='inventory_preparation'), + payload={}, + ) + + assert outcome['outcome'] == 'blocked_retryable' + assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout' + + @pytest.mark.pure_unit def test_no_blocking_returns_no_action(): """无当前阻断时不下发给任何主恢复动作。""" diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 6cbbc911..d2481cf2 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -1082,71 +1082,48 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan(): assert plan.completed_at is not None -def test_excel_regeneration_completion_preserves_manual_upload_gate(): - """跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。""" - from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt - - class Plan: - status = 'queued' - action_code = 'regenerate_excel_artifact' - resume_after_gate = 'manual_upload_handoff' - started_at = None - completed_at = None - failure_code = None - failure_detail_json = None - - plan = Plan() - complete_recovery_plan_for_attempt( - plan=plan, - outcome='blocked_manual', - business_result_code='manual_upload_pending', - ) - - assert plan.status == 'succeeded' - assert plan.completed_at is not None - - -def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch): - """Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。""" +def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch): + """已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。""" from types import SimpleNamespace + from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel - invalidated = {} + task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL') + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) monkeypatch.setattr( - 'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only', - lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]}, + ShippingExportArtifact, + 'query', + SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))), ) monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.generate_excel', - lambda _payload: {'status': 'ok'}, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', - lambda **_: None, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.process_gate_executor._task_payload', - lambda _execution, _payload: {'_orchestrator_internal_dispatch': True}, + lambda _payload: pytest.fail('existing Artifact must not be regenerated'), ) outcome = _handle_regenerate_excel( execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1), gate=SimpleNamespace(gate_code='manual_upload_handoff'), - payload={'attempt_id': 3, 'actor_user_id': 9}, + payload={'actor_user_id': 9}, ) - assert invalidated['attempt_id'] == 3 assert outcome['outcome'] == 'blocked_manual' - assert outcome['blocking_reason_code'] == 'manual_upload_pending' - assert outcome['output_snapshot']['invalidation']['artifacts'] == [10] + assert outcome['blocking_reason_code'] == 'notice_excel_already_generated' def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch): """Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。""" from types import SimpleNamespace + from app.models import ShippingExportArtifact, ShippingNotice from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel synced = [] + task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL') + monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr( + ShippingExportArtifact, + 'query', + SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: None)), + ) monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.generate_excel', lambda _payload: {'status': 'failed', 'message': 'template unavailable'}, diff --git a/backend/tests/test_shipping_review_line_fulfillment_decision.py b/backend/tests/test_shipping_review_line_fulfillment_decision.py index 6891dae9..c6fa734e 100644 --- a/backend/tests/test_shipping_review_line_fulfillment_decision.py +++ b/backend/tests/test_shipping_review_line_fulfillment_decision.py @@ -202,17 +202,18 @@ def test_shortage_release_keeps_first_export_line_override(): ) == {0: {'6': 'ODM-001'}} -def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_inventory_fact(app, monkeypatch): - """短缺放行重投影后必须入队 Excel 产物 Gate,且不得改写库存缺口事实。""" +def test_shortage_release_syncs_gate_and_enqueues_auto_fulfill_without_mutating_inventory_fact(app, monkeypatch): + """短缺放行只同步 Gate,并由 Worker 决定是否创建单条 Notice/Excel。""" from types import SimpleNamespace from app.services.shipping_notice import order_review_fulfillment_decision_service as svc - task = SimpleNamespace(id=12, active_process_execution_id=34) + task = SimpleNamespace(id=12, task_no='SN-12', active_process_execution_id=34) case = SimpleNamespace(confirmed_task_id=12) execution = SimpleNamespace(id=34, task_id=12) synced = [] queued = [] + auto_fulfill_jobs = [] monkeypatch.setattr(svc.db.session, 'get', lambda model, key: task if key == 12 else execution) monkeypatch.setattr( 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', @@ -222,6 +223,10 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_ 'app.services.shipping_notice.auto_progress_controller.submit_auto_progress', lambda **kwargs: queued.append(kwargs), ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job', + lambda **kwargs: auto_fulfill_jobs.append(kwargs), + ) with app.app_context(): _sync_confirmed_task_fulfillment_gates(case=case, actor_id=7) @@ -233,6 +238,11 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_ 'operator_id': 7, 'commit': False, }] + assert auto_fulfill_jobs == [{ + 'task_no': 'SN-12', + 'trigger': 'inventory_shortage_released', + 'commit': False, + }] def test_shortage_release_rejects_missing_template_inventory_override(): diff --git a/backend/tests/test_shipping_review_wave_line_concurrency.py b/backend/tests/test_shipping_review_wave_line_concurrency.py index 1bb96764..4d0dc002 100644 --- a/backend/tests/test_shipping_review_wave_line_concurrency.py +++ b/backend/tests/test_shipping_review_wave_line_concurrency.py @@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ') @@ -46,19 +45,19 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): ensure_order_extraction_plan(run) db.session.commit() unit = run.extraction_plan.units[0] + unit.status = 'candidate_ready' unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]} db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() - shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id)) task1 = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), + task_no=generate_task_no(), user_id=int(user.id), source_type='review_confirmation', source_file_name=document.filename, source_content_hash=document.content_hash, ) task2 = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), + task_no=generate_task_no(), user_id=int(user.id), source_type='review_confirmation', source_file_name=document.filename, source_content_hash=document.content_hash, ) @@ -93,7 +92,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE') @@ -103,17 +101,17 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): ensure_order_extraction_plan(run) db.session.commit() unit = run.extraction_plan.units[0] + unit.status = 'candidate_ready' unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]} db.session.commit() case = ensure_run_review_cases(run=run)[0] db.session.commit() case_id = int(case.id) - shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id)) tasks = [] for _ in range(2): task = ShippingNotice( - task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), + task_no=generate_task_no(), user_id=int(user.id), source_type='review_confirmation', source_file_name=document.filename, source_content_hash=document.content_hash, ) diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index 1c1770b5..90607427 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -106,6 +106,30 @@ def test_completed_checks_include_formal_ot_milestone(): assert 'order_review_completed' in codes +def test_completed_checks_do_not_mark_open_legacy_conflict_as_resolved(): + """遗留阻断 Finding 已投影为开放冲突时,不得再显示冲突已解决。""" + checks = project_completed_checks( + case=SimpleNamespace(updated_at=None), + process_gate={ + 'gates_track': [ + {'gate_code': 'field_conflict_resolution', 'status': 'passed'}, + ], + }, + customer_resolution=None, + duplicate=None, + field_conflicts=[{ + 'conflict_key': '0:unit_price', + 'field_code': 'unit_price', + 'status': 'open', + }], + field_completeness=None, + profile_match=None, + formal_ot={'has_formal_ot': False}, + ) + + assert 'field_conflicts_resolved' not in {item['code'] for item in checks} + + def test_post_ot_clears_pre_ot_blocking_gate(): """正式 OT 后建单前 Gate 不得成为当前阻断。""" summary = apply_post_ot_gate_rules( @@ -235,6 +259,7 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating(): current_step=None, stage_nodes_json=None, step_payload_json=None, + upload_status=None, ) stage = project_stage_for_task(task) assert stage['code'] == 'order_creating' diff --git a/backend/tests/test_shipping_rolling_fulfillment.py b/backend/tests/test_shipping_rolling_fulfillment.py index 46840be0..2d1251db 100644 --- a/backend/tests/test_shipping_rolling_fulfillment.py +++ b/backend/tests/test_shipping_rolling_fulfillment.py @@ -26,6 +26,7 @@ from app.services.shipping_notice.reservation_service import ( ensure_task_reservations, record_inventory_verification, ) +from app.services.shipping_notice.fulfillment_workflow import excel_gate_error from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot @@ -77,6 +78,53 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app): assert line_ids == {released_line.id} +def test_partial_inventory_allows_excel_for_the_available_lines(app): + """关键断言:部分短缺不阻断已完整满足行的滚动 Excel 导出资格。""" + with app.app_context(): + task, user = _build_accepted_order(suffix='partial-excel-gate') + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + available_line = snapshot.lines[0] + shortage_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + qty=Decimal('3'), field_values_json={}, + ) + snapshot.lines.append(shortage_line) + db.session.flush() + record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[ + {'reservation_id': available_line.reservation_id, 'part_number': available_line.part_number, 'required_qty': available_line.qty, 'available_qty': available_line.qty, 'line_status': 'ok'}, + {'reservation_id': shortage_line.reservation_id, 'part_number': shortage_line.part_number, 'required_qty': shortage_line.qty, 'available_qty': '0', 'line_status': 'shortage'}, + ]) + + assert excel_gate_error(task) is None + + +def test_selected_notice_only_returns_its_frozen_lines(app): + """独立发货通知只能取得用户选择的满足行,不能捎带同 PO 其他可用行。""" + with app.app_context(): + task, user = _build_accepted_order(suffix='selected-notice-lines') + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + first_line = snapshot.lines[0] + second_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681', + qty=Decimal('3'), field_values_json={}, + ) + snapshot.lines.append(second_line) + db.session.flush() + record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[ + {'reservation_id': first_line.reservation_id, 'part_number': first_line.part_number, 'required_qty': first_line.qty, 'available_qty': first_line.qty, 'line_status': 'ok'}, + {'reservation_id': second_line.reservation_id, 'part_number': second_line.part_number, 'required_qty': second_line.qty, 'available_qty': second_line.qty, 'line_status': 'ok'}, + ]) + + _verification, line_ids = current_available_snapshot_line_ids( + task, + selected_snapshot_line_ids={first_line.id}, + ) + + assert line_ids == {first_line.id} + + + + def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app): """关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。""" with app.app_context(): diff --git a/backend/tests/test_shipping_runtime_parse_strategy.py b/backend/tests/test_shipping_runtime_parse_strategy.py new file mode 100644 index 00000000..c573bf60 --- /dev/null +++ b/backend/tests/test_shipping_runtime_parse_strategy.py @@ -0,0 +1,165 @@ +"""验证订单模板运行时策略仅基于当前文档证据作出可审计的受控选择。""" + +from app.services.shipping_notice.document_layout.runtime_parse_strategy import ( + resolve_runtime_parse_strategy, + select_runtime_region_ids, +) + + +def _row(*, line_no: str, part_no: str, issues: list[str] | None = None) -> dict: + """构造最小重建行,关键料号与项次用于验证策略不得静默改写业务结果。""" + return { + 'status': 'parsed' if not issues else 'needs_review', + 'issues': issues or [], + 'fields': [ + {'field_code': 'customer_po_line_no', 'value': line_no}, + {'field_code': 'part_number', 'value': part_no}, + ], + } + + +def test_runtime_strategy_uses_every_page_with_coordinate_evidence(): + """模板画在首页时,运行时仍须计划检查所有有页级坐标的页面以避免静默漏续页。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}], '2': [{}], '3': []}, + fixed_rows=[], adaptive_rows=[], + ) + + # 页面计划仍完整保留;没有任何可用明细行时整体必须 Review,不能伪造成功。 + assert result.status == 'needs_review' + assert result.page_nos == (1, 2) + + +def test_runtime_strategy_selects_adaptive_only_when_fixed_has_no_valid_rows(): + """固定子行无有效行而自适应能完整重建时,系统才自动切换而非要求人工猜策略。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='10', part_no='PART-A', issues=['row_incomplete'])], + adaptive_rows=[_row(line_no='10', part_no='PART-A')], + ) + + assert result.status == 'selected' + assert result.row_mode == 'adaptive_record_columns' + assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',) + + +def test_runtime_strategy_selects_dynamic_x_columns_when_existing_modes_have_no_valid_rows(): + """固定与自适应均无行时,才允许使用同一 Schema 校验过的动态 Y 候选。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[], adaptive_rows=[], + dynamic_rows=[_row(line_no='10', part_no='PART-A')], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + +def test_runtime_strategy_requires_review_when_dynamic_conflicts_with_existing_valid_row(): + """动态结果与既有有效行冲突时不得静默保留旧模式,必须进入 Review。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='10', part_no='PART-A')], adaptive_rows=[], + dynamic_rows=[_row(line_no='10', part_no='PART-B')], + ) + + assert result.status == 'needs_review' + assert result.row_mode is None + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_selects_dynamic_when_it_safely_covers_more_valid_records(): + """动态候选完整覆盖旧模式且额外恢复有效起行记录时,才能取代不完整结果。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='20', part_no='PART-B')], adaptive_rows=[], + dynamic_rows=[ + _row(line_no='10', part_no='PART-A'), + _row(line_no='20', part_no='PART-B'), + ], + ) + + assert result.status == 'selected' + assert result.row_mode == 'dynamic_x_columns' + assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',) + + +def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_business_rows(): + """两种有效重建结果的关键项次或料号不一致时不得按分数强选,必须转既有 Review。""" + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, + fixed_rows=[_row(line_no='10', part_no='PART-A')], + adaptive_rows=[_row(line_no='10', part_no='PART-B')], + ) + + assert result.status == 'needs_review' + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value(): + """同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。""" + fixed = _row(line_no='10', part_no='PART-A') + fixed['fields'].append({'field_code': 'quantity', 'value': '12'}) + adaptive = _row(line_no='10', part_no='PART-A') + adaptive['fields'].append({'field_code': 'quantity', 'value': '10'}) + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive], + ) + + assert result.status == 'needs_review' + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_prefers_complete_fixed_rows_when_overlap_matches(): + """固定模式多识别一个字段时不得把同一条明细误判为策略冲突。""" + fixed = _row(line_no='10', part_no='PART-A') + fixed['fields'].append({'field_code': 'uom', 'value': 'EA'}) + adaptive = _row(line_no='10', part_no='PART-A') + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive], + ) + + assert result.status == 'selected' + assert result.row_mode == 'fixed_subrows' + + +def test_runtime_strategy_still_reviews_when_field_values_conflict(): + """字段值冲突仍必须进入 Review,不能用字段数量掩盖识别差异。""" + fixed = _row(line_no='10', part_no='PART-A') + fixed['fields'].append({'field_code': 'uom', 'value': 'EA'}) + adaptive = _row(line_no='10', part_no='PART-A') + adaptive['fields'].append({'field_code': 'uom', 'value': 'PCS'}) + + result = resolve_runtime_parse_strategy( + page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive], + ) + + assert result.status == 'needs_review' + assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',) + + +def test_runtime_strategy_reuses_base_region_on_continuation_page_without_duplicate_page_regions(): + """标注页只用于定位同页表区;没有专属标注的续页复用基础表区,不能重复消费其他页布局。""" + regions = [ + {'region_id': 'page_one', 'page_scope': 'exact_page', 'page_no': 1}, + {'region_id': 'page_two', 'page_scope': 'exact_page', 'page_no': 2}, + ] + + assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',) + assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('page_two',) + assert select_runtime_region_ids(table_regions=regions, page_no=3) == ('page_one',) + + +def test_runtime_region_selection_prefers_legacy_continuation_region_before_base_region(): + """已发布模板的续页专属框仍优先于首页基准框,避免升级后错用另一种行布局。""" + regions = [ + {'region_id': 'page_one', 'page_scope': 'first_page'}, + {'region_id': 'continuation', 'page_scope': 'continuation_pages'}, + {'region_id': 'all_pages', 'page_scope': 'all_pages'}, + ] + + assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',) + assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('continuation',) diff --git a/backend/tests/test_shipping_task_disposition.py b/backend/tests/test_shipping_task_disposition.py index 1f65b2ab..45d19ad6 100644 --- a/backend/tests/test_shipping_task_disposition.py +++ b/backend/tests/test_shipping_task_disposition.py @@ -4,7 +4,6 @@ from app import db from app.core.errors import ConflictError from app.models import ( ShippingAuditEvent, - ShippingCase, ShippingNotice, ShippingTaskEvent, ShippingTaskPurgeAudit, @@ -62,11 +61,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app): def test_internal_business_task_is_voided_before_recycle_bin(app): """已有业务单的任务不能伪装为纯删除,必须留下作废事实和原因。""" with app.app_context(): - case = ShippingCase(case_no='SC-DISPOSITION-001') - task = _task('SN-DISPOSITION-VOID-001') - db.session.add_all([case, task]) - db.session.flush() - task.shipping_case_id = case.id + task = _task('SN-DISPOSITION-VOID-001', business_no='SN260823001') + db.session.add(task) db.session.commit() outcome = move_task_to_recycle_bin(task, actor_id=1, reason='重复建单') @@ -210,11 +206,9 @@ def test_workspace_voided_filter_includes_voided_recycle_bin_task(app, client): """已作废视图必须可审计“作废并删除”的任务,不能被 deleted_at 条件意外排除。""" headers, user_id = _headers_for_user(app, 'disposition-voided-list') with app.app_context(): - case = ShippingCase(case_no='SC-DISPOSITION-LIST-VOIDED') - task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id) - db.session.add_all([case, task]) + task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id, business_no='SN260823002') + db.session.add(task) db.session.flush() - task.shipping_case_id = case.id move_task_to_recycle_bin(task, actor_id=user_id, reason='测试作废') db.session.commit() @@ -254,11 +248,8 @@ def test_admin_can_purge_only_pure_deleted_task_and_audit_is_retained(app, clien def test_purge_blocks_task_with_business_reference(app): """已有业务单的回收站任务即使被手工篡改为 active,也必须阻断永久删除。""" with app.app_context(): - case = ShippingCase(case_no='SC-DISPOSITION-PURGE-BLOCK') - task = _task('SN-DISPOSITION-PURGE-BLOCK') - db.session.add_all([case, task]) - db.session.flush() - task.shipping_case_id = case.id + task = _task('SN-DISPOSITION-PURGE-BLOCK', business_no='SN260823003') + db.session.add(task) task.deleted_at = __import__('datetime').datetime.utcnow() db.session.commit() diff --git a/backend/tests/test_shipping_task_supersession.py b/backend/tests/test_shipping_task_supersession.py index 4ac92d72..ae3438db 100644 --- a/backend/tests/test_shipping_task_supersession.py +++ b/backend/tests/test_shipping_task_supersession.py @@ -30,8 +30,8 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app): assert new.lifecycle_status == 'active' -def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(app): - """关键断言:已上传旧版必须先有撤销回执,后继版才恢复活动状态。""" +def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app): + """关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。""" with app.app_context(): old, new, user = _tasks(uploaded=True) establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend') @@ -39,7 +39,11 @@ def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(a assert new.lifecycle_status == 'blocked' with pytest.raises(ConflictError): assert_task_not_supersession_blocked(new) - complete_freight_cancellation(cancellation_id=row.id, actor_id=user.id, freight_receipt_no='CANCEL-1', receipt_asset_id=1) + complete_freight_cancellation( + cancellation_id=row.id, + actor_id=user.id, + note='已在货代平台确认撤销', + ) assert row.status == 'cancelled' assert old.lifecycle_status == 'voided' assert new.lifecycle_status == 'active' diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index c3efd246..95a495fd 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -18,9 +18,10 @@ from app.models import ( ShippingUploadAttempt, ) from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success +from app.services.shipping_notice.export import assert_notice_has_no_export_artifact from app.services.shipping_notice.upload_attempt_service import ( complete_attempt, has_verified_upload_success, mark_attempt_result_unknown, - start_rpa_attempt, void_rejected_artifact, + record_manual_upload, start_rpa_attempt, void_rejected_artifact, ) from app.services.shipping_notice.state_machine import resolve_task_ui_state @@ -73,6 +74,108 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app): start_rpa_attempt(task, artifact_id=artifact.id) +def test_notice_with_existing_excel_cannot_generate_another_artifact(app): + """一个发货通知单已有 Excel 后必须创建新 Notice,不能追加第二个 Artifact。""" + with app.app_context(): + task, _artifact, _reservation = _ready_artifact() + + with pytest.raises(ConflictError) as exc_info: + assert_notice_has_no_export_artifact(task) + + assert exc_info.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED' + + +def test_batch_notice_confirmation_isolates_each_business_number(app, monkeypatch): + """批量通知单确认中一张被阻断时,其他通知单仍独立提交成功。""" + from types import SimpleNamespace + + from app.api.workspace import shipping_notice as api + + with app.app_context(), app.test_request_context( + '/api/workspace/shipping-notices/batch/confirm-uploaded', + method='POST', + json={'business_nos': ['WVC26082301', 'WVC26082302']}, + ): + commits: list[str] = [] + monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7)) + monkeypatch.setattr( + api, + '_confirm_notice_uploaded', + lambda *, business_no, user_id: ( + {'status': 'ok'} if business_no.endswith('01') + else (_ for _ in ()).throw(ConflictError('already uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')) + ), + ) + monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit')) + monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback')) + + response = api.workspace_batch_confirm_shipping_notices_uploaded() + body = response[0].get_json()['data'] + + assert [item['status'] for item in body['results']] == ['confirmed', 'blocked'] + assert commits == ['commit', 'rollback'] + + +def test_business_no_rpa_batch_isolates_each_notice(app, monkeypatch): + """批量 RPA 必须只接受 business_no,并让已受理通知独立提交。""" + from types import SimpleNamespace + + from app.api.workspace import shipping_notice as api + + with app.app_context(), app.test_request_context( + '/api/workspace/shipping-notices/batch/rpa-upload', + method='POST', + json={'business_nos': ['WVC26082301', 'WVC26082302']}, + ): + commits: list[str] = [] + monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7)) + monkeypatch.setattr( + api, + '_start_notice_rpa_upload', + lambda *, business_no, user_id: ( + {'status': 'running'} if business_no.endswith('01') + else (_ for _ in ()).throw(ConflictError('unknown result', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN')) + ), + ) + monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit')) + monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback')) + + response = api.workspace_batch_start_shipping_notice_rpa_upload() + body = response[0].get_json()['data'] + + assert [item['status'] for item in body['results']] == ['accepted', 'blocked'] + assert [item['business_no'] for item in body['results']] == ['WVC26082301', 'WVC26082302'] + assert commits == ['commit', 'rollback'] + + +def test_business_no_loader_rejects_task_no_alias(app, monkeypatch): + """新货代入口不得把内部 task_no 或旧 Case 编号当作 business_no 接收。""" + from app.api.workspace import shipping_notice as api + + with app.app_context(), app.test_request_context('/api/workspace/shipping-notices/SN-1/export'): + task = ShippingNotice(task_no='SN-1', business_no='WVC26082301', user_id=7) + monkeypatch.setattr(api, 'get_task_for_user', lambda reference, user_id: task) + + with pytest.raises(Exception) as exc_info: + api._load_business_notice_for_user(business_no='SN-1', user_id=7) + + assert getattr(exc_info.value, 'code', None) == 'RESOURCE.NOT_FOUND' + + +def test_upload_success_updates_only_its_notice(app): + """一张独立 Notice 上传成功只终态化其自身,不影响同 PO 的其他 Notice。""" + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + other = ShippingNotice(task_no='TASK-UPLOAD-OTHER', order_task_id=task.order_task_id) + db.session.add(other); db.session.flush() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + + complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2') + + assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded' + assert db.session.get(ShippingNotice, other.id).upload_status is None + + def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): """历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。""" with app.app_context(): @@ -105,6 +208,24 @@ def test_failed_attempt_does_not_complete_reservation(app): assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready' +def test_manual_upload_confirmation_requires_no_receipt_or_file_evidence(app): + """人工确认只记录操作者和目标 Excel,不要求货代回执或截图/PDF。""" + with app.app_context(): + task, artifact, reservation = _ready_artifact() + + attempt = record_manual_upload( + task, + artifact_id=artifact.id, + operator_id=7, + ) + + assert attempt.mode == 'manual' + assert attempt.evidence_asset_id is None + assert attempt.freight_ref_no is None + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' + + def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app): """共享目录投递失败要落为失败 Attempt,不能遗留 uploading Artifact 阻断下一轮。""" with app.app_context(): @@ -200,7 +321,7 @@ def test_upload_callback_success_parsing_does_not_treat_false_text_as_success(): def test_rpa_report_upload_success_without_evidence_rejected(app): - """success=True 但缺少 success_evidence 时必须 fail-closed 拒绝。""" + """RPA success=True 但缺少受信 Worker 证据时必须 fail-closed 拒绝。""" with app.app_context(): from unittest.mock import patch @@ -224,7 +345,7 @@ def test_rpa_report_upload_success_without_evidence_rejected(app): def test_rpa_report_upload_success_without_reference_allowed(app): - """DSV 绿 DOM 成功时 reference 可为空;须带 success_evidence.kind 且证据资产落库。""" + """DSV 受信成功证据可不带 reference,并持久化内部审计资产。""" with app.app_context(): from unittest.mock import patch @@ -259,13 +380,9 @@ def test_rpa_report_upload_success_without_reference_allowed(app): 'observed_at': '2026-08-05T03:00:00Z', 'page_url': 'https://dsv.example/history', 'dom_snippet': '', - 'dom_sha256': ( - __import__('hashlib') - .sha256( - b'' - ) - .hexdigest() - ), + 'dom_sha256': __import__('hashlib').sha256( + b'' + ).hexdigest(), }, }) assert result['status'] == 'ok' @@ -273,13 +390,12 @@ def test_rpa_report_upload_success_without_reference_allowed(app): refreshed = db.session.get(ShippingUploadAttempt, attempt.id) assert refreshed is not None evidence = refreshed.success_evidence_json or {} - assert evidence.get('dom_sha256') assert evidence.get('page_url') assert refreshed.evidence_asset_id == 4242 -def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app): - """DOM 校验通过但证据资产落库失败时,不得标记上传成功。""" +def test_rpa_report_upload_success_requires_internal_audit_asset(app): + """自动 RPA 成功仍保存内部审计资产;人工确认路径不受此规则影响。""" with app.app_context(): from unittest.mock import patch @@ -288,12 +404,16 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app): task, artifact, reservation = _ready_artifact() attempt = start_rpa_attempt(task, artifact_id=artifact.id) db.session.commit() + def _persist(*, task, attempt, success_evidence): + attempt.evidence_asset_id = 4242 + return 4242 + with patch( 'app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response', return_value=None, ), patch( 'app.services.shipping_notice.fulfillment_workflow._persist_rpa_success_evidence_asset', - return_value=None, + side_effect=_persist, ): result = rpa_report_upload({ 'task_id': task.task_no, @@ -310,60 +430,43 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app): 'dom_sha256': __import__('hashlib').sha256(b'
').hexdigest(), }, }) - assert result['status'] == 'failed' - assert result.get('data', {}).get('upload_evidence_persist_failed') is True - assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' - assert db.session.get(ShippingUploadAttempt, attempt.id).status != 'succeeded' + assert result['status'] == 'ok' + assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' + assert db.session.get(ShippingUploadAttempt, attempt.id).evidence_asset_id == 4242 -def test_normalize_rpa_success_evidence_rejects_missing_dom_or_bad_hash(): - """缺少 page_url/dom 或哈希不匹配时必须拒绝。""" +def test_normalize_rpa_success_evidence_requires_minimal_status_summary(): + """受信 RPA 成功证据必须具备可核验的站点、时间、文件和页面定位。""" from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence - import hashlib - - snippet = '
' - digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest() base = { 'kind': 'green_success_dom', 'selector': '#ok', 'filename': 'test.xlsx', 'observed_at': '2026-08-05T03:00:00Z', 'page_url': 'https://example.test/upload', - 'dom_snippet': snippet, - 'dom_sha256': digest, } + base.update({'dom_snippet': '
', 'dom_sha256': __import__('hashlib').sha256(b'
').hexdigest()}) assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None - # 关键断言:缺 page_url / 缺 snippet / 哈希错误一律 None。 + # 关键断言:缺页面定位、选择器、时间或文件名一律拒绝。 bad_url = dict(base, page_url='') assert _normalize_rpa_success_evidence({'success_evidence': bad_url}) is None - bad_snip = dict(base, dom_snippet='') - assert _normalize_rpa_success_evidence({'success_evidence': bad_snip}) is None - bad_hash = dict(base, dom_sha256='0' * 64) - assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None + assert _normalize_rpa_success_evidence({'success_evidence': dict(base, selector='')}) is None + assert _normalize_rpa_success_evidence({'success_evidence': dict(base, observed_at='')}) is None + assert _normalize_rpa_success_evidence({'success_evidence': dict(base, filename='')}) is None -def test_normalize_rpa_success_evidence_requires_dom_contract(): - """缺 page_url / dom_snippet / 哈希不一致时必须拒绝成功证据。""" - import hashlib - +def test_normalize_rpa_success_evidence_rejects_bad_dom_contract(): + """RPA 内部回调仍需 DOM 哈希自洽;这不适用于人工上传确认。""" from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence - snippet = '' - digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest() base = { 'kind': 'dsv_history_green_dom', 'selector': 'em.ok', 'filename': 'test.xlsx', 'observed_at': '2026-08-05T03:00:00Z', 'page_url': 'https://dsv.example/history', - 'dom_snippet': snippet, - 'dom_sha256': digest, + 'dom_snippet': '', + 'dom_sha256': '0' * 64, + 'screenshot_base64': 'legacy-only', } - assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None - # 关键断言:缺 page_url / 缺 snippet / 哈希不匹配均 fail-closed。 - missing_url = dict(base, page_url='') - assert _normalize_rpa_success_evidence({'success_evidence': missing_url}) is None - missing_dom = dict(base, dom_snippet='') - assert _normalize_rpa_success_evidence({'success_evidence': missing_dom}) is None - bad_hash = dict(base, dom_sha256='0' * 64) - assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None + assert _normalize_rpa_success_evidence({'success_evidence': base}) is None diff --git a/backend/tests/test_shipping_vendor_comments_phase2.py b/backend/tests/test_shipping_vendor_comments_phase2.py deleted file mode 100644 index 97a46f7f..00000000 --- a/backend/tests/test_shipping_vendor_comments_phase2.py +++ /dev/null @@ -1,444 +0,0 @@ -""" -tests/test_shipping_vendor_comments_phase2.py - -用途:阶段 2 集成回归——契约、关系投影、三来源裁决(Header/Table/Vendor Comments)、 - 回 Draft 门禁、格式策略服务 5 大主题全量覆盖。 -依赖:6 个新服务(profile_vendor_comments_contract、coordinate_region_source_adapter、 - reservation_relation_projection、profile_field_source_mapping_service、 - source_merge_service、reservation_format_policy_service)。 -逻辑:纯内存单测——读真实 PDF/数据库的用例放在阶段 4; - 覆盖 Q13/Q14/Q15/Q16/Q18 全部冻结决策矩阵。 -""" - -from __future__ import annotations - -import pytest - -from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import ( - CoordinateRegionSourceAdapter, -) -from app.services.shipping_notice.document_layout.field_split_core import ( - BaseSplitMatcher, - BaseSplitNormalization, - BaseSplitRule, - BaseSplitRuleSet, - BaseSplitSegment, - RelationCaptureDef, - new_segment_id, -) -from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import ( - FieldSourceCandidate, - ProfileFieldSourceMappingService, -) -from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import ( - NamedRegion, - ProfileFieldSourceMapping, - ReservationFormatPolicy, - field_source_mappings_checksum, - field_source_mappings_require_draft, - named_regions_checksum, - parse_field_source_mappings, - parse_named_regions, - profile_regions_require_draft, -) -from app.services.shipping_notice.document_layout.reservation_format_policy_service import ( - ReservationFormatPolicyService, -) -from app.services.shipping_notice.document_layout.reservation_relation_projection import ( - ReservationRelationProjection, -) -from app.services.shipping_notice.document_layout.source_merge_service import ( - SourceMergeService, -) -from app.services.shipping_notice.document_layout.order_profile import RelativeRegion - - -# ========================================================================= -# [TEST GROUP 1] profile_vendor_comments_contract(Q14/Q15) -# ========================================================================= - - -def test_parse_named_regions_empty_is_allowed(): - """当前客户没配 Vendor Comments 区域 → 返回空,不报错。""" - assert parse_named_regions(None) == {} - assert parse_named_regions({}) == {} - - -def test_named_region_last_page_vendor_comments_parses(): - """Q14 冻结结构:region_id/label/region/page_scope/selection_mode 全齐。""" - raw = { - 'vendor_comments': { - 'region_id': 'vendor-comments-v1', - 'label': 'Vendor Comments', - 'region': {'x0': 0.03, 'y0': 0.62, 'x1': 0.42, 'y1': 0.78}, - 'page_scope': 'last_page', - 'selection_mode': 'fixed_region', - }, - } - regions = parse_named_regions(raw) - assert 'vendor_comments' in regions - r = regions['vendor_comments'] - assert r.page_scope == 'last_page' - assert r.region.y1 > r.region.y0 - - -def test_named_region_rejects_key_region_id_mismatch(): - """外键 key 与 region_id 不一致:拒绝。""" - raw = {'vc': {'region_id': 'other-name', - 'label': 'L', 'region': {'x0':0,'y0':0,'x1':1,'y1':1}, - 'page_scope': 'last_page', 'selection_mode': 'fixed_region'}} - from app.core.errors import ValidationError - with pytest.raises(ValidationError): - parse_named_regions(raw) - - -def test_profile_regions_require_draft_matrix(): - """Q14:增删改 region/坐标/page_scope/selection_mode → 回 Draft;仅 label 不回。""" - old = { - 'vc': { - 'region_id': 'vc', 'label': 'Old Label', - 'region': {'x0':0,'y0':0,'x1':1,'y1':1}, - 'page_scope': 'last_page', 'selection_mode': 'fixed_region', - }, - } - # 仅改 label → 不回 Draft - new_same_label_only = {k: {**v, 'label': 'New Label'} for k, v in old.items()} - assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_same_label_only) is False - - # 改 x0 → 回 Draft - new_coord = {k: {**v} for k, v in old.items()} - new_coord['vc']['region'] = {'x0':0.01,'y0':0,'x1':1,'y1':1} - assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_coord) is True - - # 新增 region → 回 Draft - new_extra = { - **old, - 'other': { - 'region_id': 'other', 'label': 'O', - 'region': {'x0':0,'y0':0,'x1':0.1,'y1':0.1}, - 'page_scope': 'first_page', 'selection_mode': 'fixed_region', - }, - } - assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_extra) is True - - -def test_field_source_mappings_require_draft_any_change_triggers(): - """Q9:field_source_mappings 任何改 → 回 Draft(首期全量 fail-close)。""" - old = [{ - 'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id', - 'target_field_id': 'f-r1', 'vendor_comments_enabled': False, - }] - new = [{ - 'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id', - 'target_field_id': 'f-r1', 'vendor_comments_enabled': True, - 'vendor_comments_region_ref': 'vc', - 'vendor_comments_split_rule_set': { - 'rule_set_id': 'rs1', 'rule_version': 1, - 'normalization': {}, 'rules': [], - 'unmatched_line_policy': 'evidence_only', 'source': 'user', - 'status': 'confirmed', 'requires_confirmation': False, - }, - }] - assert field_source_mappings_require_draft(old_mappings=old, new_mappings=new) is True - - -def test_reservation_format_policy_rejects_dangerous_regex(): - """Q15:(a+)+$ 被 Pydantic validator 拦截在构造阶段。""" - from pydantic import ValidationError as PydanticValErr - with pytest.raises(PydanticValErr): - ReservationFormatPolicy( - mode='custom_safe_regex', - pattern=r'(a+)+$', - ) - - -# ========================================================================= -# [TEST GROUP 2] reservation_relation_projection(Q2/Q7/Q12) -# ========================================================================= - - -def test_relation_projection_bind_target_line_via_profile_business_line_no(): - """Q2:captured_relation.line_no=2 命中 profile_business_line_no{2:1} → 逻辑行号1。""" - from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation - proj = ReservationRelationProjection( - relation_policy='bind_target_line', - line_reference_basis='profile_business_line_no', - ) - result = proj.project( - captured_relation=CoreCapturedRelation(type='line_reference', line_no=2, raw_text='for line#2'), - profile_business_line_numbers={1: '1', 2: '2', 3: '3'}, - ) - assert result.resolution == 'bound_to_line' - assert result.resolved_logical_line_no == 2 # 逻辑行号=1-based mapping key - - -def test_relation_projection_invalid_line_reference_emits_independent_reason(): - """Q12:引用不存在的行 99 → invalid_line_reference 独立原因码。""" - from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation - proj = ReservationRelationProjection(relation_policy='bind_target_line') - result = proj.project( - captured_relation=CoreCapturedRelation(type='line_reference', line_no=99, raw_text='line#99'), - profile_business_line_numbers={1: '1', 2: '2'}, - ) - assert result.resolution == 'invalid_line_reference' - assert result.invalid_reference_line_no == 99 - assert result.audit_chain is not None - assert result.should_generate_header_observation is True # invalid 保留为头证据 - - -def test_relation_projection_annotation_only_writes_metadata(): - """annotation_only:不绑定行,不生成行 Observation,生成头元数据。""" - proj = ReservationRelationProjection(relation_policy='annotation_only') - result = proj.project( - captured_relation=None, - annotation_reason_override='customer_commentary_reservation', - ) - assert result.resolution == 'annotation_only' - assert result.annotation_reason == 'customer_commentary_reservation' - assert result.should_generate_line_observation is False - assert result.should_generate_header_observation is True - - -def test_relation_missing_policy_default_all_lines_flags_every_line(): - """missing_relation_policy=default_all_lines:每行都生成 Observation。""" - proj = ReservationRelationProjection( - relation_policy='bind_target_line', - missing_relation_policy='default_all_lines', - ) - result = proj.project(captured_relation=None) - assert result.resolution == 'default_all_lines' - assert result.should_generate_line_observation is True - - -# ========================================================================= -# [TEST GROUP 3] SourceMergeService(Q18 三来源裁决) -# ========================================================================= - - -def _make_cand(source, scope, code, line_no, value, *, - fv=True, frc=None, mapping_id='m1', target_field_id='f-r1', - hint='provisional') -> FieldSourceCandidate: - c = FieldSourceCandidate( - source=source, target_scope=scope, target_field_code=code, - target_field_id=target_field_id, value=value, normalized_value=value, - format_valid=fv, format_reason_code=frc, effective_line_no=line_no, - resolution_hint=hint, - evidence_quote=value, evidence_ref=f'{source}-ref', - evidence_metadata={'mapping_id': mapping_id}, - ) - c.conflict_group_key = (scope, code, line_no) - return c - - -def test_source_merge_same_value_merged_marks_metadata(): - """Q18 same_value_merge:三来源同值 3000098851 → resolution=same_value_merged。""" - candidates = [ - _make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'), - _make_cand('table_column', 'line', 'reservation_id', 1, '3000098851'), - _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'), - ] - svc = SourceMergeService(candidates) - merged = svc.merge_and_decide() - assert len(merged) == 1 - m = merged[0] - assert m.accepted_value == '3000098851' - assert m.resolution == 'same_value_merged' - assert m.decision_status == 'accepted' - assert m.should_persist_observation is True - md = m.evidence_metadata - assert md['resolution'] == 'same_value_merged' - assert len(md['source_observations']) == 3 - assert 'vendor_comments' in md['resolution_meta'].get('merged_from_sources', []) - - -def test_source_merge_conflict_triggers_needs_review_no_accepted_value(): - """Q18 冲突:Header=3000098851, VC=3000098899 → accepted_value=None, needs_review。""" - candidates = [ - _make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'), - _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098899'), - ] - svc = SourceMergeService(candidates) - merged = svc.merge_and_decide() - assert len(merged) == 1 - m = merged[0] - assert m.accepted_value is None - assert m.resolution == 'needs_review' - assert m.decision_status == 'needs_review' - assert m.should_persist_observation is False - assert len(m.evidence_metadata['source_observations']) == 2 - assert len(m.conflicts) == 2 # 双冲突 - - -def test_source_merge_fill_missing_table_empty_filled_from_vc(): - """Q4 fill_missing:表列空,VC 提供值 → fill_missing 自动填补。""" - candidates = [ - _make_cand('table_column', 'line', 'reservation_id', 1, ''), - _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'), - ] - svc = SourceMergeService(candidates) - merged = svc.merge_and_decide() - m = merged[0] - assert m.accepted_value == '3000098851' - assert m.resolution == 'fill_missing' - md = m.evidence_metadata - assert md['resolution_meta']['accepted_source'] == 'vendor_comments' - - -def test_source_merge_annotation_only_never_becomes_accepted(): - """annotation_only / invalid_line_reference:永不升 accepted,永不生成有效 Observation。""" - candidates = [ - _make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851', hint='annotation_only'), - _make_cand('vendor_comments', 'line', 'reservation_id', 1, '123', hint='invalid_line_reference'), - ] - svc = SourceMergeService(candidates) - merged = svc.merge_and_decide() - assert len(merged) == 1 - m = merged[0] - assert m.should_persist_observation is False - assert m.decision_status == 'blocked' - assert len(m.evidence_metadata['source_observations']) == 2 - - -# ========================================================================= -# [TEST GROUP 4] 三来源候选收集(ProfileFieldSourceMappingService) -# ========================================================================= - - -def test_collect_candidates_table_and_header_scopes_are_independent(): - """Q4:不同 scope 独立保留,互不冲突。Header=300001, Line=300002 都被收集。""" - definition_json = { - 'field_source_mappings': [ - {'mapping_id': 'mh', 'target_scope': 'header', - 'target_field_code': 'reservation_id', 'target_field_id': 'f-hr', - 'header_source_enabled': True, 'header_source_ref': 'header-rid'}, - {'mapping_id': 'ml', 'target_scope': 'line', - 'target_field_code': 'reservation_id', 'target_field_id': 'f-lr', - 'table_source_enabled': True, 'table_column_code': 'reservation_id'}, - ], - } - svc = ProfileFieldSourceMappingService( - definition_json=definition_json, - header_observations_by_source_ref={ - 'header-rid': [{'value': '300001', 'evidence_ref': 'h-ref-1'}], - }, - table_column_values={ - 'reservation_id': [ - {'line_index': 0, 'value': '300002', 'evidence_ref': 'l1'}, - {'line_index': 1, 'value': '300003', 'evidence_ref': 'l2'}, - ], - }, - ) - cands = svc.collect_candidates() - header_cands = [c for c in cands if c.target_scope == 'header'] - line_cands = [c for c in cands if c.target_scope == 'line'] - assert len(header_cands) == 1 - assert header_cands[0].value == '300001' - assert len(line_cands) == 2 - line_values = sorted([c.value for c in line_cands]) - assert line_values == ['300002', '300003'] - # Header 与 Line 不同冲突组 - groups = {c.conflict_group_key for c in cands} - assert len(groups) == 3 # header+None / line+1 / line+2 - - -# ========================================================================= -# [TEST GROUP 5] FormatPolicyService(Q15) -# ========================================================================= - - -def test_format_policy_inherit_global_accepts_5_and_10_numeric(): - svc = ReservationFormatPolicyService() - r5 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '12345') - r10 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '1234567890') - r_alpha = svc.check(ReservationFormatPolicy(mode='inherit_global'), 'ABC12') - assert r5.valid is True and r5.normalized_value == '12345' - assert r10.valid is True and r10.normalized_value == '1234567890' - assert r_alpha.valid is False and r_alpha.reason_code == 'reservation_format_invalid' - assert r_alpha.should_block_auto_create is True - - -def test_format_policy_custom_safe_regex_uses_first_capture_group(): - """字母型 Reservation 预留(例如 R-12345)通过第 1 捕获组提取。""" - svc = ReservationFormatPolicyService() - policy = ReservationFormatPolicy( - mode='custom_safe_regex', - pattern=r'R[ -](\d{5,10})\b', - case_sensitive=False, - ) - r = svc.check(policy, 'please use R-3000098851 thanks') - assert r.valid is True - assert r.normalized_value == '3000098851' - - -# ========================================================================= -# [TEST GROUP 6] CoordinateRegionSourceAdapter smoke(小字典 bbox) -# ========================================================================= - - -def test_coordinate_region_adapter_last_page_reads_text(): - """last_page → page_no=2,返回可用原文 + bbox 证据。""" - def glyph(ch, x, y, page_w=800, page_h=1100, *, - prev_space=False, src_idx=0): - w = 10 - b = 'space' if prev_space else 'none' - return { - 'text': ch, - 'bbox': {'x0': x*page_w, 'y0': y*page_h, - 'x1': (x+0.01)*page_w, 'y1': (y+0.02)*page_h}, - 'boundary_before': b, - 'source_index': src_idx, - } - page1_glyphs = [glyph('A', 0.05, 0.1, src_idx=i) for i, A in enumerate('PageOne')] - page2_glyphs = [ - *(glyph(ch, 0.04 + i*0.015, 0.65, src_idx=100+i, prev_space=(ch == ' ')) - for i, ch in enumerate('Reservation 3000098851 for line#2')), - ] - page_bundle = { - 1: {'glyphs': page1_glyphs, 'page': {'width': 800, 'height': 1100}}, - 2: {'glyphs': page2_glyphs, 'page': {'width': 800, 'height': 1100}}, - } - region = NamedRegion( - region_id='vc', label='VC', - region=RelativeRegion(x0=0.01, y0=0.60, x1=0.80, y1=0.80), - page_scope='last_page', - selection_mode='fixed_region', - ) - adapter = CoordinateRegionSourceAdapter(region, page_bundle) - result = adapter.extract() - assert result.status == 'available' - assert result.page_no == 2 - assert '3000098851' in result.raw_text - assert 'line' in result.raw_text.lower() - - -# ========================================================================= -# [TEST GROUP 7] checksums 稳定性(防篡改) -# ========================================================================= - - -def test_checksums_deterministic_and_sensitive_to_content(): - regions = {'vc': NamedRegion( - region_id='vc', label='L', selection_mode='fixed_region', - region=RelativeRegion(x0=0, y0=0, x1=1, y1=1), - page_scope='last_page', - )} - h1 = named_regions_checksum(regions) - assert len(h1) == 64 - regions2 = dict(regions) - regions2['vc'].model_copy() # 内容相同 → hash 相同(copy 保持引用,直接 mutate 不行,因此换 label) - regions_diff = {'vc': NamedRegion( - region_id='vc', label='Changed Label But Still Same Content?', - selection_mode='fixed_region', - region=RelativeRegion(x0=0, y0=0, x1=1, y1=1), - page_scope='last_page', - )} - # Label 变化 → 不同 hash(label 进入 checksum,因为管理员 label 变更不触发回 Draft,但需要留痕) - h_diff = named_regions_checksum(regions_diff) - assert h1 != h_diff - - mappings = [ProfileFieldSourceMapping( - mapping_id='m1', target_scope='line', target_field_code='reservation_id', - target_field_id='f-r1', vendor_comments_enabled=False, - )] - mh1 = field_source_mappings_checksum(mappings) - assert len(mh1) == 64 diff --git a/backend/tests/test_shipping_xfa_publish_separation_of_duties.py b/backend/tests/test_shipping_xfa_publish_separation_of_duties.py index 27c24466..7e16090c 100644 --- a/backend/tests/test_shipping_xfa_publish_separation_of_duties.py +++ b/backend/tests/test_shipping_xfa_publish_separation_of_duties.py @@ -1,7 +1,7 @@ """ tests/test_shipping_xfa_publish_separation_of_duties.py -用途:阶段 6 发布职责分离契约——编辑人不得批准自己的 Revision。 +用途:验证发布确认不再额外限制草稿创建人。 依赖:publish_check_service 已有 consume 阻断键;本文件固化原因码与审计事件集合。 逻辑:纯单元断言职责分离键与编辑审计事件白名单稳定。 """ @@ -17,19 +17,13 @@ from app.services.shipping_notice import order_document_profile_publish_check_se pytestmark = pytest.mark.pure_unit -def test_editor_self_approval_reason_key_is_stable(): - """关键断言:职责分离失败键稳定为 editor_cannot_approve_own_version。""" +def test_editor_self_approval_gate_is_removed(): + """关键断言:消费流程不再包含自己编辑不得发布的门禁。""" source = inspect.getsource(checks.consume_report) - assert 'editor_cannot_approve_own_version' in source - assert '_find_last_profile_editor_id' in source + assert 'editor_cannot_approve_own_version' not in source + assert '_find_last_profile_editor_id' not in source -def test_editor_audit_events_cover_mapping_and_split(): - """关键断言:查找最近编辑者覆盖末端映射与拆分编辑审计事件。""" - source = inspect.getsource(checks._find_last_profile_editor_id) - for event in ( - 'xfa_mapping_saved', - 'xfa_split_rule_suggested', - 'xfa_segment_mapping_updated', - ): - assert event in source +def test_publish_check_service_has_no_editor_separation_helper(): + """关键断言:发布检查服务不再保留历史编辑者查询辅助函数。""" + assert not hasattr(checks, '_find_last_profile_editor_id') diff --git a/backend/tests/test_shipping_xfa_split_rule_contract.py b/backend/tests/test_shipping_xfa_split_rule_contract.py index faccc465..73097851 100644 --- a/backend/tests/test_shipping_xfa_split_rule_contract.py +++ b/backend/tests/test_shipping_xfa_split_rule_contract.py @@ -97,6 +97,18 @@ def test_matcher_whitelist_and_regex_limits(): XfaSplitMatcher(type='regex', pattern=r'(a+)+$') +def test_position_matcher_accepts_restricted_prefix_post_processor(): + """位置选行后可正式执行标签后取值,不能依赖 UI stages[]。""" + matcher = XfaSplitMatcher( + type='position', + line_index=3, + post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}], + ) + + assert matcher.post_processors[0].type == 'prefix' + assert matcher.post_processors[0].value == 'MPN' + + def test_rule_set_accepts_rule_id_alias(): """历史 rule_id 字段可解析为 rule_set_id。""" rule_set = XfaSplitRuleSet( diff --git a/backend/tests/test_shipping_xfa_split_rule_engine.py b/backend/tests/test_shipping_xfa_split_rule_engine.py index 9024b7f1..7a758aa4 100644 --- a/backend/tests/test_shipping_xfa_split_rule_engine.py +++ b/backend/tests/test_shipping_xfa_split_rule_engine.py @@ -254,3 +254,32 @@ def test_line_breaks_config_is_honored(): assert 'A' in claimeds unmatched = {item.normalized_text for item in result.evidence_only_segments if item.rule_id == 'unmatched'} assert unmatched == {'B', 'C'} + + +def test_position_rule_applies_prefix_post_processor_to_selected_line(): + """先按行定位,再取标签后内容,保证 XFA 正式规则与预览一致。""" + rule_set = XfaSplitRuleSet( + rule_set_id='mpn-v1', + rule_version=1, + source_path_id='path-x', + source_scope='line', + rules=[ + XfaSplitRule( + rule_id='r-mpn', + matcher=XfaSplitMatcher( + type='position', line_index=3, + post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}], + ), + segment=XfaSplitSegment( + segment_id=new_segment_id(), segment_code='part_number', display_name='MPN', + handling='mapped', target_field_id='f-part', target_field_code='part_number', + ), + ), + ], + ) + + result = execute_split_rule_set(raw_value='TEMP-S000218922\nFRAME\nMPN:D4-A08AR12000001', rule_set=rule_set) + + assert result.mapped_fields == {'part_number': 'D4-A08AR12000001'} + assert result.segments[0].raw_text == 'MPN:D4-A08AR12000001' + assert result.segments[0].normalized_text == 'D4-A08AR12000001' diff --git a/backend/tests/test_tasks_0304_chat_fix.py b/backend/tests/test_tasks_0304_chat_fix.py index 1fee59d9..a2fb2fcf 100644 --- a/backend/tests/test_tasks_0304_chat_fix.py +++ b/backend/tests/test_tasks_0304_chat_fix.py @@ -1,6 +1,7 @@ import pytest +from flask import g from app import create_app, db -from app.models import Agent, User +from app.models import Agent, ChatSession, User @pytest.fixture def client(): @@ -97,3 +98,60 @@ def test_chat_url_logic(client): res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': agent_id}) assert res.status_code == 403 assert res.get_json()['error'] == 'Permission denied for this agent' + + +def test_chat_completions_stream_reads_session_snapshot_after_commit(client, monkeypatch): + """ + 提交会话后消费 SSE 时使用标量快照,避免已脱离 Session 的 ORM 实例被延迟刷新。 + + 关键断言:生成器在请求返回后仍能产出 session_created 事件,而不会抛出 + DetachedInstanceError。 + """ + with client.application.app_context(): + user = User(username='stream-user', role='admin', email='stream-user@example.com') + agent = Agent(name='Stream Agent', dify_api_key='test-key', api_base_url='http://dify.invalid') + db.session.add_all([user, agent]) + db.session.commit() + user_id = user.id + agent_id = agent.id + + monkeypatch.setattr( + 'app.services.chat.executors.stream_chat_via_executor', + lambda _context: iter(['data: {"event": "message_end"}\n\n']), + ) + from app.api.chat import completions + + captured_session = None + original_ensure_chat_session = completions._ensure_chat_session + + def capture_ensured_session(*args, **kwargs): + nonlocal captured_session + captured_session = original_ensure_chat_session(*args, **kwargs) + return captured_session + + monkeypatch.setattr(completions, '_ensure_chat_session', capture_ensured_session) + + def get_current_user(): + current_user = db.session.get(User, user_id) + g.current_user = current_user + return current_user + + monkeypatch.setattr('app.core.decorators._get_current_user', get_current_user) + + with client.application.test_request_context( + '/api/chat/completions', + method='POST', + json={'agent_id': agent_id, 'query': '测试流式会话'}, + ): + response = client.application.view_functions['chat.chat_completions']() + # 模拟生产环境:流式处理中的事务令 ORM 属性过期,随后请求 scoped Session 被清理。 + assert captured_session is not None + db.session.expire(captured_session) + db.session.remove() + body = ''.join(response.response).encode() + + assert response.status_code == 200 + assert b'"event": "session_created"' in body + assert b'DetachedInstanceError' not in body + with client.application.app_context(): + assert ChatSession.query.filter_by(user_id=user_id, agent_id=agent_id).count() == 1 diff --git a/backend/tests/test_worker_shipping.py b/backend/tests/test_worker_shipping.py index c7ea8036..2660eff6 100644 --- a/backend/tests/test_worker_shipping.py +++ b/backend/tests/test_worker_shipping.py @@ -53,6 +53,22 @@ def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch): assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types'] +def test_shipping_worker_claims_review_revalidate_jobs(monkeypatch): + """Review Revalidate Job 必须进入 shipping worker 领取白名单,不能永久 queued。""" + received: dict[str, object] = {} + + def claim_next_job(**kwargs): + received.update(kwargs) + return None + + monkeypatch.setattr('app.jobs.queue.claim_next_job', claim_next_job) + + queue_service.claim_next_shipping_notice_job() + + # 关键断言:字段变更后的异步校验任务必须由 shipping worker 领取。 + assert JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS in received['job_types'] + + def test_route_runtime_diagnostic_identifies_loaded_workflow_without_document_content(): """路由审计必须可定位 Worker 代码身份,且不得采集文档或字段内容。""" from app.jobs.handlers import shipping_order_extraction as handler diff --git a/docs/demand.md b/docs/demand.md index 370942ce..9fb7e6e4 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -13,7 +13,7 @@ ### 当前业务阶段基线(2026-08) -业务人员只看到五个阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;下载 Excel、RPA 上传、人工回执登记、失败重试和未知结果核对属于货代上传。`ui_state` 是唯一前端读模型,按钮由后端统一返回。 +业务人员只看到五个阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;下载 Excel、RPA 上传、人工确认、失败重试和未知结果核对属于货代上传。`ui_state` 是唯一前端读模型,按钮由后端统一返回。 - **完成口径**:只有 `upload_status=uploaded`、全部预约单均为 `uploaded`、且存在关联 Artifact 的 `ShippingUploadAttempt.status=succeeded` 三项事实同时成立,才进入「通知完成」并计入任务/批次完成率。PDF 候选成功、技术 `completed`、回执文本、取消或归档均不得替代成功事实。 - **恢复口径**:上传失败、RPA 运行中、人工待登记和历史无成功 Attempt 的 `uploaded` 都停在「货代上传」。未知结果必须先查询货代侧或登记核对证据,禁止自动重试;取消/归档是终态但不计为通知完成。同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。 @@ -91,7 +91,7 @@ - **业务需要**:PDF 进入系统至待人工上传的任一业务门禁失败后,应只恢复该门禁(或按精确依赖失效下游),复用输入未变化的上游结果,避免整单重跑或误用失效匹配/Excel。 - **Phase 0**:库存源路由已可在不重识别 PDF 的前提下按最新已发布规则重算;人工决定优先,须显式采用规则建议或保留人工结果。 - **Phase 1**:冻结 20 个门禁编码、状态、恢复动作、失效图与审计事件(见 [process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md));后续阶段再接线模型/API/UI。 -- **中断恢复(2026-08)**:建单前统一恢复协调器(`order_review_resume_service`)在客户确认、重复/冲突裁决、Reservation 重校验、草稿校验、行级履约决定后重算资格;**Gate 通过 / 建单资格 / auto_gate** 三层分离;符合 auto_gate 则幂等自动建单并推进。支持完整明细行先行履约波次(禁止拆分数量);技术 Gate 对业务用户 fail-closed。 +- **中断恢复(2026-08)**:建单前统一恢复协调器(`order_review_resume_service`)在客户确认、重复/冲突裁决、Reservation 重校验、草稿校验、行级履约决定后重算资格;**Gate 通过 / 建单资格 / auto_gate** 三层分离;符合 auto_gate 则幂等自动建单并推进。支持完整明细行先行履约波次(禁止拆分数量);短缺放行后仅当恰有一条开放可履约明细时自动创建 Notice 与其 Excel,多条仍由用户勾选合并,暂不支持批次放行;技术 Gate 对业务用户 fail-closed。 - **Phase 1.5**:字段仅在 `required` 或 `auto_create_key_field` 时因质量问题阻断;可选非关键字段证据不足只诊断不阻断;用户端同一时间最多一个阻断原因;自动冻结资格类原因唯一归属 `order_freeze_readiness`;禁止旧五门禁平行用户投影。 - **权限**:任务所有者与管理员可发起恢复与人工决定;其他人员默认只读,除非另行授予恢复权限;未授权用户不可见。 @@ -99,7 +99,7 @@ - 管理员在受控低清 PDF 画布上配置表头、明细物理行和字段区域,不输入坐标数字;翻页按页加载,离开未保存草稿必须确认。 - 表头行与明细行分别配置。表头识别只能给出当前冻结 Schema 的唯一精确别名建议,不能覆盖人工字段绑定;字段缺失、重复或不确定时保持未映射。 -- 订单级字段作为独立标注域:管理员可用标签锚点、相对值区、多行停止标签和受控规范化配置 Header 字段;不得把账款/送货客户、地址、PO 等标为明细表头或物理行字段。发布前盲测须验证每个订单字段的人工真值与页级字符坐标证据,`confirmed` 字段不可被 Dify 覆盖。 +- 订单级字段作为独立标注域:管理员可用标签锚点、相对值区、多行停止标签和受控规范化配置 Header 字段;对于 PDF 本身无真实标签的稳定字段,可配置单页固定值区,但只在模板唯一匹配、原生 PDF 坐标完整且字段校验通过的正式运行或盲测回放中确认为 `confirmed`。不得把账款/送货客户、地址、PO 等标为明细表头或物理行字段。发布前盲测须验证每个订单字段的人工真值与页级字符坐标证据,`confirmed` 字段不可被 Dify 覆盖。 - 字段规则版本必须保留:文档模板绑定稳定 `field_id` 与创建时 Schema 快照。新增或调整 Schema 版本不得清空既有模板绑定;仅发生字段语义、作用域、类型或证据能力等破坏性变化时,才要求受影响字段显式迁移和重新盲测。 ## 采购合同全面审核补充需求 @@ -220,7 +220,7 @@ ### 3.x 货代发货任务删除与回收站 - **核心目标**:任务列表支持批量删除、归档和回收站恢复;“删除”优先保留可追溯业务事实,而非直接物理删除。 -- **外部一致性门禁**:上传中、已上传、有货代参考号或上传回执的任务只能归档;HXOPS 不得在未接入外部作废能力时单方作废或删除。 +- **外部一致性门禁**:上传中、已上传或已有外部上传参考的任务只能归档;HXOPS 不得在未接入外部作废能力时单方作废或删除。 - **永久删除**:仅管理员可从回收站永久清除无任何业务、解析、库存、导出、修订、重复、外部上传或审计引用的纯误建任务;清除保留独立快照审计。 - **Dify 边界**:本功能不新增、不修改 Dify Tool 或画布节点。Dify 配置无需调整;任务处置由 HXOPS 工作台 API 和后端生命周期门禁处理。 @@ -234,7 +234,8 @@ - **发布与依赖**:识别规则集须草稿/发布/退役并保留不可变审计快照;被启用规则引用的订单字段不可退役或从发布 Schema 移除。 - **Dify 边界**:不新增或修改 Dify Tool/画布;Dify 仅按现有动态契约回传 Header Observation,配置由业务管理员手工核对,HXOPS 后端负责最终裁决、匹配和确认。 -- **双编号**:`ShippingTask.task_no` 继续作为创建即生成且永不修改的内部技术编号;客户确认后生成面向业务的 `business_no`,队列、文件目录、RPA、外键和内部 API 仍使用 `task_no`。 +- **双编号与操作边界**:`ShippingNotice.task_no` 是创建即生成且永不修改的内部技术追踪键;客户确认后为每张发货通知单生成唯一 `business_no`。货代下载、人工确认、RPA 上传、重试、批量操作、文件名与对外 API 均以 `business_no` 为唯一维度;`task_no` 不得作为货代操作参数。 +- **PO 与通知单**:一个 PO 可按不同库存到位批次创建多个 `ShippingNotice`;每张 Notice 冻结本次项次、料号、数量和预约单,并且只生成一个 Excel。后续库存到位必须创建新的 Notice 和新的 `business_no`,不得向已有 Notice 追加 Excel。 - **业务编号格式**:固定为 `{customer_short_code}{YYMMDD}{sequence_2}`,不使用分隔符;例如客户简码 `WYC` 在 2026-07-15 的第 1 票为 `WYC26071501`。 - **客户简码格式**:由管理员维护,全局唯一,固定为 `2-6` 位大写英文字母(`^[A-Z]{2,6}$`);完整业务编号满足 `^[A-Z]{2,6}\d{8}$`。 - **日期与容量**:日期严格按 `Asia/Shanghai` 计算;流水按“客户 + 上海业务日期”独立从 `01` 递增至 `99`,第 100 票必须阻断并提示容量耗尽,禁止归零、覆盖或随机补号。 @@ -292,6 +293,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。 +- **XFA 可见值回读补偿(2026-08-25)**:Hybrid XFA 的可见值可能仅由浏览器 PDF.js 外观层绘制,服务端 PDFium/OCR/Widget 因而可为空。工作台依次尝试原生坐标、服务端 OCR、唯一 Widget 与受控浏览器 XFA 画布裁剪 OCR;仍为空时保留管理员已框选的值框并明确提示回读失败,继续允许绑定 datasets。裁剪图不持久化、不进入审计正文、不替代 datasets 正式值。 - **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` 来源和最低证据等级;不可变版本可复制为新草稿或退役。 @@ -327,6 +329,7 @@ - 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。 - 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。 - 订单抽取进度必须来自 HXOPS 持久化的 Run / PDF Unit / Progress Event 数据库事实;用户卡片只展示 `summary/current_activity/available_actions` 及按 PDF 归并结果,不再消费 Dify 节点事件、Workflow 阶段或浏览器 SSE。浏览器继续使用自适应短轮询,页面刷新、重新登录和 Worker 重启后均可恢复同一事实视图。 +- **生命周期工作台进度(2026-08-23)**:复核工作台在 Run 正在解析、重解析或尚未产生 Case 的窗口也必须常驻显示五阶段导航及当前阶段内步骤;步骤只由 `Run / Unit / Progress Event` 的后端投影裁决。任何会触发后端异步自动推进的动作(包括重新解析、重新识别客户后门禁通过、库存/RPA/Excel 恢复)复用同一真实投影;仅打开客户选择或其他同步人工编辑不显示伪造“处理中”。门禁未通过展示稳定阻断原因,失败、取消、排队或长时间无活动在紧凑当前步骤提示中说明原因;不新增 SSE、进度表、状态机、独立状态卡或前端计时猜测。 - **处理进度细化与全链路审计(2026-07-29)**: - 用户可见阶段必须覆盖排队、版面预处理、路由、模板匹配、提取、正文合并、候选生成、人工复核、技术重试、失败、正在取消、已取消、完成;禁止把多种内部态压缩为单一“自动处理中”,禁止虚假百分比或 ETA。 - 普通用户可刷新自己的 Run、取消自己创建的活跃 Run/Unit;管理员可取消任意活跃项但代取消必须填写原因。整批取消为主操作;已完成 PDF 结果保留;仅失败项可重试且保留 Attempt/审计历史。`review_required` 不得显示为技术失败。 @@ -398,9 +401,9 @@ 本节是发货通知后续阶段的冻结业务契约;与本文件此前关于订单真相、制单条件或单份 Excel 的描述不一致时,以本节为准。 -- 履约策略固定为 `SHIP_AVAILABLE_ROLLING`:每轮有效库存核验中,只要至少一个预约单满足,即可由用户确认生成本轮 Excel;系统必须将该任务中全部“满足且未被有效 Excel 占用”的预约单一并写入该 Excel,缺货项继续等待下一轮库存。 +- 履约策略固定为 `SHIP_AVAILABLE_ROLLING`:自动链仅在全部未分配项次满足时创建一张独立发货通知和 Excel;任一项不足即中断。人工可多选“库存满足”或“已审计放行”的完整项次,每次生成一张独立通知与同号 Excel;缺货项继续等待补货或后续放行。 - **试点容量与恢复(阶段 7)**:批量通知文件数、单文件大小、EML 附件数量/单附件大小/总大小均须由环境变量限制,超限在解析和建单前返回明确业务错误;试点先以 3–5 个高频模板逐个完成独立盲测,再根据管理员健康接口记录的 P50/P95、失败率、积压与 RPA 耗时确定正式 SLA。Worker 重启恢复、同文件幂等重试和备份恢复演练均须留存环境、时间、操作者、结果与问题记录;演练失败不得启用自动建单或自动上传。 -- 一个附件可形成一个业务任务,但一个任务可形成多份按时间顺序的 Excel Artifact。全部缺货时不得产生空 Excel;已成功上传的预约单永久不得再次制单;仅当任务全部当前有效预约单均上传成功时才完成。 +- 一个附件可形成一个业务任务;一个 PO 可按库存批次创建多个独立发货通知单,但每张 Notice 只能形成一份 Excel Artifact。全部缺货时不得产生空 Excel;已成功上传的预约单永久不得再次制单;仅当该 Notice 的全部预约单均上传成功时才完成。 - `FieldValue` 仅是解析阶段的 Observation/Decision 投影;人工复核和客户绑定完成后冻结 `OrderSnapshot` 及其行作为库存、制单、上传的正式业务真相。冻结快照不可编辑,后续客户修订必须形成新快照版本。 - **字段分层与履约门禁**:平台系统事实由代码和数据库固定;货代订单字段由「系统标准字段资产(锁定 57 项)+ 扩展字段资产」组成,Schema 版本按需采用并以稳定 `field_id` 冻结。标准目录不是全部必填。当前固定策略 `SHIP_AVAILABLE_ROLLING_V1` 只要求 Line 的 `reservation_id:string`、`part_number:string`、`qty:decimal > 0` 以及已人工确认的 Bill-to 客户;`uom` 暂不强制且不做单位换算。`inventory_source_hint` 仅是可选 Line 路由线索。履约策略本轮不改造管理 UI,但策略绑定只能消费标准字段,不得把扩展字段绑到核心履约能力。 - **Reservation 全局唯一(阶段 1)**:`reservation_id` 单列全局唯一,同一 PO 内也不得重复。PO 比较只去除首尾空格并统一大写,保留前导零和中间字符;不同 PO 必须阻断为重复订单。相同 PO 但料号或数量变化仅返回包含前后差异的人工修订候选,存在有效 Excel Artifact 或已上传时直接阻断;PO 不属于首次履约最小字段,但 Reservation 已注册后若后续记录缺 PO 必须阻断,不能以空 PO 判断修订。 @@ -409,7 +412,7 @@ - 预约单以全局注册表管理,而非以历史订单行文本去重。唯一预约单在任一时刻只能处于 `pending`、`available`、`artifact_reserved`、`uploaded` 或 `external_change_required` 之一,并只允许归属一个有效 Artifact。 - Excel 文件名允许由已发布 Excel 模板的版本化命名规则定义;没有模板规则时可使用受控环境变量默认规则。后端必须校验规则、生成最终文件名并在 Artifact 冻结规则来源/版本、文件名和流水;前端、Dify 或普通用户不得提交任意文件名。 - Dify 仅生成候选 Observation,不能创建 Task、冻结 Snapshot、选择库存、生成 Excel 或触发上传。任何关键字段含未人工确认的 LLM fallback Observation 时,必须转人工复核并阻断自动冻结。 -- 人工上传是 RPA 的受控降级,必须上传截图或回执文件;没有外部成功证据不得将预约单标记为已上传。 +- 人工上传是 RPA 的受控降级:业务人员仅按 `business_no` 确认已上传,不上传截图、回执或 PDF;服务端仍通过该 Notice 的受控 Attempt 与状态机记录成功事实。 - 上传以 Excel Artifact 为边界:每次 RPA 或人工操作均创建独立 Attempt,trigger 和回调必须携带 `artifact_id`、`attempt_id` 与幂等 `callback_id`。相同回调只生效一次;网络失败只能重试原 Artifact,只有货代明确拒绝并经授权才可作废 Artifact、释放未上传预约单;Task 上传字段仅为 Artifact/Attempt 的聚合投影。 ### 3.1 本期范围 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 2988fb46..d0f966f5 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 @@ -14,9 +14,10 @@ *{box-sizing:border-box} html,body,#app{width:100%;height:100%;margin:0} #app{display:flex;min-width:0;overflow:hidden} body{font:14px/1.5 "Microsoft YaHei","PingFang SC",Arial,sans-serif;color:var(--text);background:var(--canvas)} button,input,select{font:inherit} button{cursor:pointer} button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid rgba(22,119,210,.22);outline-offset:2px} .shell{display:flex;width:100%;height:100%;min-width:0;overflow:hidden}.side{display:flex;flex:0 0 244px;width:244px;min-width:244px;max-width:244px;flex-direction:column;overflow:hidden;background:var(--surface);border-right:1px solid var(--line)}.brand{display:flex;align-items:center;gap:10px;height:64px;padding:0 18px;border-bottom:1px solid var(--line)}.brand-mark{display:grid;place-items:center;width:32px;height:32px;border-radius:9px;background:linear-gradient(135deg,#208add,#2368c9);color:#fff;font-size:12px;font-weight:800}.brand b{display:block;color:var(--ink);font-size:15px}.brand span{display:block;color:var(--muted);font-size:11px}.new-chat{margin:14px;border:1px solid #bfdbf6;border-radius:9px;padding:9px 12px;text-align:left;color:#1265af;background:var(--brand-50);font-weight:700}.nav-label{padding:9px 17px 5px;color:#96a2b3;font-size:10px;font-weight:800;letter-spacing:.08em}.history{min-height:0;padding:0 9px;overflow:auto}.history button{position:relative;width:100%;border:0;border-radius:8px;padding:9px 10px;background:transparent;color:var(--text);text-align:left}.history button:hover{background:var(--surface-soft)}.history button.active{color:#1469b4;background:var(--brand-50)}.history b,.history span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.history b{font-size:12px}.history span{margin-top:2px;color:var(--muted);font-size:10px}.history-divider{height:1px;margin:8px 8px 4px;background:var(--line)}.history-label{padding:5px 10px 3px;color:#96a2b3;font-size:10px;font-weight:800;letter-spacing:.05em}.history button.walkthrough b{font-weight:600}.history button.walkthrough span{color:#8797ab}.dot{position:absolute;top:11px;right:10px;width:7px;height:7px;border-radius:50%;background:#ed9a2c}.dot.bad{background:#d64d61}.user{display:flex;gap:8px;align-items:center;margin-top:auto;padding:14px 17px;border-top:1px solid var(--line)}.avatar{display:grid;place-items:center;width:30px;height:30px;border-radius:50%;color:#1269b3;background:#dff1ff;font-size:11px;font-weight:800}.user b,.user span{display:block}.user b{color:var(--ink);font-size:11px}.user span{color:var(--muted);font-size:10px} .main{display:flex;min-width:0;min-height:0;flex:1 1 auto;flex-direction:column;overflow:hidden}.topbar{height:64px;display:flex;align-items:center;gap:10px;padding:0 28px;background:var(--surface);border-bottom:1px solid var(--line)}.agent-icon{display:grid;place-items:center;width:32px;height:32px;border-radius:9px;color:var(--brand);background:var(--brand-50);font-weight:800}.title b{display:block;color:var(--ink);font-size:14px}.title span{display:block;margin-top:1px;color:var(--muted);font-size:11px}.crumb{margin-left:auto;color:var(--muted);font-size:12px}.layout{min-height:0;flex:1;overflow:auto}.page{width:min(1160px,100%);margin:0 auto;padding:28px}.page-head{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:18px}.page-head h1{margin:0;color:var(--ink);font-size:22px}.page-head p{max-width:720px;margin:5px 0 0;color:var(--muted);font-size:13px}.back{border:0;background:transparent;color:#176fba;font-weight:700}.card{border:1px solid var(--line);border-radius:12px;background:var(--surface);box-shadow:var(--shadow)}.card-h{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:15px 18px;border-bottom:1px solid var(--line)}.card-h h2{margin:0;color:var(--ink);font-size:15px}.card-h p{margin:3px 0 0;color:var(--muted);font-size:11px}.card-b{padding:18px}.grid{display:grid;gap:16px}.grid.two{grid-template-columns:1.55fr 1fr}.summary{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}.metric{padding:13px;border:1px solid var(--line);border-radius:10px;background:#fff}.metric b{display:block;color:var(--ink);font-size:20px}.metric span{display:block;margin-top:3px;color:var(--muted);font-size:11px}.metric button{border:0;padding:0;background:transparent;color:inherit;text-align:left}.metric.action{border-color:#cfe5f9;background:var(--brand-50)}.metric.action b{color:#1268b2}.notice{display:flex;gap:9px;margin-top:14px;border-radius:8px;padding:10px 12px;color:#596b82;background:var(--surface-soft);font-size:12px}.notice i{font-style:normal;font-weight:800}.notice.good{color:#167642;background:var(--good-50)}.notice.warn{color:#97620c;background:var(--warn-50)}.notice.bad{color:#ae3146;background:var(--bad-50)}.btn{border:1px solid #d1dbe7;border-radius:8px;padding:8px 12px;color:#43536a;background:#fff;font-size:12px;font-weight:700}.btn:hover{background:var(--surface-soft)}.btn.primary{border-color:var(--brand);color:#fff;background:var(--brand)}.btn.danger{border-color:#efb9c2;color:#b43449;background:var(--bad-50)}.btn[disabled]{cursor:not-allowed;opacity:.48}.actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}.chip{display:inline-flex;align-items:center;border-radius:999px;padding:3px 8px;font-size:11px;font-weight:700}.chip.good{color:#147340;background:var(--good-50)}.chip.warn{color:#9a640c;background:var(--warn-50)}.chip.bad{color:#ad3145;background:var(--bad-50)}.chip.gray{color:#68788e;background:#eff3f7}.chat-panel{min-height:370px;display:flex;flex-direction:column}.chat-messages{flex:1;padding:18px}.bubble{max-width:88%;margin-bottom:13px;border:1px solid var(--line);border-radius:4px 12px 12px;padding:10px 12px;color:var(--text);background:#fff;font-size:13px}.bubble.user-msg{margin-left:auto;border-color:var(--brand);border-radius:12px 4px 12px 12px;color:#fff;background:var(--brand)}.composer{display:flex;gap:8px;padding:12px;border-top:1px solid var(--line)}.composer input{min-width:0;flex:1;border:1px solid #d4dee9;border-radius:8px;padding:9px 11px}.quick{display:grid;gap:8px}.quick button{border:1px solid var(--line);border-radius:8px;padding:10px;color:#53637a;background:#fff;text-align:left;font-size:12px}.quick button:hover{border-color:#bfdcf7;color:#1267b1;background:var(--brand-50)} - .scope{display:flex;justify-content:space-between;gap:16px;align-items:center;padding:14px;border:1px solid #d7e9fa;border-radius:10px;background:#f5faff}.scope b{display:block;color:#145f9f}.scope span{display:block;margin-top:2px;color:#60748c;font-size:12px}.source-toolbar{display:flex;gap:10px;align-items:center;margin-bottom:13px}.source-toolbar input{width:280px;border:1px solid #d4dee9;border-radius:8px;padding:8px 10px}.source-toolbar .count{margin-left:auto;color:var(--muted);font-size:12px}.source-group{border:1px solid var(--line);border-radius:10px;overflow:hidden;margin-top:10px}.source-group-head{display:flex;align-items:center;gap:10px;padding:12px 13px;background:#fbfcfe}.source-group-head b{color:var(--ink)}.source-group-head span{color:var(--muted);font-size:11px}.source-group-head button{margin-left:auto;border:0;color:#176fba;background:transparent;font-size:12px}.source-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border-top:1px solid var(--line)}.source-item{display:flex;align-items:center;gap:9px;min-height:54px;padding:10px 13px;border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.source-item:nth-child(even){border-right:0}.source-item:last-child{border-bottom:0}.source-item b{display:block;color:var(--ink);font-size:12px}.source-item span{display:block;color:var(--muted);font-size:11px}.sticky-actions{position:sticky;bottom:0;display:flex;justify-content:flex-end;gap:8px;margin:18px -18px -18px;padding:13px 18px;border-top:1px solid var(--line);background:rgba(255,255,255,.96)} - .stage-list{display:grid;gap:10px}.stage{display:grid;grid-template-columns:14px 1fr auto;gap:10px;align-items:start;padding:12px;border:1px solid var(--line);border-radius:9px}.stage .mark{width:10px;height:10px;margin-top:4px;border-radius:50%;background:#a8b3c1}.stage.good .mark{background:var(--good)}.stage.warn .mark{background:#e1a238}.stage.bad .mark{background:var(--bad)}.stage b{display:block;color:var(--ink);font-size:12px}.stage span{display:block;margin-top:2px;color:var(--muted);font-size:11px}.facts{display:grid;grid-template-columns:repeat(3,1fr);gap:0;border:1px solid var(--line);border-radius:9px;overflow:hidden}.fact{padding:10px 12px;border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.fact:nth-child(3n){border-right:0}.fact:nth-last-child(-n+3){border-bottom:0}.fact span{display:block;color:var(--muted);font-size:10px}.fact b{display:block;margin-top:3px;color:var(--ink);font-size:12px}.table-wrap{overflow:auto}.table{width:100%;border-collapse:collapse;font-size:12px}.table th,.table td{padding:11px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:middle}.table th{color:#7d8ba0;background:#fafbfd;font-size:11px;font-weight:700}.table td b{color:var(--ink)}.table tr.disabled{color:#8693a4;background:#fbfcfe}.link{border:0;padding:0;color:#146fba;background:transparent;font-weight:700}.confirm-band{display:flex;justify-content:space-between;align-items:center;gap:14px;margin-top:13px;border:1px solid #d3e8f9;border-radius:9px;padding:12px;background:#f5faff}.confirm-band b{color:#155f9f}.route-org{margin-top:12px;border:1px solid var(--line);border-radius:10px;background:#fff;overflow:hidden}.route-org>summary,.route-item>summary{display:flex;align-items:center;gap:12px;list-style:none;cursor:pointer}.route-org>summary::-webkit-details-marker,.route-item>summary::-webkit-details-marker{display:none}.route-org>summary{padding:14px 16px;background:#fbfcfe}.route-org>summary::before,.route-item>summary::before{content:'›';width:16px;color:#6d7d91;font-size:20px;line-height:1;transition:transform .15s}.route-org[open]>summary::before,.route-item[open]>summary::before{transform:rotate(90deg)}.route-org-title{min-width:0;flex:1}.route-org-title b{display:block;color:var(--ink);font-size:14px}.route-org-title span{display:block;margin-top:2px;color:var(--muted);font-size:11px}.route-org-metrics{display:flex;gap:14px;color:#52637a;font-size:12px}.route-org-metrics b{color:var(--ink)}.route-table{border-top:1px solid var(--line)}.route-item{border-bottom:1px solid var(--line)}.route-item:last-child{border-bottom:0}.route-item>summary{padding:11px 16px}.route-item>summary:hover{background:var(--surface-soft)}.route-item-main{min-width:0;flex:1}.route-item-main b{color:var(--ink)}.route-item-main span{margin-left:8px;color:var(--muted);font-size:11px}.route-item-metrics{display:flex;gap:18px;color:#52637a;font-size:12px}.route-item-metrics strong{color:var(--ink)}.route-invoices{padding:0 16px 14px 44px;background:#fcfdff}.tabs{display:flex;gap:5px;border-bottom:1px solid var(--line);margin-bottom:14px}.tab{border:0;border-bottom:2px solid transparent;padding:9px 11px;color:#718097;background:transparent;font-size:12px;font-weight:700}.tab.active{border-color:var(--brand);color:#146bb4}.filters{display:flex;gap:8px;margin-bottom:12px}.filters select{border:1px solid #d5dfe9;border-radius:7px;padding:7px 9px;color:var(--text);background:#fff}.progress{height:7px;border-radius:999px;background:#eaf0f6;overflow:hidden}.progress i{display:block;height:100%;border-radius:inherit;background:var(--brand)} + .scope{display:flex;justify-content:space-between;gap:16px;align-items:center;padding:14px;border:1px solid #d7e9fa;border-radius:10px;background:#f5faff}.scope b{display:block;color:#145f9f}.scope span{display:block;margin-top:2px;color:#60748c;font-size:12px}.source-toolbar{display:flex;gap:10px;align-items:center;margin-bottom:13px}.source-toolbar input{width:280px;border:1px solid #d4dee9;border-radius:8px;padding:8px 10px}.source-toolbar .count{margin-left:auto;color:var(--muted);font-size:12px}.source-group{border:1px solid var(--line);border-radius:10px;overflow:hidden;margin-top:10px}.source-group-head{display:flex;align-items:center;gap:10px;padding:12px 13px;background:#fbfcfe}.source-group-head b{color:var(--ink)}.source-group-head span{color:var(--muted);font-size:11px}.source-group-head button{margin-left:auto;border:0;color:#176fba;background:transparent;font-size:12px}.source-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));border-top:1px solid var(--line)}.source-item{display:flex;align-items:flex-start;gap:9px;min-height:82px;padding:10px 13px;border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.source-item input{margin-top:4px}.source-item:nth-child(even){border-right:0}.source-item:last-child{border-bottom:0}.source-detail{min-width:0;flex:1}.source-item b{display:block;color:var(--ink);font-size:12px}.source-item span{display:block;color:var(--muted);font-size:11px}.source-file{display:flex;align-items:center;gap:6px;min-width:0;margin-top:6px}.source-file-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#536b84!important}.source-file-meta{font-size:10px!important}.source-file-empty{color:#9aa6b5!important}.icon-button{display:grid;place-items:center;width:26px;height:26px;flex:0 0 26px;border:1px solid #c9d8e8;border-radius:6px;padding:0;color:#176fba;background:#fff;font-size:15px;font-weight:800}.icon-button:hover{border-color:#8cc3eb;background:var(--brand-50)}.icon-button[disabled]{cursor:not-allowed;color:#9aa6b5;background:#f5f7fa}.sticky-actions{position:sticky;bottom:0;display:flex;justify-content:flex-end;gap:8px;margin:18px -18px -18px;padding:13px 18px;border-top:1px solid var(--line);background:rgba(255,255,255,.96)} + .stage-list{display:grid;gap:10px}.stage{display:grid;grid-template-columns:14px 1fr auto;gap:10px;align-items:start;padding:12px;border:1px solid var(--line);border-radius:9px}.stage .mark{width:10px;height:10px;margin-top:4px;border-radius:50%;background:#a8b3c1}.stage.good .mark{background:var(--good)}.stage.warn .mark{background:#e1a238}.stage.bad .mark{background:var(--bad)}.stage b{display:block;color:var(--ink);font-size:12px}.stage span{display:block;margin-top:2px;color:var(--muted);font-size:11px}.facts{display:grid;grid-template-columns:repeat(3,1fr);gap:0;border:1px solid var(--line);border-radius:9px;overflow:hidden}.fact{padding:10px 12px;border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.fact:nth-child(3n){border-right:0}.fact:nth-last-child(-n+3){border-bottom:0}.fact span{display:block;color:var(--muted);font-size:10px}.fact b{display:block;margin-top:3px;color:var(--ink);font-size:12px}.table-wrap{overflow:auto}.table{width:100%;border-collapse:collapse;font-size:12px}.table th,.table td{padding:11px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:middle}.table th{color:#7d8ba0;background:#fafbfd;font-size:11px;font-weight:700}.table td b{color:var(--ink)}.table tr.disabled{color:#8693a4;background:#fbfcfe}.link{border:0;padding:0;color:#146fba;background:transparent;font-weight:700}.confirm-band{display:flex;justify-content:space-between;align-items:center;gap:14px;margin-top:13px;border:1px solid #d3e8f9;border-radius:9px;padding:12px;background:#f5faff}.confirm-band b{color:#155f9f}.tabs{display:flex;gap:5px;border-bottom:1px solid var(--line);margin-bottom:14px}.tab{border:0;border-bottom:2px solid transparent;padding:9px 11px;color:#718097;background:transparent;font-size:12px;font-weight:700}.tab.active{border-color:var(--brand);color:#146bb4}.filters{display:flex;gap:8px;margin-bottom:12px}.filters select{border:1px solid #d5dfe9;border-radius:7px;padding:7px 9px;color:var(--text);background:#fff}.progress{height:7px;border-radius:999px;background:#eaf0f6;overflow:hidden}.progress i{display:block;height:100%;border-radius:inherit;background:var(--brand)} .toast{position:fixed;right:24px;bottom:24px;z-index:20;max-width:380px;border-radius:9px;padding:11px 14px;color:#fff;background:#253c57;box-shadow:0 12px 30px rgba(20,37,60,.23);font-size:12px;opacity:0;transform:translateY(12px);pointer-events:none;transition:.18s}.toast.show{opacity:1;transform:translateY(0)}.overlay{position:fixed;inset:0;z-index:10;display:none;align-items:center;justify-content:center;padding:20px;background:rgba(19,32,49,.38)}.overlay.show{display:flex}.modal{width:min(480px,100%);border-radius:12px;background:#fff;box-shadow:0 24px 60px rgba(20,37,60,.28)}.modal h2{margin:0;padding:17px 18px 10px;color:var(--ink);font-size:16px}.modal p{margin:0;padding:0 18px;color:var(--muted);font-size:12px}.modal .body{padding:16px 18px}.modal input{width:100%;border:1px solid #d4dee9;border-radius:8px;padding:9px 10px}.modal .footer{display:flex;justify-content:flex-end;gap:8px;padding:12px 18px;border-top:1px solid var(--line)} + .precheck-meta{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:6px;color:var(--muted);font-size:12px}.precheck-meta .link{font-size:12px}.precheck-summary{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:14px}.transfer-precheck-table{min-width:1320px}.transfer-precheck-table th:nth-child(2){min-width:112px}.transfer-precheck-table th:nth-child(3){min-width:104px}.transfer-precheck-table th:nth-child(4){min-width:128px}.transfer-precheck-table th:nth-child(5){min-width:122px}.transfer-precheck-table th:nth-child(6){min-width:108px}.transfer-precheck-table th:nth-child(7),.transfer-precheck-table th:nth-child(9){min-width:138px}.transfer-precheck-table th:nth-child(8),.transfer-precheck-table th:nth-child(10){min-width:104px}.transfer-precheck-table th:nth-child(11){min-width:118px}.erp-document{margin-top:10px;border:1px solid var(--line);border-radius:9px;overflow:hidden}.erp-document:first-of-type{margin-top:0}.erp-document summary{display:grid;grid-template-columns:18px minmax(190px,1.25fr) minmax(150px,1fr) minmax(120px,.7fr) auto;gap:14px;align-items:center;padding:13px 15px;cursor:pointer;list-style:none}.erp-document summary::-webkit-details-marker{display:none}.erp-document summary::before{content:'›';color:#6d7d91;font-size:20px;transform:rotate(0deg);transition:transform .15s}.erp-document[open] summary::before{transform:rotate(90deg)}.erp-document summary b{display:block;color:var(--ink);font-size:13px}.erp-document summary span{display:block;margin-top:2px;color:var(--muted);font-size:11px}.erp-document .document-total{text-align:right}.erp-document .document-details{border-top:1px solid var(--line);padding:0 15px 13px;background:#fcfdff}.result-downloads{display:flex;flex-wrap:wrap;gap:8px;padding-top:14px;margin-top:14px;border-top:1px solid var(--line)}.result-downloads span{width:100%;color:var(--muted);font-size:11px} /* Chat 首页对齐当前 HXOPS Chat:深色画布、56px 顶栏、抽屉式历史记录与底部双行输入区。 */ .chat-mode{background:#020617;color:#cbd5e1}.chat-mode #app{background:#020617}.chat-mode .main{background:#020617}.chat-mode .topbar{display:flex;height:56px;gap:9px;padding:0 16px;border-color:#1e293b;background:#020617}.chat-mode .agent-icon{width:28px;height:28px;border-radius:8px;color:#e0f2fe;background:#2582ca;font-size:11px}.chat-mode .title{display:flex;align-items:center;gap:10px}.chat-mode .title b{color:#f8fafc;font-size:14px}.chat-mode .title span{display:none}.chat-mode .crumb{margin-left:0;border:1px solid #7dd3fc;border-radius:8px;padding:5px 10px;color:#0369a1;background:#e0f2fe;font-size:12px;font-weight:700}.chat-mode .chat-nav-actions{display:flex;align-items:center;gap:8px;margin-left:auto}.chat-mode .chat-nav-actions button{display:grid;place-items:center;width:32px;height:32px;border:0;border-radius:8px;color:#94a3b8;background:transparent;font-size:18px}.chat-mode .chat-nav-actions button:hover{color:#e2e8f0;background:#0f172a}.chat-mode .layout{overflow:hidden}.chat-mode .page{width:100%;height:100%;max-width:none;margin:0;padding:0}.chat-mode .side{position:fixed;top:0;bottom:0;left:0;z-index:30;display:flex;flex:0 0 296px;width:296px;min-width:296px;max-width:296px;transform:translateX(-100%);border-color:#1e293b;background:#0f172a;box-shadow:18px 0 44px rgba(0,0,0,.38);transition:transform .2s ease}.chat-mode.history-open .side{transform:translateX(0)}.chat-mode .brand{height:56px;border-color:#1e293b;padding:0 16px}.chat-mode .brand-mark{width:28px;height:28px;border-radius:8px;background:#2582ca;font-size:11px}.chat-mode .brand b{color:#f8fafc;font-size:14px}.chat-mode .brand span{color:#64748b}.chat-mode .new-chat{margin:12px;border-color:#1d4f78;border-radius:8px;color:#bae6fd;background:#082f49}.chat-mode .nav-label,.chat-mode .history-label{color:#64748b}.chat-mode .history-divider{background:#1e293b}.chat-mode .history button{color:#cbd5e1}.chat-mode .history button:hover{background:#172554}.chat-mode .history button.active{color:#e0f2fe;background:#0c4a6e}.chat-mode .history span{color:#64748b}.chat-mode .user{border-color:#1e293b}.chat-mode .user b{color:#e2e8f0}.chat-mode .user span{color:#64748b}.chat-mode .avatar{color:#bae6fd;background:#164e63}.chat-home{display:flex;height:100%;min-height:0;flex-direction:column;align-items:center}.chat-home-head{width:100%;max-width:920px;padding:67px 20px 17px;text-align:center}.chat-home-head .welcome-mark{display:none}.chat-home-head h1{margin:0;color:#f8fafc;font-size:29px;line-height:1.3}.chat-home-head h1 span{margin-left:6px;color:#7dd3fc}.chat-home-head p{display:none}.chat-todo-section{width:100%;max-width:760px;padding:0 16px 12px}.chat-todo-label{margin:0 0 8px;color:#94a3b8;font-size:12px;font-weight:700}.chat-today{display:flex;justify-content:center}.today-item{display:flex;align-items:center;gap:9px;width:auto;max-width:100%;border:1px solid #334155;border-radius:999px;padding:9px 14px;color:#cbd5e1;background:#0f172a;text-align:left}.today-item:hover{border-color:#7dd3fc;color:#e0f2fe;background:#172554}.today-item .today-icon{display:grid;place-items:center;width:18px;height:18px;flex:0 0 18px;border-radius:50%;color:#0c4a6e;background:#7dd3fc;font-size:15px;line-height:1}.today-item b{display:inline;color:inherit;font-size:13px}.today-item span{display:inline;margin:0;color:#94a3b8;font-size:12px}.today-item span span{display:none}.today-item .today-go{display:none}.chat-pending{display:flex;justify-content:center;gap:8px}.pending-item{display:flex;align-items:center;gap:6px;min-width:0;width:auto;border:1px solid #334155;border-radius:999px;padding:8px 12px;color:#cbd5e1;background:#0f172a;text-align:left}.pending-item:hover{border-color:#64748b;background:#172554}.pending-item.primary{border-color:#2c5572;background:#082f49}.pending-item b{display:inline;color:inherit;font-size:12px}.pending-item.primary b{color:#bae6fd}.pending-item span{display:none}.pending-item .pending-count{display:inline;margin:0;color:#7dd3fc;font-size:12px}.pending-item.warning .pending-count{color:#fbbf24}.pending-item.muted .pending-count{color:#94a3b8}.chat-thread{width:100%;max-width:760px;min-height:0;flex:1;overflow:auto;padding:36px 16px 154px}.chat-thread .bubble{max-width:82%;border:1px solid #1e293b;border-radius:6px 14px 14px;padding:11px 13px;color:#cbd5e1;background:#0f172a;box-shadow:none}.chat-thread .bubble.user-msg{margin-left:auto;border:0;border-radius:14px 5px 14px 14px;color:#eff6ff;background:#075985}.chat-thread .scope{border-color:#1e3a5f;border-radius:10px;color:#cbd5e1;background:#0b1327}.chat-thread .scope b{color:#bae6fd}.chat-thread .scope span{color:#94a3b8}.chat-thread .notice{border-radius:10px;color:#fcd34d;background:#2a1d05}.chat-action .btn{border-color:#0369a1;color:#e0f2fe;background:#075985}.chat-input-wrap{position:fixed;right:0;bottom:0;left:0;z-index:4;padding:0 14px 8px;background:#020617}.chat-input{display:block;width:min(760px,100%);margin:0 auto;border:0;border-radius:0;padding:0;background:#0f172a;box-shadow:none}.chat-input textarea{display:block;width:100%;min-height:42px;resize:none;border:0;outline:0;padding:10px 11px;color:#f8fafc;background:transparent;font-size:15px;line-height:1.45}.chat-input textarea::placeholder{color:#94a3b8}.chat-input-tools{display:flex;align-items:center;min-height:43px;padding:0 7px 5px}.chat-input-tools button{display:grid;place-items:center;width:32px;height:32px;border:0;border-radius:50%;color:#94a3b8;background:transparent;font-size:18px}.chat-input-tools button:hover{color:#e0f2fe;background:#1e293b}.chat-input-tools .kb-pill{display:flex;width:auto;gap:5px;border:1px solid #1e293b;border-radius:7px;padding:5px 8px;color:#64748b;background:#0b1222;font-size:11px}.chat-input-tools .send{margin-left:auto;border:1px solid #1e293b;color:#64748b;background:#0b1222}.chat-input-hint{width:min(760px,100%);margin:8px auto 0;text-align:center;color:#64748b;font-size:10px} /* 当前浏览器的浅色 Chat 基线:常驻会话栏、无业务顶栏、居中欢迎区和底部输入容器。 */ @@ -56,20 +57,20 @@ - - - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue deleted file mode 100644 index d2a730d5..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcNamedRegionBox.vue +++ /dev/null @@ -1,431 +0,0 @@ - - - - - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue deleted file mode 100644 index 6a14c10c..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingPanel.vue +++ /dev/null @@ -1,544 +0,0 @@ - - - - - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue deleted file mode 100644 index 951d7514..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSourceMappingSection.vue +++ /dev/null @@ -1,393 +0,0 @@ - - - - - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue deleted file mode 100644 index b084a50d..00000000 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/VcSplitRuleEditor.vue +++ /dev/null @@ -1,921 +0,0 @@ - - - - - - diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts index d3a8353b..dcae59d6 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts @@ -546,6 +546,28 @@ describe('XfaSplitRulePanel', () => { ]); }); + it('keeps advanced processing attached to a position matcher rule', async () => { + const ruleSet = makePipelineRuleSet({ + rules: [{ + ...makePipelineRuleSet().rules[0], + matcher: { type: 'position', line_index: 3 }, + }], + }); + const wrapper = mountPanel({ + definition: { ...baseDefinition, split_rules: [ruleSet] }, + }); + const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理')); + await advancedButton!.trigger('click'); + const addAdvanced = wrapper.find('.xfa-split__add-stage-select'); + await addAdvanced.setValue('extract_prefix'); + await addAdvanced.trigger('change'); + const emitted = wrapper.emitted('update:split-rules'); + const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules; + expect(last?.[0]?.rules[0]?.stages.map((stage) => stage.type)).toEqual([ + 'split_lines', 'select_line', 'extract_prefix', + ]); + }); + it('adds a rule after mounting when autoAddRule is enabled', () => { const wrapper = mountPanel({ autoAddRule: true, @@ -577,6 +599,73 @@ describe('XfaSplitRulePanel', () => { expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() })); }); + it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => { + previewMock.mockResolvedValue({ + preview: { status: 'ok', mapped_fields: {}, segments: [], evidence_only_segments: [], diagnostics: [] }, + }); + const wrapper = mountPanel({ + definition: { + ...baseDefinition, + split_rules: [makePipelineRuleSet({ + strategy: 'pipeline', + rules: [{ + ...makePipelineRuleSet().rules[0], + order: 3, + matcher: { type: 'position', line_index: 3 }, + stages: [ + { stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] }, + { stage_id: 'line', type: 'select_line', line_index: 3 }, + { stage_id: 'mpn', type: 'extract_prefix', value: 'MPN', separators: [':', ':'] }, + ], + }], + })], + }, + }); + + await exposedActions(wrapper).runPreview(); + await flushPromises(); + + expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ + rule_set: expect.objectContaining({ + rules: [expect.objectContaining({ + matcher: expect.objectContaining({ + type: 'position', + line_index: 3, + post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'], case_sensitive: false }], + }), + })], + }), + })); + const request = previewMock.mock.calls[0]?.[1] as { rule_set: Record }; + expect(request.rule_set).not.toHaveProperty('strategy'); + expect(request.rule_set.rules[0]).not.toHaveProperty('order'); + expect(request.rule_set.rules[0]).not.toHaveProperty('stages'); + }); + + it('reprojects saved formal post-processors into the advanced editor', async () => { + const wrapper = mountPanel({ + definition: { + ...baseDefinition, + split_rules: [makePipelineRuleSet({ + rules: [{ + ...makePipelineRuleSet().rules[0], + stages: [], + matcher: { + type: 'position', + line_index: 3, + post_processors: [{ type: 'prefix', value: 'MPN', separators: [':', ':'] }], + }, + }], + })], + }, + }); + + const advancedButton = wrapper.findAll('button').find((btn) => btn.text().includes('高级处理')); + await advancedButton!.trigger('click'); + + expect(wrapper.findAll('input').some((input) => input.element.value === 'MPN')).toBe(true); + }); + it('ignores exposed edit actions when canEdit is false', () => { const wrapper = mountPanel({ canEdit: false }); exposedActions(wrapper).addRule(); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue index 667cc195..511e03dd 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue @@ -2,8 +2,8 @@ features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.vue 用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。 依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。 - 逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 保留供 UI 与兼容预览; - 确认前须预览当前 rule_set 哈希;预览直接返回完整识别值。 + 逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 仅保留编辑态; + 预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希。 --> diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts index 1c2c554f..0ce28300 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts @@ -22,6 +22,7 @@ const i18n = createI18n({ lifecycle: { navigation: '订单生命周期阶段', current: '当前可处理', + processing: '处理中', completed: '已完成,可查看', blocked: '前置未完成', }, @@ -41,7 +42,7 @@ const stages: ReviewLifecycleStageItem[] = [ /** 挂载导航,复用真实 i18n 以覆盖状态文案渲染。 */ function mountNavigation() { return mount(ReviewLifecycleStageNavigation, { - props: { stages, activeCode: 'fulfillment_prep' }, + props: { stages, activeCode: 'fulfillment_prep', processingCode: 'fulfillment_prep' }, global: { plugins: [i18n] }, }); } @@ -102,6 +103,14 @@ describe('ReviewLifecycleStageNavigation', () => { expect(wrapper.emitted('select')).toEqual([['order_review']]); }); + it('shows a spinner and processing label on the active stage while automation runs', () => { + const wrapper = mountNavigation(); + const stage = wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]'); + expect(stage.attributes('data-processing')).toBe('1'); + expect(stage.text()).toContain('处理中'); + expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true); + }); + it('disables a future stage and does not emit a selection', async () => { const wrapper = mountNavigation(); const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]'); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue index 52e74a6e..ed6eb2da 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue @@ -5,7 +5,7 @@ 逻辑:用户可打开当前或已完成阶段查看;后续阶段由父级传入 blocked 并禁用,本组件不写业务状态。 -->