From c35223d49d211ba7d9913b782fd489bab1de1628 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 22 Jul 2026 18:52:43 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E6=B7=BB=E5=8A=A0=20M?= =?UTF-8?q?inerU=20=E8=AE=A2=E5=8D=95=E9=99=84=E4=BB=B6=E8=A1=A8=E6=A0=BC?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E5=8C=96=E5=8A=9F=E8=83=BD=EF=BC=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E7=8E=AF=E5=A2=83=E9=85=8D=E7=BD=AE=E5=92=8C=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E6=A8=A1=E5=9E=8B=E4=BB=A5=E6=94=AF=E6=8C=81=E6=96=B0?= =?UTF-8?q?=E5=B8=83=E5=B1=80=E8=A7=A3=E6=9E=90=E5=92=8C=E6=96=87=E6=A1=A3?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.dev | 12 + .env.prod | 12 + .env.test | 12 + backend/app/api/admin/__init__.py | 2 + .../api/admin/shipping_document_layouts.py | 40 + .../admin/shipping_order_document_profiles.py | 121 ++ .../api/admin/shipping_order_extraction.py | 83 ++ .../app/api/admin/shipping_order_schema.py | 9 + backend/app/api/workspace/shipping_notice.py | 30 + backend/app/core/config/settings.py | 31 + backend/app/jobs/handlers/__init__.py | 2 +- .../jobs/handlers/shipping_document_layout.py | 90 ++ .../handlers/shipping_order_extraction.py | 33 +- backend/app/jobs/queue.py | 6 + backend/app/jobs/types.py | 6 +- backend/app/models/__init__.py | 10 + backend/app/models/agent_runtime_binding.py | 5 +- backend/app/models/job.py | 17 + backend/app/models/shipping.py | 32 +- .../app/models/shipping_document_layout.py | 71 ++ .../models/shipping_order_document_profile.py | 69 ++ .../shipping_order_extraction_quality.py | 83 ++ .../models/shipping_order_extraction_run.py | 21 +- backend/app/models/shipping_order_schema.py | 6 +- .../services/agent_runtime_binding_service.py | 87 +- .../shipping_notice/batch_from_intakes.py | 4 + .../shipping_notice/candidate_service.py | 32 +- .../shipping_notice/context_fields/runtime.py | 5 + .../shipping_notice/decision_workflow.py | 31 +- .../document_candidate_persist.py | 44 +- .../document_layout/__init__.py | 38 + .../document_layout/evaluation.py | 147 ++- .../document_layout/html_layout.py | 119 ++ .../document_layout/html_table.py | 68 ++ .../document_layout/lifecycle.py | 405 +++++++ .../shipping_notice/document_layout/mineru.py | 161 ++- .../document_layout/native_pdf.py | 363 ++++++ .../document_layout/ocr_pdf.py | 154 +++ .../document_layout/order_profile.py | 13 +- .../document_layout/runtime.py | 238 ++++ .../document_layout/schema_mapping.py | 112 ++ .../document_layout/text_cell_alignment.py | 212 ++++ .../app/services/shipping_notice/eml_parse.py | 54 +- .../app/services/shipping_notice/extract.py | 4 +- .../order_document_profile_service.py | 525 ++++++++ .../shipping_notice/order_extraction.py | 88 +- .../shipping_notice/order_extraction_merge.py | 82 +- .../order_extraction_quality_service.py | 271 +++++ .../order_extraction_run_service.py | 258 +++- .../order_extraction_workflow.py | 502 ++++++-- .../shipping_notice/order_schema/runtime.py | 179 ++- .../shipping_notice/order_schema/service.py | 60 +- .../services/shipping_notice/queue_service.py | 16 +- .../shipping_notice/reservation_id.py | 24 +- ...68f8091a2b4_add_order_document_profiles.py | 94 ++ ...f8091a2b5_add_document_layout_lifecycle.py | 182 +++ ...6_add_order_observation_layout_evidence.py | 35 + ...1a2b7_add_order_extraction_quality_gate.py | 97 ++ ...e_quality_batch_on_order_extraction_run.py | 40 + ...move_order_extraction_contract_versions.py | 67 ++ ...remove_order_extraction_quality_binding.py | 41 + ...c0_add_order_extraction_reparse_lineage.py | 70 ++ ...091a2c1_merge_quality_and_reparse_heads.py | 28 + ...epair_order_schema_auto_creation_policy.py | 51 + ...c3_add_order_extraction_quality_binding.py | 46 + .../build_shipping_layout_truth_workbench.py | 291 +++++ .../test_admin_shipping_document_layouts.py | 59 + backend/tests/test_agent_runtime_bindings.py | 387 +++++- .../test_order_document_profile_migration.py | 58 + backend/tests/test_order_extraction_merge.py | 80 ++ ...est_shipping_document_layout_evaluation.py | 96 +- ...st_shipping_document_layout_html_layout.py | 69 ++ ...est_shipping_document_layout_html_table.py | 48 + .../test_shipping_document_layout_job.py | 106 ++ ...test_shipping_document_layout_lifecycle.py | 209 ++++ ...ing_document_layout_lifecycle_migration.py | 102 ++ .../test_shipping_document_layout_mineru.py | 37 + ...est_shipping_document_layout_native_pdf.py | 264 ++++ .../test_shipping_document_layout_ocr_pdf.py | 99 ++ .../test_shipping_document_layout_runtime.py | 152 +++ ...shipping_document_layout_schema_mapping.py | 169 +++ ...ing_document_layout_text_cell_alignment.py | 153 +++ .../test_shipping_layout_truth_workbench.py | 79 ++ backend/tests/test_shipping_notice_extract.py | 17 +- backend/tests/test_shipping_notice_intakes.py | 79 +- .../test_shipping_notice_inventory_aws.py | 12 +- .../test_shipping_notice_order_extraction.py | 75 +- .../test_shipping_notice_reservation_id.py | 12 +- backend/tests/test_shipping_notice_tools.py | 10 +- ...shipping_order_document_profile_service.py | 316 +++++ ...st_shipping_order_extraction_dify_guide.py | 120 ++ ..._shipping_order_extraction_quality_gate.py | 315 +++++ ...ping_order_extraction_quality_migration.py | 51 + ..._order_extraction_run_quality_migration.py | 87 ++ .../test_shipping_order_extraction_runs.py | 371 +++++- ...hipping_order_layout_evidence_migration.py | 54 + ...ng_order_schema_policy_repair_migration.py | 93 ++ .../test_shipping_order_schema_runtime.py | 199 ++- .../test_shipping_task_parsed_projection.py | 62 +- docs/demand.md | 19 +- docs/features/shipping-notice/business.md | 8 +- .../order-extraction-workflow-dify-guide.md | 371 +++++- .../pdf-order-truth-fill-form.md | 875 ++++++++++++++ docs/features/shipping-notice/technical.md | 168 ++- docs/funclist.md | 23 +- docs/tec.md | 21 +- docs/test_plan_matrix.md | 17 +- .../src/app/router/routes/admin.routes.ts | 8 + frontend/src/features/admin/api/admin.api.ts | 6 +- .../shipping-order-document-profile.api.ts | 74 ++ .../admin/api/shipping-order-schema.api.ts | 12 +- .../src/features/admin/constants/modules.ts | 5 +- .../agents/components/AgentFormModal.vue | 70 +- .../agents/composables/useAgentsAdmin.ts | 28 +- .../ShippingOrderDocumentProfilesPage.vue | 365 ++++++ .../orderProfileForm.utils.spec.ts | 48 + .../orderProfileForm.utils.ts | 42 + .../ShippingOrderSchemaPage.vue | 35 +- .../admin/shippingConfigNavigation.spec.ts | 9 +- .../src/features/admin/types/admin.types.ts | 2 +- .../src/features/admin/types/agent.types.ts | 42 +- .../shipping-order-document-profile.types.ts | 80 ++ .../types/shipping-order-schema.types.ts | 3 + .../src/features/chat/api/shipping.api.ts | 9 + .../features/chat/components/ChatInputBar.vue | 17 +- .../ShippingNoticeCandidateReview.vue | 15 - .../ShippingTaskParsedResultCard.vue | 3 + .../components/messages/ChatMessageBubble.vue | 58 + .../messages/shippingMessageHandlers.ts | 4 + .../chat/composables/useChatShipping.ts | 8 + .../chat/page/useChatPageHandlerBundles.ts | 8 + .../chat/shipping/useShippingNoticeIntakes.ts | 16 +- .../useShippingOrderExtractionRuns.spec.ts | 61 +- .../useShippingOrderExtractionRuns.ts | 94 +- .../src/features/chat/types/chat.types.ts | 9 + .../features/chat/types/shipping.api.types.ts | 9 +- frontend/src/locales/en/admin.json | 1032 +++++++++++++--- frontend/src/locales/en/chat.json | 15 +- frontend/src/locales/en/errors.json | 12 + frontend/src/locales/th/admin.json | 1039 +++++++++++++--- frontend/src/locales/th/chat.json | 15 +- frontend/src/locales/th/errors.json | 12 + frontend/src/locales/zh-CN/admin.json | 997 ++++++++++++---- frontend/src/locales/zh-CN/chat.json | 15 +- frontend/src/locales/zh-CN/errors.json | 12 + frontend/src/locales/zh-TW/admin.json | 1063 ++++++++++++++--- frontend/src/locales/zh-TW/chat.json | 15 +- frontend/src/locales/zh-TW/errors.json | 12 + 148 files changed, 15709 insertions(+), 1353 deletions(-) create mode 100644 backend/app/api/admin/shipping_document_layouts.py create mode 100644 backend/app/api/admin/shipping_order_document_profiles.py create mode 100644 backend/app/jobs/handlers/shipping_document_layout.py create mode 100644 backend/app/models/shipping_document_layout.py create mode 100644 backend/app/models/shipping_order_document_profile.py create mode 100644 backend/app/models/shipping_order_extraction_quality.py create mode 100644 backend/app/services/shipping_notice/document_layout/html_layout.py create mode 100644 backend/app/services/shipping_notice/document_layout/lifecycle.py create mode 100644 backend/app/services/shipping_notice/document_layout/native_pdf.py create mode 100644 backend/app/services/shipping_notice/document_layout/ocr_pdf.py create mode 100644 backend/app/services/shipping_notice/document_layout/runtime.py create mode 100644 backend/app/services/shipping_notice/document_layout/schema_mapping.py create mode 100644 backend/app/services/shipping_notice/document_layout/text_cell_alignment.py create mode 100644 backend/app/services/shipping_notice/order_document_profile_service.py create mode 100644 backend/app/services/shipping_notice/order_extraction_quality_service.py create mode 100644 backend/migrations/versions/a68f8091a2b4_add_order_document_profiles.py create mode 100644 backend/migrations/versions/a69f8091a2b5_add_document_layout_lifecycle.py create mode 100644 backend/migrations/versions/a70f8091a2b6_add_order_observation_layout_evidence.py create mode 100644 backend/migrations/versions/a71f8091a2b7_add_order_extraction_quality_gate.py create mode 100644 backend/migrations/versions/a72f8091a2b8_freeze_quality_batch_on_order_extraction_run.py create mode 100644 backend/migrations/versions/a73f8091a2b9_remove_order_extraction_contract_versions.py create mode 100644 backend/migrations/versions/a74f8091a2ba_remove_order_extraction_quality_binding.py create mode 100644 backend/migrations/versions/a74f8091a2c0_add_order_extraction_reparse_lineage.py create mode 100644 backend/migrations/versions/a75f8091a2c1_merge_quality_and_reparse_heads.py create mode 100644 backend/migrations/versions/a76f8091a2c2_repair_order_schema_auto_creation_policy.py create mode 100644 backend/migrations/versions/a77f8091a2c3_add_order_extraction_quality_binding.py create mode 100644 backend/scripts/build_shipping_layout_truth_workbench.py create mode 100644 backend/tests/test_admin_shipping_document_layouts.py create mode 100644 backend/tests/test_order_document_profile_migration.py create mode 100644 backend/tests/test_shipping_document_layout_html_layout.py create mode 100644 backend/tests/test_shipping_document_layout_job.py create mode 100644 backend/tests/test_shipping_document_layout_lifecycle.py create mode 100644 backend/tests/test_shipping_document_layout_lifecycle_migration.py create mode 100644 backend/tests/test_shipping_document_layout_native_pdf.py create mode 100644 backend/tests/test_shipping_document_layout_ocr_pdf.py create mode 100644 backend/tests/test_shipping_document_layout_runtime.py create mode 100644 backend/tests/test_shipping_document_layout_schema_mapping.py create mode 100644 backend/tests/test_shipping_document_layout_text_cell_alignment.py create mode 100644 backend/tests/test_shipping_layout_truth_workbench.py create mode 100644 backend/tests/test_shipping_order_document_profile_service.py create mode 100644 backend/tests/test_shipping_order_extraction_dify_guide.py create mode 100644 backend/tests/test_shipping_order_extraction_quality_gate.py create mode 100644 backend/tests/test_shipping_order_extraction_quality_migration.py create mode 100644 backend/tests/test_shipping_order_extraction_run_quality_migration.py create mode 100644 backend/tests/test_shipping_order_layout_evidence_migration.py create mode 100644 backend/tests/test_shipping_order_schema_policy_repair_migration.py create mode 100644 docs/features/shipping-notice/pdf-order-truth-fill-form.md create mode 100644 frontend/src/features/admin/api/shipping-order-document-profile.api.ts create mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts create mode 100644 frontend/src/features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.ts create mode 100644 frontend/src/features/admin/types/shipping-order-document-profile.types.ts diff --git a/.env.dev b/.env.dev index 4b178a68..945302d3 100644 --- a/.env.dev +++ b/.env.dev @@ -88,6 +88,18 @@ SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8 SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8 SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000 +# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭) +SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false +SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL= +SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10 +SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300 +SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4 +SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2 +SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000 +SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000 +SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360 +SHIPPING_NOTICE_LAYOUT_PARSER_REVISION=v3 SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 # 字段对齐确认(生产建议 true;测试可设 false) diff --git a/.env.prod b/.env.prod index f9ac1435..c3e7c311 100644 --- a/.env.prod +++ b/.env.prod @@ -78,6 +78,18 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true # 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥) SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 +# MinerU 订单附件表格结构化(服务地址由 Jenkins/系统环境注入,未配置时保持关闭) +SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false +SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL= +SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10 +SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300 +SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4 +SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2 +SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000 +SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000 +SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360 +SHIPPING_NOTICE_LAYOUT_PARSER_REVISION=v3 # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致) SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 diff --git a/.env.test b/.env.test index dbb2fc80..ac094996 100644 --- a/.env.test +++ b/.env.test @@ -98,6 +98,18 @@ SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8 SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8 SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000 +# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭) +SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true +SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.192:8100/ +SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10 +SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300 +SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4 +SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2 +SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000 +SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000 +SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360 +SHIPPING_NOTICE_LAYOUT_PARSER_REVISION=v3 SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 # 字段对齐确认(生产建议 true;测试可设 false) diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index 8ddbdae6..7731f9cc 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -24,5 +24,7 @@ import app.api.admin.shipping_customers # noqa: F401 import app.api.admin.shipping_identity_rules # noqa: F401 import app.api.admin.shipping_inventory # noqa: F401 import app.api.admin.shipping_order_schema # noqa: F401 +import app.api.admin.shipping_order_document_profiles # noqa: F401 +import app.api.admin.shipping_document_layouts # noqa: F401 __all__ = ['admin_bp'] diff --git a/backend/app/api/admin/shipping_document_layouts.py b/backend/app/api/admin/shipping_document_layouts.py new file mode 100644 index 00000000..8c73a588 --- /dev/null +++ b/backend/app/api/admin/shipping_document_layouts.py @@ -0,0 +1,40 @@ +""" +backend/app/api/admin/shipping_document_layouts.py + +用途:提供发货通知 Document 布局版本诊断和显式重解析管理员 API。 +依赖:admin blueprint、require_admin、document_layout.lifecycle。 +逻辑:响应只含状态/checksum/计数,不返回 HTML、bbox、正文或 Provider 原始输出。 +""" + +from __future__ import annotations + +from flask import g + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.response import ok +from app.services.shipping_notice.document_layout import lifecycle + + +def _actor_id() -> int | None: + """读取当前管理员主键。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +@admin_bp.route('/shipping-notice/documents//layout-versions', methods=['GET']) +@require_admin +def list_shipping_document_layout_versions(document_id: int): + """列出单个 Document 的布局解析版本安全摘要。""" + return ok( + lifecycle.list_layout_versions(document_id), request_id=getattr(g, 'request_id', None), + ) + + +@admin_bp.route('/shipping-notice/documents//layout-reparse', methods=['POST']) +@require_admin +def reparse_shipping_document_layout(document_id: int): + """显式创建或复用当前活动布局版本。""" + return ok( + lifecycle.request_layout_reparse(document_id, created_by_id=_actor_id()), + request_id=getattr(g, 'request_id', None), status=202, + ) diff --git a/backend/app/api/admin/shipping_order_document_profiles.py b/backend/app/api/admin/shipping_order_document_profiles.py new file mode 100644 index 00000000..7a26eefe --- /dev/null +++ b/backend/app/api/admin/shipping_order_document_profiles.py @@ -0,0 +1,121 @@ +""" +backend/app/api/admin/shipping_order_document_profiles.py + +用途:提供订单文档模板 Profile 的管理员版本治理 API。 +依赖:admin blueprint、require_admin、order_document_profile_service。 +逻辑:路由只转换请求和操作者;版本、Schema、字段及发布门禁全部由服务层执行。 +""" + +from __future__ import annotations + +from flask import g, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.response import ok +from app.services.shipping_notice import order_document_profile_service as service + + +def _actor_id() -> int | None: + """读取管理员身份。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _ok(data, *, status: int = 200): + """返回统一成功 envelope。""" + return ok(data, request_id=getattr(g, 'request_id', None), status=status) + + +@admin_bp.route('/shipping-notice/order-document-profiles', methods=['GET']) +@require_admin +def list_order_document_profiles(): + """列出全部模板 Profile 版本。""" + return _ok(service.list_profiles()) + + +@admin_bp.route('/shipping-notice/order-document-profile-samples', methods=['GET']) +@require_admin +def list_order_document_profile_samples(): + """列出可用于建立 Profile 的 MinerU 样本文档。""" + try: + limit = int(request.args.get('limit', '50')) + except ValueError as exc: + raise service.ValidationError( + 'limit is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) from exc + return _ok(service.list_sample_documents(limit=limit)) + + +@admin_bp.route('/shipping-notice/order-document-profile-samples//tables', methods=['GET']) +@require_admin +def get_order_document_profile_sample_tables(document_id: int): + """读取样本文档的结构化表格预览。""" + return _ok(service.get_sample_tables(document_id)) + + +@admin_bp.route('/shipping-notice/order-document-profiles/from-sample', methods=['POST']) +@require_admin +def create_order_document_profile_from_sample(): + """由真实样本和结构化列选择生成后端计算指纹的 Profile 草稿。""" + return _ok(service.create_draft_from_sample( + request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/order-document-profiles//from-sample', methods=['PUT']) +@require_admin +def update_order_document_profile_from_sample(profile_id: int): + """用新样本和乐观锁整体更新 Profile 草稿,不允许浏览器提供结构指纹。""" + return _ok(service.create_draft_from_sample( + request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id, + )) + + +@admin_bp.route('/shipping-notice/order-document-profiles', methods=['POST']) +@require_admin +def create_order_document_profile(): + """创建一个模板 Profile 草稿。""" + return _ok(service.save_draft( + request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/order-document-profiles/', methods=['PUT']) +@require_admin +def update_order_document_profile(profile_id: int): + """按乐观锁整体更新模板 Profile 草稿。""" + return _ok(service.save_draft( + request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id, + )) + + +@admin_bp.route('/shipping-notice/order-document-profiles//clone', methods=['POST']) +@require_admin +def clone_order_document_profile(profile_id: int): + """从发布/退役版本创建同编码下一草稿。""" + return _ok(service.clone_draft(profile_id, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/order-document-profiles//publish', methods=['POST']) +@require_admin +def publish_order_document_profile(profile_id: int): + """发布草稿并退役同模板旧版本。""" + data = request.get_json(silent=True) or {} + return _ok(service.publish( + profile_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'), + )) + + +@admin_bp.route('/shipping-notice/order-document-profiles//retire', methods=['POST']) +@require_admin +def retire_order_document_profile(profile_id: int): + """手工退役当前发布模板。""" + return _ok(service.retire(profile_id)) + + +@admin_bp.route('/shipping-notice/order-document-profiles/', methods=['DELETE']) +@require_admin +def delete_order_document_profile(profile_id: int): + """删除错误草稿。""" + service.delete_draft(profile_id) + return '', 204 diff --git a/backend/app/api/admin/shipping_order_extraction.py b/backend/app/api/admin/shipping_order_extraction.py index a27e52b4..bed097bd 100644 --- a/backend/app/api/admin/shipping_order_extraction.py +++ b/backend/app/api/admin/shipping_order_extraction.py @@ -8,6 +8,7 @@ backend/app/api/admin/shipping_order_extraction.py from flask import g, request +from app import db from app.api.admin.blueprint import admin_bp from app.core.decorators import require_admin from app.core.errors import ValidationError @@ -70,3 +71,85 @@ def get_shipping_order_extraction_diagnostic_run_detail(run_no: str): run_no=run_no, ) return ok(payload, request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['GET']) +@require_admin +def list_shipping_order_extraction_quality_batches(): + """列出指定 Owner 可用于自动建单门禁的已批准、仍达标批次。""" + owner_agent_id = _query_int('owner_agent_id', 0) + if owner_agent_id <= 0: + raise ValidationError('owner_agent_id must be positive') + from app.services.shipping_notice.order_extraction_quality_service import list_approved_quality_batches + + return ok( + list_approved_quality_batches(owner_agent_id=owner_agent_id), + request_id=getattr(g, 'request_id', None), + ) + + +@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['POST']) +@require_admin +def create_shipping_order_extraction_quality_batch(): + """创建 L7 影子验收批次;仅锁定 Owner/Schema,不复制任何订单内容。""" + body = request.get_json(silent=True) + if not isinstance(body, dict): + raise ValidationError('JSON body must be an object') + try: + owner_agent_id = int(body.get('owner_agent_id')) + schema_version_id = int(body.get('schema_version_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('owner_agent_id and schema_version_id are required') from exc + from app.services.shipping_notice.order_extraction_quality_service import ( + create_quality_batch, serialize_quality_batch, + ) + + batch = create_quality_batch( + owner_agent_id=owner_agent_id, schema_version_id=schema_version_id, + actor_id=g.current_user.id, + ) + return ok( + serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None), status=201, + ) + + +@admin_bp.route('/shipping-notice/order-extraction-quality-batches/', methods=['GET']) +@require_admin +def get_shipping_order_extraction_quality_batch(batch_id: int): + """读取批次脱敏指标和批准状态,不返回 Run 内容、订单值或单条标签。""" + from app.models import ShippingOrderExtractionQualityBatch + from app.services.shipping_notice.order_extraction_quality_service import serialize_quality_batch + + batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id) + if batch is None: + from app.core.errors import NotFoundError + raise NotFoundError('Quality batch not found') + return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route('/shipping-notice/order-extraction-quality-batches//runs//label', methods=['PUT']) +@require_admin +def label_shipping_order_extraction_quality_run(batch_id: int, run_no: str): + """提交当前管理员的匿名质量标签;同管理员重提为幂等覆盖。""" + from app.services.shipping_notice.order_extraction_quality_service import save_quality_label, serialize_quality_batch + + batch = save_quality_label( + batch_id=batch_id, run_no=run_no, actor_id=g.current_user.id, + payload=request.get_json(silent=True), + ) + return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None)) + + +@admin_bp.route('/shipping-notice/order-extraction-quality-batches//approve', methods=['POST']) +@require_admin +def approve_shipping_order_extraction_quality_batch(batch_id: int): + """提交 business/technical 批准;同一管理员不能承担两个角色。""" + body = request.get_json(silent=True) + if not isinstance(body, dict): + raise ValidationError('JSON body must be an object') + from app.services.shipping_notice.order_extraction_quality_service import approve_quality_batch, serialize_quality_batch + + batch = approve_quality_batch( + batch_id=batch_id, role=str(body.get('role') or ''), actor_id=g.current_user.id, + ) + return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None)) diff --git a/backend/app/api/admin/shipping_order_schema.py b/backend/app/api/admin/shipping_order_schema.py index 8ecf159d..f8b5c754 100644 --- a/backend/app/api/admin/shipping_order_schema.py +++ b/backend/app/api/admin/shipping_order_schema.py @@ -33,6 +33,15 @@ def get_shipping_order_schema(): return _ok(service.get_state()) +@admin_bp.route('/shipping-order-schema/auto-creation-policy', methods=['GET', 'PUT']) +@require_admin +def shipping_order_auto_creation_policy(): + """读取或更新订单解析自动建单总开关;字段阈值由 Schema 草稿维护。""" + if request.method == 'GET': + return _ok(service.get_auto_creation_policy()) + return _ok(service.save_auto_creation_policy(request.get_json(silent=True) or {}, actor_id=_actor_id())) + + @admin_bp.route('/shipping-order-schema', methods=['POST']) @require_admin def initialize_shipping_order_schema(): diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 37ed6257..2c933df2 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -956,6 +956,36 @@ def workspace_retry_shipping_order_extraction_run(run_no: str): ) +@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs//reparse', methods=['POST']) +def workspace_reparse_shipping_order_extraction_run(run_no: str): + """ + 使用当前发布规则重新识别一个终态订单抽取 Run。 + + 核心逻辑:只接收受控原因与可选备注,服务层复用原始 Intake 创建新的版本化 Run; + 不复用失败重试的冻结 Provider 缓存,也不允许前端传入 Schema、Binding 或附件内容。 + """ + user = _require_user() + body = request.get_json(silent=True) + if not isinstance(body, dict): + raise ValidationError('Request body must be an object') + from app.services.shipping_notice.order_extraction_run_service import ( + reparse_order_extraction_run, + serialize_order_extraction_run, + ) + + run, reused = reparse_order_extraction_run( + user_id=user.id, + run_no=run_no, + reason=str(body.get('reason') or ''), + comment=str(body.get('comment') or '') or None, + ) + db.session.commit() + return ok( + {'run': serialize_order_extraction_run(run), 'reused': reused}, + request_id=getattr(g, 'request_id', None), status=202, + ) + + @workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET']) def workspace_list_shipping_order_extraction_runs(): """列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 25521b70..7697b7fc 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -462,6 +462,37 @@ class Config: os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300') ) SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6') + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv( + 'SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', 'false' + ).lower() == 'true' + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL = os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL', '').strip() + SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS', '10') + ) + SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', '300') + ) + SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', '4') + ) + SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', '2') + ) + SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', str(1_000_000)) + ) + SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', str(2_000_000)) + ) + SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS', '3') + ) + SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS = int( + os.getenv('SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', '360') + ) + SHIPPING_NOTICE_LAYOUT_PARSER_REVISION = os.getenv( + 'SHIPPING_NOTICE_LAYOUT_PARSER_REVISION', 'v3' + ).strip() or 'v3' # EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本) # parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析 # parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文 diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index e71ffbd9..8153e8ac 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py 逻辑:Wave 2 起在 worker 启动前 import 本包。 """ -from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401 +from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_document_layout, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401 diff --git a/backend/app/jobs/handlers/shipping_document_layout.py b/backend/app/jobs/handlers/shipping_document_layout.py new file mode 100644 index 00000000..dcca5b68 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_document_layout.py @@ -0,0 +1,90 @@ +""" +backend/app/jobs/handlers/shipping_document_layout.py + +用途:独立执行单份 ShippingNoticeDocument 的 MinerU 布局解析任务。 +依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue。 +逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本。 +""" + +from __future__ import annotations + +from app.extensions import db +from app.jobs.context import JobContext +from app.jobs.queue import fail_job, finish_job +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import FileAsset, Job, ShippingDocumentLayoutVersion +from app.services.file_assets.service import read_asset_bytes +from app.services.shipping_notice.document_layout.lifecycle import ( + claim_layout_version, + complete_layout_version, + sync_layout_after_job_failure, +) +from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot + + +LAYOUT_JOB_ERROR = 'shipping_document_layout_provider_failed' + + +@register_handler(JobType.SHIPPING_DOCUMENT_LAYOUT) +def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None: + """ + 执行单文档布局任务;Job 和版本均使用相同 attempt 代次条件收口。 + + Args: + ctx: Worker 上下文,用于记录仅运维可见的异常堆栈。 + payload: 通用队列载荷,只读取 job_id;布局版本 ID 从冻结 Job 载荷读取。 + + Returns: + None。成功时同时完成布局版本与 Job;失败时按通用重试策略重新排队。 + """ + raw_job_id = payload.get('job_id') + job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None + if job is None: + return + owned_attempt = int(job.attempts or 0) + version_id = int((job.payload_json or {}).get('layout_version_id') or 0) + version = db.session.get(ShippingDocumentLayoutVersion, version_id) if version_id else None + if version is None: + fail_job(job.id, error='layout version not found', retryable=False, owned_attempt=owned_attempt) + return + if version.status in {'ready', 'needs_review', 'failed', 'unsupported'}: + finish_job(job.id, result={'status': version.status, 'skipped': True}, owned_attempt=owned_attempt) + return + claimed = claim_layout_version(version.id, job_id=job.id, owned_attempt=owned_attempt) + if claimed is None: + finish_job(job.id, result={'status': 'stale', 'skipped': True}, owned_attempt=owned_attempt) + return + version, lease = claimed + try: + document = version.document + asset = db.session.get(FileAsset, int(document.asset_id or 0)) + if asset is None: + raise ValueError('layout document asset is unavailable') + snapshot = build_mineru_table_snapshot( + filename=str(document.filename or asset.original_filename or 'document.pdf'), + content=read_asset_bytes(asset), + document_id=document.id, + content_hash=document.content_hash, + ) + if snapshot is None: + snapshot = { + 'snapshot_version': version.contract_version, + 'provider': version.parser_name, 'backend': version.backend, + 'status': 'unsupported', 'tables': [], + 'issues': ['shipping_document_layout_input_unsupported'], + } + if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot): + finish_job( + job.id, result={'status': str(snapshot.get('status') or 'failed')}, + message='文档版面解析完成', owned_attempt=owned_attempt, + ) + except Exception as exc: + db.session.rollback() + if ctx.logger is not None: + ctx.logger.exception( + 'shipping_document_layout_failed job_id=%s version_id=%s', job.id, version.id, + ) + fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt) + sync_layout_after_job_failure(job.id) + raise diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 814a639a..ff02d10a 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -2,8 +2,9 @@ backend/app/jobs/handlers/shipping_order_extraction.py 用途:消费订单抽取领域 Run,调用显式绑定的 Dify Workflow 并持久化订单结果。 -依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机。 -逻辑:Job 只承载执行尝试;Run 是业务真相。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。 +依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机、provider_guard。 +逻辑:Job 只承载执行尝试;Run 是业务真相。线程快照须含 provider_config_json/schema_version_id; +仅 Dify 传输类失败累计熔断。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。 """ from __future__ import annotations @@ -50,12 +51,22 @@ from app.services.shipping_notice.order_extraction_provider_guard import ( ) +# 仅 Dify 传输类失败累计熔断;本地编程错误与 CIRCUIT_OPEN 自身不得拉长冷却窗。 +_PROVIDER_CIRCUIT_FAILURE_CODES = frozenset({ + 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT', + 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED', +}) + + def _execute_dify_unit_with_retry( *, app, run_snapshot: dict, unit_snapshot: dict, provider_snapshot: dict, timeout_seconds: int, max_attempts: int, backoff_ms: int, job_id: int, job_attempt: int, provider_max_concurrency: int, circuit_failure_threshold: int, circuit_cooldown_seconds: int, ) -> dict: - """在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。""" + """在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。 + + 核心逻辑:熔断仅统计 Dify 超时/请求失败;本地异常与 CIRCUIT_OPEN 不拉长冷却。 + """ last_error: Exception | None = None started = time.perf_counter() for attempt in range(1, max_attempts + 1): @@ -84,7 +95,8 @@ def _execute_dify_unit_with_retry( except Exception as exc: last_error = exc retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False)) - if retryable: + # [STEP] 仅传输类 Provider 失败累计熔断,避免本地异常或开路自身延长冷却。 + if isinstance(exc, AppError) and getattr(exc, 'code', None) in _PROVIDER_CIRCUIT_FAILURE_CODES: record_provider_failure( int(provider_snapshot['id']), threshold=circuit_failure_threshold, cooldown_seconds=circuit_cooldown_seconds, @@ -180,7 +192,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: run.attempt_count = owned_attempt db.session.commit() - timeout_seconds = int((run.provider_config_json or {}).get('timeout_seconds') or 900) + run_config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {} + if bool(run_config.get('auto_create_enabled')): + from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch + + require_approved_quality_batch( + batch_id=run.quality_batch_id, + owner_agent_id=int(run.owner_agent_id), + schema_version_id=int(run.schema_version_id), + ) + timeout_seconds = int(run_config.get('timeout_seconds') or 900) saved_provider_result = run.provider_result_json if isinstance(run.provider_result_json, dict) else {} saved_orders = saved_provider_result.get('orders') if isinstance(saved_orders, list) and all(isinstance(item, dict) for item in saved_orders): @@ -243,8 +264,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: with ThreadPoolExecutor(max_workers=min(concurrency, len(dify_units) or 1)) as pool: run_snapshot = { 'id': run.id, 'run_no': run.run_no, 'user_id': run.user_id, + 'schema_version_id': run.schema_version_id, 'input_snapshot_hash': run.input_snapshot_hash, 'input_snapshot_json': run.input_snapshot_json, + 'provider_config_json': run.provider_config_json, } provider_snapshot = { 'id': provider.id, 'api_base_url': provider.api_base_url, diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py index 04d628aa..2287149c 100644 --- a/backend/app/jobs/queue.py +++ b/backend/app/jobs/queue.py @@ -983,6 +983,12 @@ def process_next_job( ) on_recovered = sync_order_extraction_run_after_job_recovery + elif normalized_type == JobType.SHIPPING_DOCUMENT_LAYOUT.value: + from app.services.shipping_notice.document_layout.lifecycle import ( + sync_layout_after_job_recovery, + ) + + on_recovered = sync_layout_after_job_recovery recover_stale_jobs( domain=domain, timeout_seconds=timeout_seconds, diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 267866a0..16715dac 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -17,6 +17,7 @@ class JobType(StrEnum): SHIPPING_NOTICE_RUN = 'shipping_notice_run' SHIPPING_NOTICE_PARSE = 'shipping_notice_parse' SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' + SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SCHEDULE_RUN = 'schedule_run' FILE_CHECK_RUN = 'file_check_run' WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' @@ -50,7 +51,10 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = { # worker --queues 参数 → 可消费的 KbJob.job_type 集合 QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'kb': frozenset({'clean', 'path_upload', 'sync_dify'}), - 'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction'}), + 'shipping': frozenset({ + 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', + 'shipping_document_layout', + }), } diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index e50035d1..3129903d 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -52,6 +52,8 @@ from app.models.shipping_order_extraction_run import ( ShippingOrderExtractionRunIntake, ShippingOrderExtractionUnit, ) +from app.models.shipping_order_document_profile import ShippingOrderDocumentProfile +from app.models.shipping_document_layout import ShippingDocumentLayoutVersion from app.models.shipping_inventory_config import ( ShippingInventoryField, ShippingInventoryExternalMapping, @@ -80,6 +82,10 @@ from app.models.shipping_customer import ( ) from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution +from app.models.shipping_order_extraction_quality import ( + ShippingOrderExtractionQualityBatch, + ShippingOrderExtractionQualityLabel, +) from app.models.shipping_identity_rule import ( ShippingIdentityDefinition, ShippingIdentityEvidence, @@ -144,6 +150,10 @@ __all__ = [ 'ShippingOrderExtractionUnit', 'ShippingOrderExtractionProgressEvent', 'ShippingOrderExtractionDiagnosticAudit', + 'ShippingOrderExtractionQualityBatch', + 'ShippingOrderExtractionQualityLabel', + 'ShippingOrderDocumentProfile', + 'ShippingDocumentLayoutVersion', 'ShippingCustomer', 'ShippingCustomerIdentifier', 'ShippingCustomerExternalRef', diff --git a/backend/app/models/agent_runtime_binding.py b/backend/app/models/agent_runtime_binding.py index 07c70ac3..d8b772c4 100644 --- a/backend/app/models/agent_runtime_binding.py +++ b/backend/app/models/agent_runtime_binding.py @@ -3,7 +3,7 @@ backend/app/models/agent_runtime_binding.py 用途:定义用户入口 Agent 到内部运行能力 Provider 的显式绑定。 依赖:agents 表。 -逻辑:业务代码只按 owner_agent_id + capability_code 解析 Provider;Dify App ID、Key 和 URL 继续由 Provider Agent 保存。 +逻辑:业务代码按 owner_agent_id + capability_code 解析 Provider;执行策略仅保存通用超时与重试参数。 """ from __future__ import annotations @@ -34,6 +34,9 @@ class AgentRuntimeBinding(Base): ForeignKey('agents.id'), nullable=False, index=True, ) enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default='1', nullable=False) + quality_batch_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True, + ) config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) diff --git a/backend/app/models/job.py b/backend/app/models/job.py index 9ff66112..dd7b4a60 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -65,6 +65,23 @@ class Job(Base): "AND business_ref IS NOT NULL" ), ), + Index( + 'uq_jobs_shipping_document_layout_active_ref', + 'domain', + 'job_type', + 'business_ref', + unique=True, + postgresql_where=text( + "job_type = 'shipping_document_layout' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + sqlite_where=text( + "job_type = 'shipping_document_layout' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + ), ) id: Mapped[int] = mapped_column(primary_key=True) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 607649e7..c7cbf328 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -509,6 +509,15 @@ class ShippingNoticeDocument(Base): parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False) extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + current_layout_version_id: Mapped[Optional[int]] = mapped_column( + ForeignKey( + 'shipping_document_layout_versions.id', + name='fk_shipping_notice_documents_current_layout_version', + ondelete='SET NULL', + use_alter=True, + ), + nullable=True, + ) order_extraction_status: Mapped[str] = mapped_column( String(32), default='not_started', @@ -522,6 +531,19 @@ class ShippingNoticeDocument(Base): order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, 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) + current_layout_version = relationship( + 'ShippingDocumentLayoutVersion', + foreign_keys=[current_layout_version_id], + post_update=True, + ) + layout_versions = relationship( + 'ShippingDocumentLayoutVersion', + foreign_keys='ShippingDocumentLayoutVersion.document_id', + back_populates='document', + cascade='all, delete-orphan', + ) + + class ShippingNoticeCandidate(Base): """ 订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。 @@ -533,7 +555,10 @@ class ShippingNoticeCandidate(Base): __tablename__ = 'shipping_notice_candidates' __table_args__ = ( UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'), - UniqueConstraint('intake_id', 'candidate_key', name='uq_shipping_notice_candidates_intake_key'), + UniqueConstraint( + 'intake_id', 'candidate_key', 'order_extraction_run_id', + name='uq_shipping_notice_candidates_intake_key_run', + ), # 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接 ForeignKeyConstraint( ['primary_document_id', 'intake_id'], @@ -566,6 +591,11 @@ class ShippingNoticeCandidate(Base): order_extraction_run_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True, ) + # 仅当前版本候选可进入建单;旧版本保留为只读审计和重新识别失败时的回退依据。 + is_current_version: Mapped[bool] = mapped_column( + Boolean, default=True, server_default=text('true'), nullable=False, index=True, + ) + selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) diff --git a/backend/app/models/shipping_document_layout.py b/backend/app/models/shipping_document_layout.py new file mode 100644 index 00000000..525893c9 --- /dev/null +++ b/backend/app/models/shipping_document_layout.py @@ -0,0 +1,71 @@ +""" +backend/app/models/shipping_document_layout.py + +用途:持久化每份发货通知 Document 的版本化版面解析生命周期、冻结快照和质量结果。 +依赖:shipping_notice_documents、jobs、SQLAlchemy Base。 +逻辑:同一 Document 版本递增;运行租约隔离旧 Worker,只有成功版本可成为 Document 当前布局。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingDocumentLayoutVersion(Base): + """单文档版面解析版本;payload/checksum 一旦完成即不可原地改写。""" + + __tablename__ = 'shipping_document_layout_versions' + __table_args__ = ( + UniqueConstraint('document_id', 'version', name='uq_shipping_document_layout_document_version'), + CheckConstraint( + "status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')", + name='ck_shipping_document_layout_status', + ), + Index('ix_shipping_document_layout_document_status', 'document_id', 'status'), + Index('ix_shipping_document_layout_content_parser', 'source_content_hash', 'parser_key'), + Index( + 'uq_shipping_document_layout_one_active', + 'document_id', + unique=True, + postgresql_where=text("status IN ('queued', 'running')"), + sqlite_where=text("status IN ('queued', 'running')"), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + document_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_documents.id', ondelete='CASCADE'), nullable=False, + ) + version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(24), default='queued', server_default='queued', nullable=False) + source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False) + parser_key: Mapped[str] = mapped_column(String(128), nullable=False) + parser_name: Mapped[str] = mapped_column(String(32), nullable=False) + parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + backend: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + contract_version: Mapped[str] = mapped_column(String(64), nullable=False) + payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + payload_size_bytes: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False) + quality_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + issues_json: Mapped[list] = mapped_column(JSON, default=list, nullable=False) + job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True) + lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + document = relationship( + 'ShippingNoticeDocument', foreign_keys=[document_id], back_populates='layout_versions', + ) + job = relationship('Job', foreign_keys=[job_id]) diff --git a/backend/app/models/shipping_order_document_profile.py b/backend/app/models/shipping_order_document_profile.py new file mode 100644 index 00000000..ead4e752 --- /dev/null +++ b/backend/app/models/shipping_order_document_profile.py @@ -0,0 +1,69 @@ +""" +backend/app/models/shipping_order_document_profile.py + +用途:保存订单文档模板解析 Profile 的草稿、不可变发布版本及 Schema 绑定。 +依赖:shipping_order_schema_versions、users、SQLAlchemy Base。 +逻辑:同一模板编码按版本递增;发布版本冻结结构指纹、固定列规则和稳定字段 ID,Run 再复制完整快照。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingOrderDocumentProfile(Base): + """版本化订单文档模板解析配置;published/retired 行不可原地修改。""" + + __tablename__ = 'shipping_order_document_profiles' + __table_args__ = ( + UniqueConstraint('profile_code', 'version', name='uq_shipping_order_document_profiles_code_version'), + CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_shipping_order_document_profiles_status', + ), + Index('ix_shipping_order_document_profiles_schema_status', 'schema_version_id', 'status'), + Index('ix_shipping_order_document_profiles_fingerprint', 'structure_fingerprint'), + Index( + 'uq_shipping_order_document_profiles_one_published', + 'profile_code', + unique=True, + postgresql_where=text("status = 'published'"), + sqlite_where=text("status = 'published'"), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + profile_code: Mapped[str] = mapped_column(String(64), nullable=False) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + schema_version_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_schema_versions.id'), nullable=False, + ) + structure_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False) + definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + source_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_document_profiles.id'), nullable=True, + ) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + schema_version = relationship('ShippingOrderSchemaVersion') + source_profile: Mapped[Optional['ShippingOrderDocumentProfile']] = relationship( + remote_side='ShippingOrderDocumentProfile.id', foreign_keys=[source_profile_id], + ) diff --git a/backend/app/models/shipping_order_extraction_quality.py b/backend/app/models/shipping_order_extraction_quality.py new file mode 100644 index 00000000..86962e4e --- /dev/null +++ b/backend/app/models/shipping_order_extraction_quality.py @@ -0,0 +1,83 @@ +""" +backend/app/models/shipping_order_extraction_quality.py + +用途:保存订单抽取 L7 影子验收批次、双人匿名标签和双角色批准事实。 +依赖:Agent、User、ShippingOrderSchemaVersion、ShippingOrderExtractionRun。 +逻辑:批次锁定 owner/schema/阈值;同 Run 两名管理员标签一致后计入指标,达标后双人批准供 Runtime Binding 门禁引用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingOrderExtractionQualityBatch(Base): + """L7 影子验收批次;批准后成为不可变自动建单发布凭证。""" + + __tablename__ = 'shipping_order_extraction_quality_batches' + __table_args__ = ( + UniqueConstraint('batch_no', name='uq_shipping_order_extraction_quality_batches_no'), + CheckConstraint( + "status IN ('collecting', 'ready', 'approved', 'rejected')", + name='ck_shipping_order_extraction_quality_batches_status', + ), + Index('ix_shipping_order_extraction_quality_batches_owner_created', 'owner_agent_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + batch_no: Mapped[str] = mapped_column(String(64), nullable=False) + owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True) + schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) + threshold_version: Mapped[str] = mapped_column(String(32), nullable=False, default='l7.v1', server_default='l7.v1') + status: Mapped[str] = mapped_column(String(32), nullable=False, default='collecting', server_default='collecting') + created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False) + business_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + business_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + technical_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + technical_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + rejected_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + rejected_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + rejection_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + labels: Mapped[list['ShippingOrderExtractionQualityLabel']] = relationship( + back_populates='batch', cascade='all, delete-orphan', order_by='ShippingOrderExtractionQualityLabel.id', + ) + + +class ShippingOrderExtractionQualityLabel(Base): + """单个管理员对真实 Run 提交的匿名质量计数;不保存订单字段值或正文。""" + + __tablename__ = 'shipping_order_extraction_quality_labels' + __table_args__ = ( + UniqueConstraint('batch_id', 'run_id', 'reviewer_id', name='uq_shipping_order_quality_label_reviewer'), + CheckConstraint('core_expected_count >= 0', name='ck_shipping_order_quality_expected_nonnegative'), + CheckConstraint('core_extracted_count >= 0', name='ck_shipping_order_quality_extracted_nonnegative'), + CheckConstraint('core_correct_count >= 0', name='ck_shipping_order_quality_correct_nonnegative'), + Index('ix_shipping_order_quality_labels_batch_run', 'batch_id', 'run_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + batch_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False, + ) + run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id'), nullable=False) + reviewer_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False) + core_expected_count: Mapped[int] = mapped_column(Integer, nullable=False) + core_extracted_count: Mapped[int] = mapped_column(Integer, nullable=False) + core_correct_count: Mapped[int] = mapped_column(Integer, nullable=False) + wrong_merge: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false') + wrong_split: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false') + wrong_auto_create: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false') + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + batch: Mapped['ShippingOrderExtractionQualityBatch'] = relationship(back_populates='labels') diff --git a/backend/app/models/shipping_order_extraction_run.py b/backend/app/models/shipping_order_extraction_run.py index 5dba3edc..fd90ea28 100644 --- a/backend/app/models/shipping_order_extraction_run.py +++ b/backend/app/models/shipping_order_extraction_run.py @@ -3,7 +3,7 @@ backend/app/models/shipping_order_extraction_run.py 用途:定义建单前订单抽取的领域运行记录及其冻结 Intake 集合。 依赖:agents、users、jobs、shipping_notice_intakes、shipping_order_schema_versions。 -逻辑:Run 保存用户可见生命周期和不可变输入快照;通用 Job 只承担执行尝试,Candidate/Extraction 通过 run_id 回溯本次运行。 +逻辑:Run 保存用户可见生命周期和不可变输入快照;自动建单策略随 Schema 快照冻结。 """ from __future__ import annotations @@ -65,8 +65,21 @@ class ShippingOrderExtractionRun(Base): provider_agent_id: Mapped[Optional[int]] = mapped_column( ForeignKey('agents.id'), nullable=True, index=True, ) + quality_batch_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True, + ) provider_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) provider_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + # 重新识别创建新 Run;谱系字段保留旧结果,禁止用原地覆盖破坏审计事实。 + reparse_of_run_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True, + ) + superseded_by_run_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True, + ) + reparse_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + reparse_comment: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True) schema_version_id: Mapped[int] = mapped_column( ForeignKey('shipping_order_schema_versions.id'), nullable=False, @@ -108,6 +121,12 @@ class ShippingOrderExtractionRun(Base): intakes: Mapped[list['ShippingOrderExtractionRunIntake']] = relationship( back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRunIntake.position', ) + reparse_source: Mapped[Optional['ShippingOrderExtractionRun']] = relationship( + 'ShippingOrderExtractionRun', foreign_keys=[reparse_of_run_id], remote_side='ShippingOrderExtractionRun.id', + ) + superseding_run: Mapped[Optional['ShippingOrderExtractionRun']] = relationship( + 'ShippingOrderExtractionRun', foreign_keys=[superseded_by_run_id], remote_side='ShippingOrderExtractionRun.id', + ) extraction_plan: Mapped[Optional['ShippingOrderExtractionPlan']] = relationship( back_populates='run', cascade='all, delete-orphan', uselist=False, ) diff --git a/backend/app/models/shipping_order_schema.py b/backend/app/models/shipping_order_schema.py index 29314032..2295688e 100644 --- a/backend/app/models/shipping_order_schema.py +++ b/backend/app/models/shipping_order_schema.py @@ -55,6 +55,8 @@ class ShippingOrderSchema(Base): schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) display_name: Mapped[str] = mapped_column(String(128), nullable=False) description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + # 自动建单是订单解析的运行策略,不属于不可变字段模板版本。 + auto_creation_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) @@ -240,7 +242,7 @@ class ShippingOrderLine(Base): class ShippingOrderFieldObservation(Base): - """某字段来自某 Document/解析器的原始观察及可回查证据。""" + """某字段来自某 Document/解析器的原始观察及可回查文本或版面证据。""" __tablename__ = 'shipping_order_field_observations' __table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),) @@ -255,6 +257,8 @@ class ShippingOrderFieldObservation(Base): raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True) + evidence_metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True) evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false')) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/services/agent_runtime_binding_service.py b/backend/app/services/agent_runtime_binding_service.py index 2e1ec608..7fa0a583 100644 --- a/backend/app/services/agent_runtime_binding_service.py +++ b/backend/app/services/agent_runtime_binding_service.py @@ -17,6 +17,13 @@ from app.services.agent_registry.catalog import get_catalog_entry from app.services.agent_registry.resolver import resolve_effective_role +_EXECUTOR_GOVERNANCE_DEFAULTS = { + 'provider_max_concurrency': 4, + 'circuit_failure_threshold': 5, + 'circuit_cooldown_seconds': 60, +} + + def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]: """读取 owner Agent Catalog 中声明的能力定义;未声明能力不可由管理员任意绑定。""" entry = get_catalog_entry(owner.agent_code) or {} @@ -37,13 +44,7 @@ def _normalize_config(raw: Any) -> dict[str, Any]: raw = {} if not isinstance(raw, dict): raise ValidationError('config must be an object', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') - unknown = set(raw) - { - 'timeout_seconds', 'max_attempts', 'unit_concurrency', - 'unit_max_attempts', 'unit_retry_backoff_ms', - 'max_model_units', 'provider_max_concurrency', - 'circuit_failure_threshold', 'circuit_cooldown_seconds', - 'auto_create_enabled', - } + unknown = set(raw) - {'timeout_seconds', 'max_attempts', 'auto_create_enabled'} if unknown: raise ValidationError( 'Unsupported runtime binding config keys', @@ -53,14 +54,6 @@ def _normalize_config(raw: Any) -> dict[str, Any]: try: timeout_seconds = int(raw.get('timeout_seconds', 900)) max_attempts = int(raw.get('max_attempts', 3)) - unit_concurrency = int(raw.get('unit_concurrency', 2)) - unit_max_attempts = int(raw.get('unit_max_attempts', 2)) - unit_retry_backoff_ms = int(raw.get('unit_retry_backoff_ms', 500)) - max_model_units = int(raw.get('max_model_units', 20)) - provider_max_concurrency = int(raw.get('provider_max_concurrency', 4)) - circuit_failure_threshold = int(raw.get('circuit_failure_threshold', 5)) - circuit_cooldown_seconds = int(raw.get('circuit_cooldown_seconds', 60)) - auto_create_enabled = raw.get('auto_create_enabled', False) except (TypeError, ValueError) as exc: raise ValidationError( 'Runtime binding execution settings must be integers', @@ -71,34 +64,34 @@ def _normalize_config(raw: Any) -> dict[str, Any]: 'Runtime binding config is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', ) - if not 2 <= unit_concurrency <= 4 or not 1 <= unit_max_attempts <= 3: - raise ValidationError( - 'Runtime binding unit concurrency/attempts are outside allowed limits', - code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', - ) - if not 100 <= unit_retry_backoff_ms <= 5000: - raise ValidationError( - 'Runtime binding unit retry backoff is outside allowed limits', - code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', - ) - if not 1 <= max_model_units <= 100 or not 1 <= provider_max_concurrency <= 20: - raise ValidationError('Runtime binding provider budget is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') - if not 2 <= circuit_failure_threshold <= 20 or not 10 <= circuit_cooldown_seconds <= 600: - raise ValidationError('Runtime binding circuit settings are outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') - if not isinstance(auto_create_enabled, bool): - raise ValidationError('Runtime binding auto-create gate must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') - return { + result = { 'timeout_seconds': timeout_seconds, 'max_attempts': max_attempts, - 'unit_concurrency': unit_concurrency, - 'unit_max_attempts': unit_max_attempts, - 'unit_retry_backoff_ms': unit_retry_backoff_ms, - 'max_model_units': max_model_units, - 'provider_max_concurrency': provider_max_concurrency, - 'circuit_failure_threshold': circuit_failure_threshold, - 'circuit_cooldown_seconds': circuit_cooldown_seconds, - 'auto_create_enabled': auto_create_enabled, } + if 'auto_create_enabled' in raw: + if not isinstance(raw['auto_create_enabled'], bool): + raise ValidationError('auto_create_enabled must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') + result['auto_create_enabled'] = raw['auto_create_enabled'] + return result + + +def resolve_executor_governance(provider: Agent) -> dict[str, int]: + """读取内部执行器全局治理,供新 Run 冻结并避免入口应用绕过 Provider 保护。""" + raw_extra = provider.extra_config if isinstance(provider.extra_config, dict) else {} + raw = raw_extra.get('order_extraction_governance') if isinstance(raw_extra.get('order_extraction_governance'), dict) else {} + try: + config = { + 'provider_max_concurrency': int(raw.get('provider_max_concurrency', _EXECUTOR_GOVERNANCE_DEFAULTS['provider_max_concurrency'])), + 'circuit_failure_threshold': int(raw.get('circuit_failure_threshold', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_failure_threshold'])), + 'circuit_cooldown_seconds': int(raw.get('circuit_cooldown_seconds', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_cooldown_seconds'])), + } + except (TypeError, ValueError) as exc: + raise ValidationError('Internal executor governance settings must be integers', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') from exc + if not 1 <= config['provider_max_concurrency'] <= 20: + raise ValidationError('Internal executor concurrency is outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') + if not 2 <= config['circuit_failure_threshold'] <= 20 or not 10 <= config['circuit_cooldown_seconds'] <= 600: + raise ValidationError('Internal executor circuit settings are outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') + return config def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None: @@ -145,6 +138,7 @@ def serialize_runtime_binding(binding: AgentRuntimeBinding) -> dict[str, Any]: 'is_active': provider.is_active, } if provider else None, 'enabled': bool(binding.enabled), + 'quality_batch_id': binding.quality_batch_id, 'config': dict(binding.config_json or {}), } @@ -166,10 +160,11 @@ def save_runtime_binding( capability_code: str, provider_agent_id: int, enabled: bool, + quality_batch_id: int | None = None, config: Any, commit: bool = True, ) -> AgentRuntimeBinding: - """创建或更新能力绑定;owner/provider 必须是不同 Agent 且满足 Catalog 约束。""" + """创建或更新能力绑定;开启自动建单时必须引用已批准质量批次。""" owner = db.session.get(Agent, owner_agent_id) provider = db.session.get(Agent, provider_agent_id) if owner is None or provider is None: @@ -181,6 +176,15 @@ def save_runtime_binding( if enabled: _validate_provider(provider, definition) normalized_config = _normalize_config(config) + if code == 'shipping.order_extraction' and normalized_config.get('auto_create_enabled'): + from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch + from app.services.shipping_notice.order_schema.runtime import published_version + + require_approved_quality_batch( + batch_id=quality_batch_id, + owner_agent_id=owner.id, + schema_version_id=int(published_version().id), + ) binding = AgentRuntimeBinding.query.filter_by( owner_agent_id=owner.id, capability_code=code, ).first() @@ -189,6 +193,7 @@ def save_runtime_binding( db.session.add(binding) binding.provider_agent_id = provider.id binding.enabled = bool(enabled) + binding.quality_batch_id = int(quality_batch_id) if quality_batch_id is not None else None binding.config_json = normalized_config if commit: db.session.commit() diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py index 2087f625..b4c7d3a0 100644 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -560,6 +560,7 @@ def create_shipping_batch_from_candidates( .filter( ShippingNoticeCandidate.candidate_no.in_(candidate_nos), ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]), + ShippingNoticeCandidate.is_current_version.is_(True), ) .order_by(ShippingNoticeCandidate.id.asc()) .with_for_update() @@ -582,6 +583,7 @@ def create_shipping_batch_from_candidates( ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]), ShippingNoticeCandidate.selected.is_(True), ShippingNoticeCandidate.consumed_task_id.is_(None), + ShippingNoticeCandidate.is_current_version.is_(True), ) .all() ) @@ -612,6 +614,8 @@ def create_shipping_batch_from_candidates( raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期') if not candidate.selected: raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中') + if not candidate.is_current_version: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代') if candidate.consumed_task_id is not None: raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费') if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json: diff --git a/backend/app/services/shipping_notice/candidate_service.py b/backend/app/services/shipping_notice/candidate_service.py index 08c6f399..b5b85b29 100644 --- a/backend/app/services/shipping_notice/candidate_service.py +++ b/backend/app/services/shipping_notice/candidate_service.py @@ -66,11 +66,30 @@ def _refresh_candidate(candidate: ShippingNoticeCandidate, intake: ShippingNotic return result +def _append_manual_review_history( + structured: dict[str, Any], *, user_id: int, before_summary: dict[str, Any], + before_conflicts: list[Any], before_status: str, after_summary: dict[str, Any], +) -> None: + """追加不可变人工修订快照,保留规则/LLM 结果被人工更正前的审核依据。""" + history = list(structured.get('manual_review_history') or []) + history.append({ + 'action': 'business_summary_edited', + 'actor_user_id': int(user_id), + 'edited_at': datetime.utcnow().isoformat(), + 'before_summary': before_summary, + 'before_conflicts': before_conflicts, + 'before_validation_status': before_status, + 'after_summary': after_summary, + }) + structured['manual_review_history'] = history + + def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = None, business_summary: dict[str, Any] | None = None) -> dict[str, Any]: """ 更新候选选择状态或人工修订后的业务摘要。 - 核心逻辑:已消费候选禁止修改;摘要变化时清除冲突、置 ready 并重算双指纹与判重。 + 核心逻辑:已消费候选禁止修改;人工摘要通过统一校验后保留修订前快照, + 再清除已人工处理的冲突、置 ready 并重算双指纹与判重。 """ candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True) if candidate.consumed_task_id is not None or intake.parse_status == 'consumed': @@ -84,6 +103,17 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象') normalized_summary = normalize_candidate_business_summary(business_summary) structured = dict(candidate.structured_result_json or {}) + before_summary = dict(structured.get('business_summary') or {}) + before_conflicts = list(candidate.conflicts_json or []) + before_status = str(candidate.validation_status or '') + _append_manual_review_history( + structured, + user_id=user_id, + before_summary=before_summary, + before_conflicts=before_conflicts, + before_status=before_status, + after_summary=normalized_summary, + ) structured['business_summary'] = normalized_summary structured['manual_edited'] = True candidate.structured_result_json = structured diff --git a/backend/app/services/shipping_notice/context_fields/runtime.py b/backend/app/services/shipping_notice/context_fields/runtime.py index a2646d72..f47d0731 100644 --- a/backend/app/services/shipping_notice/context_fields/runtime.py +++ b/backend/app/services/shipping_notice/context_fields/runtime.py @@ -87,6 +87,7 @@ def persist_deterministic_context_fields( 'id': decision.id, 'field_id': field_id, 'field_code': field_code, 'line_id': None, 'status': decision.decision_status, 'value': value, 'reason_code': decision.reason_code, 'observation_ids': list(decision.supporting_observation_ids_json or []), + 'confidence': 1.0 if value is not None else 0.0, }) continue @@ -99,6 +100,8 @@ def persist_deterministic_context_fields( extraction_id=extraction.id, line_id=None, field_id=field_id, source_document_id=None, source_type='mail_header', extractor='deterministic_context', raw_value_json=value, normalized_value_json=value, evidence_quote=None, + evidence_ref=f'mail_header:{option_key}', + evidence_metadata_json={'kind': 'mail_header', 'option_key': option_key}, confidence=Decimal('1.0000'), evidence_verified=True, ) db.session.add(observation) @@ -123,6 +126,7 @@ def persist_deterministic_context_fields( 'id': observation.id, 'field_id': field_id, 'line_id': None, 'source_type': 'mail_header', 'document_id': None, 'value': value, 'evidence_verified': True, + 'evidence_ref': observation.evidence_ref, 'evidence_kind': 'mail_header', }) elif config.get('required'): blocked.append(field_code) @@ -130,5 +134,6 @@ def persist_deterministic_context_fields( 'id': decision.id, 'field_id': field_id, 'field_code': field_code, 'line_id': None, 'status': status, 'value': value, 'reason_code': reason, 'observation_ids': list(decision.supporting_observation_ids_json or []), + 'confidence': 1.0 if observation is not None else 0.0, }) return header, observations, decisions, blocked diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index a1797de7..44042dc4 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -11,7 +11,7 @@ from __future__ import annotations from typing import Any from app import db -from app.models import ShippingTaskInventoryLink +from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingTaskInventoryLink from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, CP_PARSE_OK, @@ -371,12 +371,37 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: ) return match_result - # [STEP 4] Task 不再回退到旧 Chatflow 重新抽取;只有 Intake Run 可以执行订单识别。 + # [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。 if decision == "reparse": + candidate = ( + db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id)) + if task.source_candidate_id else None + ) + source_run_id = candidate.order_extraction_run_id if candidate is not None else None + if source_run_id: + from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run + + run = db.session.get(ShippingOrderExtractionRun, source_run_id) + if run is not None: + replacement, reused = reparse_order_extraction_run( + user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None, + ) + log_task_action_event( + task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment, + extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused}, + ) + db.session.commit() + return tool_response( + status="needs_human", task=task, + message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。", + data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no}, + checkpoint=task.review_status or "parse_review", stop_agent_turn=True, + forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], + ) return tool_response( status="needs_human", task=task, - message="订单重新识别必须从原始发货通知重新上传并创建后台识别任务。", + message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。", data=serialize_task_for_tool(task), checkpoint=task.review_status or "parse_review", stop_agent_turn=True, diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index d22ec10c..8964c480 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -157,6 +157,7 @@ def _upsert_document( warnings: list[str], asset_id: int | None, classification: str, + layout_snapshot: dict[str, Any] | None = None, ) -> ShippingNoticeDocument: row = ( db.session.query(ShippingNoticeDocument) @@ -184,6 +185,10 @@ def _upsert_document( row.classification = classification row.updated_at = datetime.utcnow() db.session.flush() + if isinstance(layout_snapshot, dict): + from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot + + record_inline_layout_snapshot(row, layout_snapshot) # 按 Document→Asset 关联边增减引用,避免「已 referenced」跳过 +1 导致漏计多文档共用 new_asset_id = int(asset_id) if asset_id else None if previous_asset_id and previous_asset_id != new_asset_id: @@ -460,6 +465,8 @@ def persist_documents_and_candidates( # [STEP 1] 正文 Document:仅邮件级上下文,不生成 Candidate if is_eml: + html_tables = email_meta.pop('body_html_tables', []) + canonical_html_tables = [str(item) for item in html_tables if str(item).strip()] body_summary = parse_intake_business_summary( extracted_text=body_text, source_type='email', @@ -472,7 +479,11 @@ def persist_documents_and_candidates( parse_status='parsed' if body_text.strip() else 'empty', business_summary=body_summary, ) - body_hash = hashlib.sha256(body_text.encode('utf-8')).hexdigest().lower() if body_text else None + body_hash_source = '\x1f'.join([body_text, *canonical_html_tables]).strip('\x1f') + body_hash = ( + hashlib.sha256(body_hash_source.encode('utf-8')).hexdigest().lower() + if body_hash_source else None + ) body_doc = _upsert_document( intake=intake, attachment_key=BODY_ATTACHMENT_KEY, @@ -485,6 +496,29 @@ def persist_documents_and_candidates( asset_id=None, classification=body_class, ) + if canonical_html_tables and body_doc.content_hash: + from app.services.shipping_notice.document_layout.html_layout import ( + build_html_layout_candidate, + ) + from app.services.shipping_notice.document_layout.lifecycle import ( + record_inline_layout_snapshot, + ) + + layout = build_html_layout_candidate( + document_id=int(body_doc.id), content_hash=str(body_doc.content_hash), + tables=canonical_html_tables, + ) + record_inline_layout_snapshot( + body_doc, + { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'eml-html-dom', 'provider_version': 'v1', + 'backend': 'html', 'status': 'needs_review', + 'tables': [], 'layout_candidate': layout.model_dump(mode='json'), + 'issues': [item.code for item in layout.quality.issues], + }, + parser_key='eml-html-dom:shipping_document_layout.v1:v1', + ) active_keys.add(BODY_ATTACHMENT_KEY) documents.append(body_doc) @@ -549,6 +583,7 @@ def persist_documents_and_candidates( parse_status=att_status, extracted_text=att_text or None, warnings=[str(w) for w in (item.get('warnings') or [])], + layout_snapshot=item.get('layout_snapshot') if isinstance(item.get('layout_snapshot'), dict) else None, asset_id=asset_id, classification=classification, ) @@ -612,6 +647,7 @@ def persist_documents_and_candidates( parse_status='parsed', extracted_text=str(result.text or '') or None, warnings=list(result.warnings or []), + layout_snapshot=meta.get('layout_snapshot') if isinstance(meta.get('layout_snapshot'), dict) else None, asset_id=int(parent_asset.id), classification=file_class, ) @@ -682,11 +718,17 @@ def persist_documents_and_candidates( strip_attachment_payloads(meta) db.session.flush() + from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts + + layout_versions = schedule_document_layouts( + documents, created_by_id=int(intake.user_id) if intake.user_id else None, + ) return { 'document_count': len(documents), 'candidate_count': len(candidates), 'linked_asset_count': linked_asset_count, 'created_asset_count': created_asset_count, + 'layout_version_count': len(layout_versions), 'documents': [_serialize_document_brief(d, include_text=False) for d in documents], 'candidates': [_serialize_candidate_brief(c) for c in candidates], } diff --git a/backend/app/services/shipping_notice/document_layout/__init__.py b/backend/app/services/shipping_notice/document_layout/__init__.py index 49b5879f..436d0d3a 100644 --- a/backend/app/services/shipping_notice/document_layout/__init__.py +++ b/backend/app/services/shipping_notice/document_layout/__init__.py @@ -45,6 +45,29 @@ from app.services.shipping_notice.document_layout.html_table import ( map_html_table_to_schema, parse_html_grid, ) +from app.services.shipping_notice.document_layout.text_cell_alignment import ( + PositionedCharacter, + TextAlignedCell, + TextCellAlignmentResult, + align_html_cells_from_positioned_text, +) +from app.services.shipping_notice.document_layout.native_pdf import ( + NativePdfPage, + build_native_pdf_layout_candidate, + extract_native_pdf_pages, +) +from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate +from app.services.shipping_notice.document_layout.ocr_pdf import ( + OcrCellEvidence, + OcrLine, + OcrTableEvidence, + build_ocr_table_evidence, + extract_ocr_lines, +) +from app.services.shipping_notice.document_layout.schema_mapping import ( + layout_table_to_grid, + map_layout_document_to_schema, +) __all__ = [ 'LAYOUT_SCHEMA_VERSION', @@ -67,6 +90,21 @@ __all__ = [ 'MinerUClientConfig', 'MinerUParseCandidate', 'MinerUTextCandidate', + 'PositionedCharacter', + 'TextAlignedCell', + 'TextCellAlignmentResult', + 'NativePdfPage', + 'build_native_pdf_layout_candidate', + 'extract_native_pdf_pages', + 'build_html_layout_candidate', + 'OcrCellEvidence', + 'OcrLine', + 'OcrTableEvidence', + 'build_ocr_table_evidence', + 'extract_ocr_lines', + 'layout_table_to_grid', + 'map_layout_document_to_schema', + 'align_html_cells_from_positioned_text', 'canonical_layout_checksum', 'evaluate_layout', 'inspect_mineru_capabilities', diff --git a/backend/app/services/shipping_notice/document_layout/evaluation.py b/backend/app/services/shipping_notice/document_layout/evaluation.py index 7de2ea4c..42a93264 100644 --- a/backend/app/services/shipping_notice/document_layout/evaluation.py +++ b/backend/app/services/shipping_notice/document_layout/evaluation.py @@ -1,9 +1,10 @@ """ backend/app/services/shipping_notice/document_layout/evaluation.py -用途:定义版面解析人工真值格式并计算阶段 L0/L2/L3 的表格与单元格质量指标。 +用途:定义版面和 PDF 订单行人工真值格式,并计算阶段 L0/L2/L3 的质量指标与安全门禁。 依赖:Pydantic 2、document_layout.contracts。 -逻辑:人工标注保存期望表格/单元格位置;候选解析结果按页与几何交并比匹配,输出可审计指标而非业务订单值。 +逻辑:人工标注保存期望表格/单元格位置及订单行事实;候选解析结果按页与几何交并比匹配, +再由匿名聚合指标验证删除项和高风险字段不会被错误自动放行。 """ from __future__ import annotations @@ -19,6 +20,15 @@ from app.services.shipping_notice.document_layout.contracts import ( ANNOTATION_SCHEMA_VERSION = 'shipping_document_layout_annotation.v1' +PDF_ORDER_TRUTH_SCHEMA_VERSION = 'shipping_pdf_order_truth.v1' +REQUIRED_PDF_ORDER_SAMPLE_CATEGORIES = frozenset({ + 'normal_multi_line', 'continued_row', 'deleted_line', 'cross_page_header', + 'scanned_ocr', 'unreadable_pdf', +}) +HIGH_RISK_PDF_ORDER_FIELDS = frozenset({ + 'line_no', 'part_number', 'customer_part_number', 'aws_part_number', + 'reservation_id', 'qty', 'unit_price', 'amount', 'required_date', +}) class LayoutAnnotationModel(BaseModel): @@ -27,6 +37,139 @@ class LayoutAnnotationModel(BaseModel): model_config = ConfigDict(extra='forbid', validate_assignment=True) +class AnnotatedOrderField(LayoutAnnotationModel): + """保存一项高风险订单字段真值及其版面单元格证据引用。""" + + field_code: str = Field(min_length=1, max_length=80) + value: str | int | float + evidence_cell_ids: list[str] = Field(min_length=1) + + @model_validator(mode='after') + def validate_high_risk_evidence(self) -> 'AnnotatedOrderField': + """高风险字段必须能回指至少一个人工确认的版面单元格。""" + if self.field_code not in HIGH_RISK_PDF_ORDER_FIELDS: + raise ValueError('order truth may only contain high-risk field codes') + if len(self.evidence_cell_ids) != len(set(self.evidence_cell_ids)): + raise ValueError('order field evidence_cell_ids must be unique') + return self + + +class AnnotatedOrderLine(LayoutAnnotationModel): + """记录视觉行块、删除归属及可自动放行前必须校验的订单字段真值。""" + + line_id: str = Field(min_length=1, max_length=160) + table_annotation_id: str = Field(min_length=1, max_length=160) + line_cell_ids: list[str] = Field(min_length=1) + status: str = Field(pattern=r'^(active|deleted|needs_review)$') + fields: list[AnnotatedOrderField] = Field(default_factory=list) + deletion_marker_cell_id: str | None = None + + @model_validator(mode='after') + def validate_line_status(self) -> 'AnnotatedOrderLine': + """删除项必须有独立删除证据;待复核项不能被伪装成可放行字段。""" + if len(self.line_cell_ids) != len(set(self.line_cell_ids)): + raise ValueError('order line cell ids must be unique') + if self.status == 'deleted' and not self.deletion_marker_cell_id: + raise ValueError('deleted order line requires deletion_marker_cell_id') + if self.status != 'deleted' and self.deletion_marker_cell_id: + raise ValueError('only deleted order line may reference deletion marker') + codes = [item.field_code for item in self.fields] + if len(codes) != len(set(codes)): + raise ValueError('order line field codes must be unique') + return self + + +class PdfOrderTruthAnnotation(LayoutAnnotationModel): + """保存脱敏 PDF 订单真值,驱动行重建、删除归属和自动放行的阶段 Review。""" + + schema_version: str = PDF_ORDER_TRUTH_SCHEMA_VERSION + sample_id: str = Field(min_length=1, max_length=160) + content_hash: str = Field(pattern=r'^[0-9a-f]{64}$') + categories: list[str] = Field(min_length=1) + lines: list[AnnotatedOrderLine] = Field(min_length=1) + + @model_validator(mode='after') + def validate_pdf_order_truth(self) -> 'PdfOrderTruthAnnotation': + """保证样本类别、行标识和删除项审计引用在真值录入时即可发现错误。""" + if self.schema_version != PDF_ORDER_TRUTH_SCHEMA_VERSION: + raise ValueError('unsupported PDF order truth schema_version') + if len(self.categories) != len(set(self.categories)): + raise ValueError('PDF order truth categories must be unique') + line_ids = [item.line_id for item in self.lines] + if len(line_ids) != len(set(line_ids)): + raise ValueError('PDF order truth line ids must be unique') + return self + + +class PdfOrderQualityMetrics(LayoutAnnotationModel): + """汇总脱敏真值集的行级结果,不包含 PDF 原文、字段值或用户身份。""" + + active_truth_lines: int = Field(ge=0) + deleted_truth_lines: int = Field(ge=0) + active_lines_auto_released: int = Field(ge=0) + active_lines_misdeleted: int = Field(ge=0) + high_risk_auto_released_fields: int = Field(ge=0) + incorrect_high_risk_auto_released_fields: int = Field(ge=0) + unreliable_truth_lines: int = Field(ge=0) + unreliable_lines_sent_to_review: int = Field(ge=0) + + @model_validator(mode='after') + def validate_metric_totals(self) -> 'PdfOrderQualityMetrics': + """拒绝分子大于分母的指标,避免用无效数据错误开启自动放行。""" + if self.active_lines_misdeleted > self.active_truth_lines: + raise ValueError('misdeleted active lines exceed active truth lines') + if self.incorrect_high_risk_auto_released_fields > self.high_risk_auto_released_fields: + raise ValueError('incorrect high-risk fields exceed auto-released fields') + if self.unreliable_lines_sent_to_review > self.unreliable_truth_lines: + raise ValueError('reviewed unreliable lines exceed unreliable truth lines') + return self + + +class PdfOrderQualityGate(LayoutAnnotationModel): + """表达安全优先的 PDF 自动放行结论及其不可绕过的失败原因。""" + + passed: bool + reasons: list[str] + + +def review_pdf_order_quality_gate( + annotations: list[dict | PdfOrderTruthAnnotation], + metrics: dict | PdfOrderQualityMetrics, +) -> PdfOrderQualityGate: + """ + 审查 PDF 订单 IDP 的阶段质量门禁。 + + 核心逻辑:要求六类脱敏真值样本齐全;并强制有效行零误删、高风险自动放行字段零错误、 + 所有不可靠行均已转人工复核。覆盖率不设最低值,避免为提高自动化比例降低安全边界。 + + Args: + annotations: 业务确认的 PDF 订单真值;每个样本仅保存 hash、类别和脱敏行事实。 + metrics: 对同一真值集计算的匿名行级质量计数。 + + Returns: + PdfOrderQualityGate: passed 为 True 才允许后续阶段尝试自动放行。 + """ + truth = [ + item if isinstance(item, PdfOrderTruthAnnotation) else PdfOrderTruthAnnotation.model_validate(item) + for item in annotations + ] + quality = metrics if isinstance(metrics, PdfOrderQualityMetrics) else PdfOrderQualityMetrics.model_validate(metrics) + reasons: list[str] = [] + if not truth: + reasons.append('pdf_order_truth_set_missing') + categories = {category for item in truth for category in item.categories} + missing_categories = sorted(REQUIRED_PDF_ORDER_SAMPLE_CATEGORIES - categories) + if missing_categories: + reasons.append(f"pdf_order_truth_categories_missing:{','.join(missing_categories)}") + if quality.active_lines_misdeleted: + reasons.append('active_order_line_misdeleted') + if quality.incorrect_high_risk_auto_released_fields: + reasons.append('incorrect_high_risk_field_auto_released') + if quality.unreliable_lines_sent_to_review != quality.unreliable_truth_lines: + reasons.append('unreliable_order_line_not_sent_to_review') + return PdfOrderQualityGate(passed=not reasons, reasons=reasons) + + class AnnotatedCell(LayoutAnnotationModel): """记录人工确认的单元格位置、列归属和可选业务字段,不保存邮件身份信息。""" diff --git a/backend/app/services/shipping_notice/document_layout/html_layout.py b/backend/app/services/shipping_notice/document_layout/html_layout.py new file mode 100644 index 00000000..678678c7 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/html_layout.py @@ -0,0 +1,119 @@ +""" +backend/app/services/shipping_notice/document_layout/html_layout.py + +用途:把 EML 正文中受控 HTML table 转换为统一 shipping_document_layout.v1 逻辑布局候选。 +依赖:BeautifulSoup HTML 网格解析、布局契约。 +逻辑:DOM 直接证明 rowspan/colspan;坐标仅表示逻辑行列,不冒充屏幕像素,结果固定 needs_review。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.document_layout.contracts import ( + LayoutBBox, + LayoutCell, + LayoutDocument, + LayoutIssue, + LayoutPage, + LayoutParserInfo, + LayoutQuality, + LayoutRow, + LayoutTable, + normalize_layout_text, + stable_layout_id, +) +from app.services.shipping_notice.document_layout.html_table import parse_html_grid + + +def build_html_layout_candidate( + *, document_id: int, content_hash: str, tables: list[str], +) -> LayoutDocument: + """ + 将已清洗 HTML 表格列表转换为逻辑坐标布局。 + + Args: + document_id: email_body Document 主键。 + content_hash: 正文文本哈希,用于稳定对象 ID。 + tables: 只包含 table/tr/th/td 及跨度属性的清洗片段。 + Returns: + DOM 行列可追溯但没有浏览器像素证据的 needs_review 布局。 + """ + parsed = [] + issues: list[LayoutIssue] = [LayoutIssue( + code='html_logical_coordinates_only', severity='blocking', page_no=1, + )] + for index, html in enumerate(tables): + table_ref = stable_layout_id('html-source-table', content_hash, index) + try: + parsed.append((index, parse_html_grid(html, table_id=table_ref))) + except Exception: + issues.append(LayoutIssue( + code='html_table_invalid', severity='blocking', page_no=1, + table_id=table_ref, + )) + page_width = float(max((grid.column_count for _index, grid in parsed), default=1)) + page_height = float(max( + sum(grid.row_count for _index, grid in parsed) + max(len(parsed) - 1, 0), 1, + )) + offset = 0.0 + layout_tables: list[LayoutTable] = [] + for table_index, grid in parsed: + table_id = stable_layout_id('table', content_hash, 1, table_index) + table_bbox = LayoutBBox( + x0=0, y0=offset, x1=float(grid.column_count), y1=offset + grid.row_count, + ) + rows: list[LayoutRow] = [] + for row_index in range(grid.row_count): + source_cells = [item for item in grid.cells if item.row_index == row_index] + if not source_cells: + continue + role = 'header' if all(item.is_header for item in source_cells) else 'data' + cells = [] + for source in sorted(source_cells, key=lambda item: item.column_index): + bbox = LayoutBBox( + x0=float(source.column_index), y0=offset + source.row_index, + x1=float(source.column_index + source.column_span), + y1=offset + source.row_index + source.row_span, + ) + cells.append(LayoutCell( + cell_id=stable_layout_id( + 'cell', content_hash, 1, table_index, + source.row_index, source.column_index, + ), + row_index=source.row_index, column_index=source.column_index, + row_span=source.row_span, column_span=source.column_span, + text=source.text, normalized_text=normalize_layout_text(source.text), + bbox=bbox, + normalized_bbox=_normalized(bbox, page_width, page_height), + source='html', confidence=1, role=role, + )) + rows.append(LayoutRow( + row_id=stable_layout_id('row', content_hash, 1, table_index, row_index), + row_index=row_index, cells=cells, role=role, + )) + layout_tables.append(LayoutTable( + table_id=table_id, bbox=table_bbox, + normalized_bbox=_normalized(table_bbox, page_width, page_height), + rows=rows, + header_row_indices=[item.row_index for item in rows if item.role == 'header'], + confidence=1, status='needs_review', + )) + offset += grid.row_count + 1 + if not layout_tables: + issues.append(LayoutIssue(code='html_table_structure_missing', severity='blocking', page_no=1)) + return LayoutDocument( + document_id=document_id, content_hash=content_hash, + parser=LayoutParserInfo(name='eml-html-dom', version='v1'), + pages=[LayoutPage( + page_no=1, width=page_width, height=page_height, + tokens=[], tables=layout_tables, + )], + quality=LayoutQuality(status='needs_review', confidence=0, issues=issues), + ) + + +def _normalized(bbox: LayoutBBox, width: float, height: float) -> LayoutBBox: + """将 DOM 逻辑网格坐标转换为 0..1。""" + return LayoutBBox( + x0=bbox.x0 / width, y0=bbox.y0 / height, + x1=bbox.x1 / width, y1=bbox.y1 / height, + ) diff --git a/backend/app/services/shipping_notice/document_layout/html_table.py b/backend/app/services/shipping_notice/document_layout/html_table.py index 82b30696..b8eb2414 100644 --- a/backend/app/services/shipping_notice/document_layout/html_table.py +++ b/backend/app/services/shipping_notice/document_layout/html_table.py @@ -230,6 +230,28 @@ def map_html_table_to_schema( 包含列诊断、有效/删除/汇总行和 evidence_ref 的映射结果。 """ grid = parse_html_grid(html, table_id=table_id) + return map_html_grid_to_schema( + grid, page_no=page_no, table_id=table_id, contract=contract, + ) + + +def map_html_grid_to_schema( + grid: HtmlGrid, + *, + page_no: int, + table_id: str, + contract: TableHeaderContract, +) -> HtmlTableMappingResult: + """ + 按冻结 Schema 映射已验证网格,并保留网格自身 cell_id 作为证据身份。 + + Args: + grid: 来自 HTML 或 layout.v1 的固定矩形网格。 + page_no/table_id: 当前布局契约中的来源位置。 + contract: Run 冻结 Schema 编译出的精确表头契约。 + Returns: + 复用统一安全规则的列、行和字段候选。 + """ header_index, score = _select_header_row(grid, contract) if header_index is None: return HtmlTableMappingResult( @@ -271,6 +293,7 @@ def map_html_table_to_schema( for row_index in range(grid.row_count) if row_index > header_index ] + issues.extend(_apply_exclusive_deletion_markers(grid, mapped_rows)) required_codes = { code for code, config in contract.fields_by_code.items() if config.get('scope') == 'line' and config.get('required') @@ -423,6 +446,12 @@ def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any: """按冻结字段类型、normalizer 和 validator 转换 HTML 单元格;非法值留空不跨列补偿。""" if config is None: return None + # [STEP] 表格错列时,典型 SAP 项次会落入 Reservation ID 列;不能只靠数字长度放行。 + if ( + str(config.get('field_code') or '') == 'reservation_id' + and _is_probable_sap_line_number(raw) + ): + return None value_type = str(config.get('value_type') or 'string') candidate: Any = raw if value_type in {'decimal', 'integer'}: @@ -440,6 +469,11 @@ def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any: return None +def _is_probable_sap_line_number(value: Any) -> bool: + """识别典型五位 SAP 项次,防止 PDF 表格错列将 00010/00020 误作预约号。""" + return bool(re.fullmatch(r'0{3,4}[1-9]\d?', str(value or '').strip())) + + def _has_explicit_zero_quantity( row: list[HtmlGridSlot | None], *, columns: list[HtmlColumnMapping], ) -> bool: @@ -460,6 +494,40 @@ def _has_explicit_zero_quantity( return value is not None and value == 0 +def _apply_exclusive_deletion_markers( + grid: HtmlGrid, rows: list[HtmlMappedRow], +) -> list[str]: + """将独占删除标记归属到唯一相邻明细;存在零数量竞争行时保留有效行并转复核。""" + issues: list[str] = [] + for index, marker_row in enumerate(rows): + if not _is_exclusive_deletion_marker_row(grid, marker_row.row_index): + continue + previous = rows[index - 1] if index else None + if previous is None or previous.role != 'data' or not previous.fields: + issues.append('deletion_marker_without_unique_previous_line') + continue + # A zero-Qty row before a positive adjacent row is stronger deletion evidence than + # a displaced marker. Do not silently delete the positive row in that situation. + if any(item.role == 'deleted' for item in rows[:index - 1]): + issues.append('deletion_marker_target_ambiguous') + continue + rows[index - 1] = previous.model_copy(update={'role': 'deleted', 'fields': []}) + return issues + + +def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool: + """仅接受整行只表达删除含义的标记,避免把描述列中的普通文字误当删除指令。""" + texts = [ + normalize_table_header(slot.text) + for slot in grid.rows[row_index] + if slot is not None and slot.text.strip() + ] + if not texts: + return False + markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'} + return all(text in markers for text in texts) + + def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]: """生成叶表头、上层合并表头和组合路径的标准化候选,保持精确匹配。""" displays = _header_display_path(grid, row_index, column_index) diff --git a/backend/app/services/shipping_notice/document_layout/lifecycle.py b/backend/app/services/shipping_notice/document_layout/lifecycle.py new file mode 100644 index 00000000..d2ea5221 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/lifecycle.py @@ -0,0 +1,405 @@ +""" +backend/app/services/shipping_notice/document_layout/lifecycle.py + +用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。 +依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session。 +逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime +from typing import Any + +from flask import current_app +from sqlalchemy import and_, func, or_, update + +from app.extensions import db +from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument + + +LAYOUT_PARSER_NAME = 'mineru' +LAYOUT_BACKEND = 'pipeline' +LAYOUT_CONTRACT_VERSION = 'shipping_document_table_snapshot.v1' +CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'}) +TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'}) + + +def current_layout_parser_key() -> str: + """生成运维可轮转的 parser 身份;Provider/模型升级必须提升 revision 防止复用旧结果。""" + revision = str(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_PARSER_REVISION', 'v3', + ) or 'v3').strip() + return f'{LAYOUT_PARSER_NAME}:{LAYOUT_BACKEND}:{LAYOUT_CONTRACT_VERSION}:{revision}' + + +def canonical_layout_payload(payload: dict[str, Any]) -> tuple[str, int]: + """返回布局 JSON 的稳定 SHA-256 和 UTF-8 大小,供幂等与容量门禁复用。""" + encoded = json.dumps( + payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), + ).encode('utf-8') + return hashlib.sha256(encoded).hexdigest(), len(encoded) + + +def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None: + """读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。""" + version = 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) + + +def record_inline_layout_snapshot( + document: ShippingNoticeDocument, + snapshot: dict[str, Any], + *, + parser_key: str | None = None, +) -> ShippingDocumentLayoutVersion: + """ + 将 Intake 解析阶段已有布局快照转为不可变版本;后续 L1 Job 会复用同一收口逻辑。 + + 超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。 + """ + payload = dict(snapshot) + parser_key = str(parser_key or current_layout_parser_key()) + checksum, payload_size = canonical_layout_payload(payload) + source_hash = str(document.content_hash or '').strip().lower() + if len(source_hash) != 64: + source_hash = hashlib.sha256( + f'document:{document.id}:{document.attachment_key}'.encode('utf-8'), + ).hexdigest() + existing = ( + ShippingDocumentLayoutVersion.query + .filter_by( + document_id=int(document.id), + source_content_hash=source_hash, + parser_key=parser_key, + payload_checksum=checksum, + ) + .order_by(ShippingDocumentLayoutVersion.version.desc()) + .first() + ) + if existing is not None: + if existing.status in CURRENT_LAYOUT_STATUSES: + document.current_layout_version_id = existing.id + return existing + + version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by( + document_id=int(document.id), + ).scalar() or 0) + 1 + now = datetime.utcnow() + provider_status = str(payload.get('status') or 'failed') + status = provider_status if provider_status in { + 'ready', 'needs_review', 'failed', 'unsupported', + } else 'failed' + max_bytes = max(int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, + )), 1) + issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)}) + stored_payload: dict[str, Any] | None = payload + if payload_size > max_bytes: + status = 'failed' + stored_payload = None + issues.append('shipping_document_layout_snapshot_size_exceeded') + version = ShippingDocumentLayoutVersion( + document_id=int(document.id), + version=version_no, + status=status, + source_content_hash=source_hash, + parser_key=parser_key, + parser_name=str(payload.get('provider') or LAYOUT_PARSER_NAME)[:32], + parser_version=str(payload.get('provider_version') or '')[:64] or None, + backend=str(payload.get('backend') or LAYOUT_BACKEND)[:32], + contract_version=str(payload.get('snapshot_version') or LAYOUT_CONTRACT_VERSION)[:64], + payload_json=stored_payload, + payload_checksum=checksum, + payload_size_bytes=payload_size, + quality_json=( + dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None + ), + issues_json=sorted(set(issues)), + attempt_count=1, + created_at=now, + updated_at=now, + finished_at=now, + ) + db.session.add(version) + db.session.flush() + if status in CURRENT_LAYOUT_STATUSES: + document.current_layout_version_id = version.id + return version + + +def schedule_layout_version( + document: ShippingNoticeDocument, + *, + force: bool = False, + created_by_id: int | None = None, +) -> ShippingDocumentLayoutVersion | None: + """为支持的附件创建唯一 queued 版本和 Job;相同 parser 成功版本默认幂等复用。""" + from pathlib import Path + + from app.jobs.queue import enqueue + from app.jobs.types import JobType + from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS + + if not bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False)): + return None + if document.asset_id is None or Path(str(document.filename or '')).suffix.lower() not in MINERU_SUPPORTED_EXTENSIONS: + return None + source_hash = str(document.content_hash or '').strip().lower() + if len(source_hash) != 64: + return None + active = ShippingDocumentLayoutVersion.query.filter( + ShippingDocumentLayoutVersion.document_id == int(document.id), + ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}), + ).first() + if active is not None: + return active + if not force: + reusable = ShippingDocumentLayoutVersion.query.filter_by( + document_id=int(document.id), source_content_hash=source_hash, + parser_key=current_layout_parser_key(), + ).filter(ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES))).order_by( + ShippingDocumentLayoutVersion.version.desc(), + ).first() + if reusable is not None: + document.current_layout_version_id = reusable.id + return reusable + version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by( + document_id=int(document.id), + ).scalar() or 0) + 1 + version = ShippingDocumentLayoutVersion( + document_id=int(document.id), version=version_no, status='queued', + source_content_hash=source_hash, parser_key=current_layout_parser_key(), + parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND, + contract_version=LAYOUT_CONTRACT_VERSION, issues_json=[], attempt_count=0, + ) + db.session.add(version) + db.session.flush() + job_id = enqueue( + JobType.SHIPPING_DOCUMENT_LAYOUT, + {'layout_version_id': int(version.id)}, + domain='shipping_notice', business_ref=f'layout:{version.id}', + created_by_id=created_by_id, message='等待解析文档版面', + max_attempts=int(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS', 3)), + commit=False, + ) + version.job_id = job_id + return version + + +def schedule_document_layouts( + documents: list[ShippingNoticeDocument], *, created_by_id: int | None = None, +) -> list[ShippingDocumentLayoutVersion]: + """在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。""" + from pathlib import Path + + from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS + + max_documents = max(int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4, + )), 0) + eligible = [ + item for item in documents + if item.asset_id is not None + and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS + ] + result: list[ShippingDocumentLayoutVersion] = [] + for index, document in enumerate(eligible): + if index >= max_documents: + existing = ShippingDocumentLayoutVersion.query.filter_by( + document_id=int(document.id), source_content_hash=str(document.content_hash or ''), + parser_key=current_layout_parser_key(), status='unsupported', + ).first() + if existing is None: + version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by( + document_id=int(document.id), + ).scalar() or 0) + 1 + existing = ShippingDocumentLayoutVersion( + document_id=int(document.id), version=version_no, status='unsupported', + source_content_hash=str(document.content_hash or ''), + parser_key=current_layout_parser_key(), + parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND, + contract_version=LAYOUT_CONTRACT_VERSION, + issues_json=['mineru_intake_document_budget_exceeded'], attempt_count=0, + finished_at=datetime.utcnow(), + ) + db.session.add(existing) + db.session.flush() + result.append(existing) + continue + version = schedule_layout_version(document, created_by_id=created_by_id) + if version is not None: + result.append(version) + return result + + +def serialize_layout_version(version: ShippingDocumentLayoutVersion) -> dict[str, Any]: + """返回管理员诊断安全摘要,不暴露 HTML、bbox、正文或 Provider 原始响应。""" + payload = version.payload_json if isinstance(version.payload_json, dict) else {} + tables = payload.get('tables') if isinstance(payload.get('tables'), list) else [] + layout_candidate = ( + payload.get('layout_candidate') if isinstance(payload.get('layout_candidate'), dict) else {} + ) + candidate_pages = ( + layout_candidate.get('pages') if isinstance(layout_candidate.get('pages'), list) else [] + ) + candidate_table_count = sum( + len(page.get('tables') or []) + for page in candidate_pages + if isinstance(page, dict) and isinstance(page.get('tables'), list) + ) + return { + 'id': version.id, 'document_id': version.document_id, 'version': version.version, + 'status': version.status, 'parser_name': version.parser_name, + 'parser_version': version.parser_version, 'backend': version.backend, + 'contract_version': version.contract_version, + 'payload_checksum': version.payload_checksum, + 'payload_size_bytes': version.payload_size_bytes, + 'table_count': candidate_table_count or len(tables), + 'issues': list(version.issues_json or []), + 'attempt_count': version.attempt_count, 'job_id': version.job_id, + 'is_current': version.document.current_layout_version_id == version.id, + 'created_at': version.created_at.isoformat() if version.created_at else None, + 'started_at': version.started_at.isoformat() if version.started_at else None, + 'finished_at': version.finished_at.isoformat() if version.finished_at else None, + } + + +def list_layout_versions(document_id: int) -> list[dict[str, Any]]: + """列出一个 Document 的布局版本安全摘要。""" + document = db.session.get(ShippingNoticeDocument, int(document_id)) + if document is None: + from app.core.errors import NotFoundError + + raise NotFoundError( + 'Shipping notice document not found', code='SHIPPING_NOTICE.DOCUMENT_NOT_FOUND', + ) + return [serialize_layout_version(item) for item in ShippingDocumentLayoutVersion.query.filter_by( + document_id=int(document.id), + ).order_by(ShippingDocumentLayoutVersion.version.desc()).all()] + + +def request_layout_reparse( + document_id: int, *, created_by_id: int | None, +) -> dict[str, Any]: + """管理员显式创建下一布局版本;活动版本存在时幂等返回同一版本。""" + document = db.session.get(ShippingNoticeDocument, int(document_id)) + if document is None: + from app.core.errors import NotFoundError + + raise NotFoundError( + 'Shipping notice document not found', code='SHIPPING_NOTICE.DOCUMENT_NOT_FOUND', + ) + version = schedule_layout_version(document, force=True, created_by_id=created_by_id) + if version is None: + from app.core.errors import ValidationError + + raise ValidationError( + 'Document is not eligible for layout parsing', + code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED', + ) + db.session.commit() + return serialize_layout_version(version) + + +def claim_layout_version( + version_id: int, *, job_id: int, owned_attempt: int, +) -> tuple[ShippingDocumentLayoutVersion, str] | None: + """原子领取 queued/同 Job running 版本并轮转 lease,旧 Worker 立即失效。""" + lease = f'{int(job_id)}:{int(owned_attempt)}' + now = datetime.utcnow() + predicate = or_( + ShippingDocumentLayoutVersion.status == 'queued', + and_( + ShippingDocumentLayoutVersion.status == 'running', + ShippingDocumentLayoutVersion.job_id == int(job_id), + ), + ) + result = db.session.execute( + update(ShippingDocumentLayoutVersion) + .where(ShippingDocumentLayoutVersion.id == int(version_id), predicate) + .values( + status='running', job_id=int(job_id), lease_token=lease, + attempt_count=int(owned_attempt), started_at=now, updated_at=now, + ) + ) + if int(result.rowcount or 0) != 1: + db.session.rollback() + return None + db.session.commit() + version = db.session.get(ShippingDocumentLayoutVersion, int(version_id)) + return (version, lease) if version is not None else None + + +def complete_layout_version( + version_id: int, *, lease_token: str, snapshot: dict[str, Any], +) -> bool: + """按 lease 条件冻结 payload/checksum;失败版本不覆盖 Document 旧成功引用。""" + version = db.session.get(ShippingDocumentLayoutVersion, int(version_id)) + if version is None or version.status != 'running' or version.lease_token != lease_token: + db.session.rollback() + return False + checksum, payload_size = canonical_layout_payload(snapshot) + max_bytes = max(int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000, + )), 1) + issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)}) + provider_status = str(snapshot.get('status') or 'failed') + status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed' + stored_payload: dict[str, Any] | None = dict(snapshot) + if payload_size > max_bytes: + status = 'failed' + stored_payload = None + issues.append('shipping_document_layout_snapshot_size_exceeded') + 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.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.issues_json = sorted(set(issues)) + version.lease_token = None + version.finished_at = now + version.updated_at = now + if status in CURRENT_LAYOUT_STATUSES: + version.document.current_layout_version_id = version.id + db.session.commit() + return True + + +def sync_layout_after_job_recovery(job: Any) -> None: + """通用 Job 超时回收后同步布局版本,清除旧 lease 或记录最终失败。""" + version = ShippingDocumentLayoutVersion.query.filter_by(job_id=int(job.id)).first() + if version is None or version.status != 'running': + return + version.lease_token = None + version.updated_at = datetime.utcnow() + if str(job.status or '') == 'queued': + version.status = 'queued' + elif str(job.status or '') in {'failed', 'cancelled'}: + version.status = 'failed' + version.finished_at = datetime.utcnow() + version.issues_json = sorted(set(list(version.issues_json or []) + [ + 'shipping_document_layout_job_exhausted', + ])) + + +def sync_layout_after_job_failure(job_id: int) -> None: + """Handler 调用 fail_job 后立即同步版本状态,避免等待超时回收才清 lease。""" + from app.models import Job + + job = db.session.get(Job, int(job_id)) + if job is None: + return + sync_layout_after_job_recovery(job) + db.session.commit() diff --git a/backend/app/services/shipping_notice/document_layout/mineru.py b/backend/app/services/shipping_notice/document_layout/mineru.py index ce28af6f..e2f444bf 100644 --- a/backend/app/services/shipping_notice/document_layout/mineru.py +++ b/backend/app/services/shipping_notice/document_layout/mineru.py @@ -10,6 +10,7 @@ from __future__ import annotations import hashlib import json +import time from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable @@ -40,6 +41,7 @@ class MinerUClientConfig: languages: tuple[str, ...] = ('ch',) connect_timeout_seconds: int = 10 read_timeout_seconds: int = 300 + poll_interval_seconds: float = 1.0 max_upload_bytes: int = 30 * 1024 * 1024 max_response_bytes: int = 20 * 1024 * 1024 @@ -193,20 +195,7 @@ class MinerUClient: details={'max_bytes': self.config.max_upload_bytes}, ) - data = [ - ('backend', self.config.backend), - ('parse_method', self.config.parse_method), - ('formula_enable', 'false'), - ('table_enable', 'true'), - ('image_analysis', 'false'), - ('return_md', 'false'), - ('return_middle_json', 'true'), - ('return_model_output', 'true'), - ('return_content_list', 'true'), - ('return_images', 'false'), - ('response_format_zip', 'false'), - ] - data.extend(('lang_list', item) for item in self.config.languages) + data = _mineru_request_data(self.config) try: response = self.session.post( f'{self.base_url}/file_parse', @@ -252,6 +241,110 @@ class MinerUClient: ) return payload + def parse_file_async(self, *, filename: str, content: bytes) -> dict[str, Any]: + """ + 通过 `/tasks` 提交异步解析并轮询终态结果,避免单条 HTTP 长连接占用 Worker。 + + Args: + filename: 受支持文件名,仅用于扩展名和 multipart。 + content: 文件原始字节,受上传上限限制。 + Returns: + 与同步 `/file_parse` 相同的 completed 结果对象。 + Raises: + ValidationError: 提交、状态或终态响应不符合协议。 + ServiceUnavailableError: 网络、5xx 或总等待时间超限。 + """ + extension = Path(str(filename or '')).suffix.lower() + if extension not in MINERU_SUPPORTED_EXTENSIONS: + raise ValidationError( + 'MinerU file type is unsupported', + code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED', + details={'extension': extension}, + ) + if not content: + raise ValidationError('MinerU input file is empty', code='SHIPPING_NOTICE.LAYOUT_FILE_EMPTY') + if len(content) > self.config.max_upload_bytes: + raise ValidationError( + 'MinerU input file exceeds size limit', + code='SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE', + details={'max_bytes': self.config.max_upload_bytes}, + ) + data = _mineru_request_data(self.config) + try: + response = self.session.post( + f'{self.base_url}/tasks', + files=[('files', (filename, content, _mime_type(extension)))], + data=data, + timeout=(self.config.connect_timeout_seconds, self.config.connect_timeout_seconds), + ) + submission = _response_json(response, max_bytes=self.config.max_response_bytes) + except requests.exceptions.RequestException as exc: + raise ServiceUnavailableError( + 'MinerU task submission failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE', + ) from exc + if response.status_code >= 500: + raise ServiceUnavailableError( + 'MinerU task submission failed', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE', + details={'status': response.status_code}, + ) + if response.status_code >= 400: + raise ValidationError( + 'MinerU task submission was rejected', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED', + details={'status': response.status_code}, + ) + task_id = str(submission.get('task_id') or submission.get('id') or '').strip() + if not task_id: + raise ValidationError( + 'MinerU task response has no task id', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE', + ) + deadline = time.monotonic() + max(float(self.config.read_timeout_seconds), 1.0) + while time.monotonic() < deadline: + status = self._get_async_json(f'/tasks/{task_id}') + state = str(status.get('status') or status.get('state') or '').strip().lower() + if state in {'completed', 'succeeded', 'success'}: + result = self._get_async_json(f'/tasks/{task_id}/result') + if str(result.get('status') or '').strip().lower() not in {'completed', 'succeeded', 'success'}: + result = {**result, 'status': 'completed', 'task_id': task_id} + return result + if state in {'failed', 'error', 'cancelled', 'canceled'}: + raise ValidationError( + 'MinerU parse task failed', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED', + details={'provider_error_code': _provider_error_code(status.get('error'))}, + ) + time.sleep(max(float(self.config.poll_interval_seconds), 0.05)) + raise ServiceUnavailableError( + 'MinerU parse task timed out', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE', + ) + + def _get_async_json(self, path: str) -> dict[str, Any]: + """读取一个异步任务接口并统一网络、状态码和 JSON 容量错误。""" + try: + response = self.session.get( + f'{self.base_url}{path}', + timeout=(self.config.connect_timeout_seconds, self.config.connect_timeout_seconds), + ) + payload = _response_json(response, max_bytes=self.config.max_response_bytes) + except requests.exceptions.RequestException as exc: + raise ServiceUnavailableError( + 'MinerU task polling failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE', + ) from exc + if response.status_code >= 500: + raise ServiceUnavailableError( + 'MinerU task polling failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE', + details={'status': response.status_code}, + ) + if response.status_code >= 400: + raise ValidationError( + 'MinerU task polling response is invalid', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE', + details={'status': response.status_code}, + ) + return payload + def parse_mineru_candidate(payload: dict[str, Any]) -> MinerUParseCandidate: """ @@ -404,6 +497,46 @@ def _read_limited_response(response: requests.Response, *, max_bytes: int) -> by return b''.join(chunks) +def _mineru_request_data(config: MinerUClientConfig) -> list[tuple[str, str]]: + """生成同步/异步接口共用的 pipeline multipart 参数。""" + data = [ + ('backend', config.backend), + ('parse_method', config.parse_method), + ('formula_enable', 'false'), + ('table_enable', 'true'), + ('image_analysis', 'false'), + ('return_md', 'false'), + ('return_middle_json', 'true'), + ('return_model_output', 'true'), + ('return_content_list', 'true'), + ('return_images', 'false'), + ('response_format_zip', 'false'), + ] + data.extend(('lang_list', item) for item in config.languages) + return data + + +def _response_json(response: requests.Response, *, max_bytes: int) -> dict[str, Any]: + """读取有限大小 JSON 响应;兼容测试替身和 requests 非流式 GET。""" + if hasattr(response, 'iter_content'): + raw = _read_limited_response(response, max_bytes=max_bytes) + else: # pragma: no cover - requests.Response 始终实现 iter_content + raw = bytes(response.content or b'') + try: + payload = json.loads(raw.decode(response.encoding or 'utf-8')) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValidationError( + 'MinerU response is not valid JSON', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE', + ) from exc + if not isinstance(payload, dict): + raise ValidationError( + 'MinerU response must be an object', + code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE', + ) + return payload + + def _decode_json_field(value: Any, *, field: str) -> Any: """解包 MinerU 将 middle/model/content JSON 作为字符串返回的协议形式。""" parsed = value diff --git a/backend/app/services/shipping_notice/document_layout/native_pdf.py b/backend/app/services/shipping_notice/document_layout/native_pdf.py new file mode 100644 index 00000000..19b5e180 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/native_pdf.py @@ -0,0 +1,363 @@ +""" +backend/app/services/shipping_notice/document_layout/native_pdf.py + +用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。 +依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。 +逻辑:MinerU 提供整表与 HTML;PDFium提供独立字符/图像证据;只有严格匹配的 cell 才写入候选,整体仍固定 needs_review。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +import numpy as np +import pypdfium2 as pdfium + +from app.services.shipping_notice.document_layout.contracts import ( + LayoutBBox, + LayoutCell, + LayoutDocument, + LayoutIssue, + LayoutPage, + LayoutParserInfo, + LayoutQuality, + LayoutRow, + LayoutTable, + LayoutToken, + normalize_layout_text, + stable_layout_id, +) +from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid +from app.services.shipping_notice.document_layout.mineru import MinerUParseCandidate +from app.services.shipping_notice.document_layout.opencv_table import ( + reconstruct_opencv_table_geometry, + validate_opencv_cell_text, +) +from app.services.shipping_notice.document_layout.ocr_pdf import build_ocr_table_evidence +from app.services.shipping_notice.document_layout.text_cell_alignment import ( + PositionedCharacter, + align_html_cells_from_positioned_text, +) + + +@dataclass(frozen=True) +class NativePdfPage: + """保存单页原生字符和渲染图;对象仅在 Worker 内存中存在。""" + + page_no: int + width: float + height: float + rotation: int + characters: list[PositionedCharacter] + image: np.ndarray + + +def extract_native_pdf_pages(content: bytes, *, render_scale: float = 2.0) -> list[NativePdfPage]: + """ + 从 PDF bytes 提取左上原点字符坐标和页面图。 + + Args: + content: 原始 PDF 字节,不写文件和日志。 + render_scale: OpenCV 网格检测使用的渲染倍率,必须为正数。 + Returns: + 连续页列表;扫描 PDF 可返回无字符页面,但仍保留页面尺寸和图像。 + Raises: + ValueError: 内容为空、倍率非法或 PDFium 无法打开文件。 + """ + 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] = [] + for char_index in range(text_page.count_chars()): + text = text_page.get_text_range(char_index, 1) + if not text or not normalize_layout_text(text): + continue + left, bottom, right, top = text_page.get_charbox(char_index, loose=True) + if right <= left or top <= bottom: + continue + try: + characters.append(PositionedCharacter( + text=text, + bbox=LayoutBBox( + x0=left, y0=height - top, x1=right, y1=height - bottom, + ), + source_index=len(characters), + )) + except ValueError: + continue + 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(), + )) + return pages + + +def build_native_pdf_layout_candidate( + *, + document_id: int, + content_hash: str, + content: bytes, + mineru: MinerUParseCandidate, +) -> LayoutDocument: + """ + 组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。 + + Args: + document_id: 当前 ShippingNoticeDocument 主键。 + content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。 + content: 原始 PDF 字节。 + mineru: 同一文件的 MinerU pipeline 候选。 + Returns: + 通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。 + """ + native_pages = extract_native_pdf_pages(content) + mineru_pages = {item.page_no: item for item in mineru.pages} + issues: list[LayoutIssue] = [LayoutIssue( + code='document_cell_truth_deferred', severity='blocking', + )] + pages: list[LayoutPage] = [] + for native in native_pages: + page_candidate = mineru_pages.get(native.page_no) + tables: list[LayoutTable] = [] + page_tokens: dict[str, LayoutToken] = {} + for table_index, table_candidate in enumerate(page_candidate.tables if page_candidate else []): + try: + grid = parse_html_grid(table_candidate.html, table_id=table_candidate.candidate_id) + cells, method_issues = _candidate_cells( + native=native, grid=grid, table_bbox=table_candidate.bbox, + ) + except Exception: + issues.append(LayoutIssue( + code='native_pdf_table_candidate_invalid', severity='blocking', page_no=native.page_no, + table_id=table_candidate.candidate_id, + )) + continue + for code in method_issues: + issues.append(LayoutIssue( + code=code, severity='blocking', page_no=native.page_no, + table_id=table_candidate.candidate_id, + )) + if not cells: + continue + try: + layout_table = _layout_table( + native=native, + grid=grid, + table_bbox=table_candidate.bbox, + content_hash=content_hash, + table_index=table_index, + cells=cells, + page_tokens=page_tokens, + ) + except Exception: + issues.append(LayoutIssue( + code='native_pdf_layout_table_invalid', severity='blocking', + page_no=native.page_no, table_id=table_candidate.candidate_id, + )) + continue + tables.append(layout_table) + if page_candidate and page_candidate.tables and not tables: + issues.append(LayoutIssue( + code='native_pdf_table_cells_unresolved', severity='blocking', page_no=native.page_no, + )) + pages.append(LayoutPage( + page_no=native.page_no, width=native.width, height=native.height, + rotation=native.rotation, + tokens=[page_tokens[token_id] for token_id in sorted(page_tokens)], + tables=tables, + )) + if not any(page.tables for page in pages): + issues.append(LayoutIssue(code='native_pdf_no_resolved_tables', severity='blocking')) + return LayoutDocument( + document_id=document_id, + content_hash=content_hash, + parser=LayoutParserInfo( + name='mineru-pipeline+pdfium+rapidocr', + version=str(mineru.provider_version or 'unknown'), + ), + pages=pages, + quality=LayoutQuality(status='needs_review', confidence=0, issues=issues), + ) + + +def _candidate_cells( + *, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, +) -> tuple[dict[str, dict[str, Any]], list[str]]: + """优先唯一文本对齐,失败后仅对严格有框表使用 OpenCV 双门禁。""" + alignment = align_html_cells_from_positioned_text( + grid, characters=native.characters, table_bbox=table_bbox, + page_width=native.width, page_height=native.height, + ) + if alignment.complete: + return { + item.cell_id: { + 'bbox': item.bbox, + 'tokens': [ + _native_layout_token(native=native, glyph_index=index, content_hash='pending') + for index in item.glyph_indices + ], + 'source': 'native_text', 'confidence': 1, + } + for item in alignment.cells + }, ['native_pdf_cells_from_unique_text_candidate'] + geometry = reconstruct_opencv_table_geometry( + native.image, page_width=native.width, page_height=native.height, + table_bbox=table_bbox, grid=grid, + ) + validation = validate_opencv_cell_text( + geometry, grid=grid, + bounded_text_reader=lambda bbox: _text_within(native.characters, bbox), + minimum_match_rate=1.0, + required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()}, + ) + if not validation.accepted: + ocr = build_ocr_table_evidence( + image=native.image, page_width=native.width, page_height=native.height, + table_bbox=table_bbox, grid=grid, + ) + if not ocr.ready: + return {}, sorted(set( + alignment.issues + geometry.issues + validation.issues + ocr.issues, + )) + ocr_lines = {index: item for index, item in enumerate(ocr.lines)} + return { + item.cell_id: { + 'bbox': item.bbox, + 'tokens': [ + _ocr_layout_token( + native=native, line=ocr_lines[index], line_index=index, + ) + for index in item.line_indices + ], + 'source': 'ocr', + 'confidence': min( + (ocr_lines[index].confidence for index in item.line_indices), default=0, + ), + } + for item in ocr.cells + }, ['ocr_pdf_cells_from_grid_candidate'] + cells: dict[str, dict[str, Any]] = {} + for item in geometry.cells: + indices = _glyph_indices_within(native.characters, item.bbox) + expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id) + if expected.text.strip() and not indices: + return {}, ['native_pdf_opencv_cell_tokens_missing'] + cells[item.cell_id] = { + 'bbox': item.bbox, + 'tokens': [ + _native_layout_token(native=native, glyph_index=index, content_hash='pending') + for index in indices + ], + 'source': 'native_text', 'confidence': 1, + } + return cells, ['native_pdf_cells_from_opencv_candidate'] + + +def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_hash: str) -> LayoutToken: + """把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken。""" + glyph = native.characters[glyph_index] + return LayoutToken( + token_id=stable_layout_id('token', content_hash, native.page_no, glyph_index), + text=glyph.text, + normalized_text=normalize_layout_text(glyph.text), + bbox=glyph.bbox, + normalized_bbox=_normalized_bbox(glyph.bbox, native.width, native.height), + source='native_text', confidence=1, line_id=None, + ) + + +def _ocr_layout_token(*, native: NativePdfPage, line: Any, line_index: int) -> LayoutToken: + """把一条 OCR 行转为临时 LayoutToken;最终稳定 ID 在组表时绑定 Document/cell。""" + return LayoutToken( + token_id=stable_layout_id('ocr-token', 'pending', native.page_no, line_index), + text=line.text, + normalized_text=normalize_layout_text(line.text), + bbox=line.bbox, + normalized_bbox=_normalized_bbox(line.bbox, native.width, native.height), + source='ocr', confidence=line.confidence, line_id=None, + ) + + +def _layout_table( + *, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, content_hash: str, + table_index: int, cells: dict[str, dict[str, Any]], page_tokens: dict[str, LayoutToken], +) -> LayoutTable: + """按 HTML row/column/span 组装具有真实 bbox 和 token 引用的 needs_review 表格。""" + rows: list[LayoutRow] = [] + for row_index in range(grid.row_count): + source_cells = [item for item in grid.cells if item.row_index == row_index] + if not source_cells: + continue + role = 'header' if source_cells and all(item.is_header for item in source_cells) else 'data' + layout_cells = [] + for source in sorted(source_cells, key=lambda item: item.column_index): + evidence = cells[source.cell_id] + tokens = [ + token.model_copy(update={ + 'token_id': stable_layout_id( + 'token', content_hash, native.page_no, table_index, + source.row_index, source.column_index, token.token_id, + ), + }) + for token in evidence['tokens'] + ] + for token in tokens: + page_tokens[token.token_id] = token + layout_cells.append(LayoutCell( + cell_id=stable_layout_id( + 'cell', content_hash, native.page_no, table_index, + source.row_index, source.column_index, + ), + row_index=source.row_index, column_index=source.column_index, + row_span=source.row_span, column_span=source.column_span, + text=source.text, normalized_text=normalize_layout_text(source.text), + bbox=evidence['bbox'], + normalized_bbox=_normalized_bbox(evidence['bbox'], native.width, native.height), + token_ids=[token.token_id for token in tokens], + source=evidence['source'], confidence=evidence['confidence'], role=role, + )) + rows.append(LayoutRow( + row_id=stable_layout_id('row', content_hash, native.page_no, table_index, row_index), + row_index=row_index, cells=layout_cells, role=role, + )) + return LayoutTable( + table_id=stable_layout_id('table', content_hash, native.page_no, table_index), + bbox=table_bbox, + normalized_bbox=_normalized_bbox(table_bbox, native.width, native.height), + rows=rows, + header_row_indices=[row.row_index for row in rows if row.role == 'header'], + confidence=0, status='needs_review', + ) + + +def _glyph_indices_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> list[int]: + """返回中心点落在 bbox 内的 glyph 索引,保持 PDF 文本顺序。""" + return [ + index for index, item in enumerate(characters) + if bbox.x0 <= (item.bbox.x0 + item.bbox.x1) / 2 <= bbox.x1 + and bbox.y0 <= (item.bbox.y0 + item.bbox.y1) / 2 <= bbox.y1 + ] + + +def _text_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> str: + """读取 bbox 内原生字符,供 OpenCV 几何的独立文本一致性验证。""" + return ''.join(characters[index].text for index in _glyph_indices_within(characters, bbox)) + + +def _normalized_bbox(bbox: LayoutBBox, width: float, height: float) -> LayoutBBox: + """将页面单位 bbox 转换为布局契约 0..1 坐标。""" + return LayoutBBox( + x0=bbox.x0 / width, y0=bbox.y0 / height, + x1=bbox.x1 / width, y1=bbox.y1 / height, + ) diff --git a/backend/app/services/shipping_notice/document_layout/ocr_pdf.py b/backend/app/services/shipping_notice/document_layout/ocr_pdf.py new file mode 100644 index 00000000..df0a01c6 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/ocr_pdf.py @@ -0,0 +1,154 @@ +""" +backend/app/services/shipping_notice/document_layout/ocr_pdf.py + +用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选。 +依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约。 +逻辑:OCR 只提供独立文本坐标;必须与多参数有框网格及全部非空 cell 文本一致才输出,结果仍需人工真值。 +""" + +from __future__ import annotations + +from functools import lru_cache +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + +from app.services.shipping_notice.document_layout.contracts import LayoutBBox, normalize_layout_text +from app.services.shipping_notice.document_layout.html_table import HtmlGrid +from app.services.shipping_notice.document_layout.opencv_table import ( + reconstruct_opencv_table_geometry, + validate_opencv_cell_text, +) + + +class OcrLayoutModel(BaseModel): + """为 OCR 坐标结果启用严格字段校验。""" + + model_config = ConfigDict(extra='forbid') + + +class OcrLine(OcrLayoutModel): + """保存一条 RapidOCR 文本行、页面坐标和置信度。""" + + text: str = Field(min_length=1) + bbox: LayoutBBox + confidence: float = Field(ge=0, le=1) + + +class OcrCellEvidence(OcrLayoutModel): + """保存经几何和文本双门禁确认的 OCR cell 候选。""" + + cell_id: str + bbox: LayoutBBox + line_indices: list[int] = Field(default_factory=list) + + +class OcrTableEvidence(OcrLayoutModel): + """汇总扫描表候选;ready=False 时禁止暴露 cell。""" + + ready: bool + lines: list[OcrLine] = Field(default_factory=list) + cells: list[OcrCellEvidence] = Field(default_factory=list) + issues: list[str] = Field(default_factory=list) + + +@lru_cache(maxsize=1) +def _ocr_engine() -> Any: + """惰性创建 RapidOCR 引擎,避免未使用 OCR 时加载模型。""" + from rapidocr_onnxruntime import RapidOCR + + return RapidOCR() + + +def extract_ocr_lines( + image: Any, *, page_width: float, page_height: float, minimum_confidence: float = 0.8, +) -> list[OcrLine]: + """ + 将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。 + + Args: + image: PDFium 渲染的页面 ndarray。 + page_width/page_height: PDF 页面单位尺寸。 + minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。 + Returns: + 保持 OCR 返回顺序的文本行坐标。 + """ + if not 0 < minimum_confidence <= 1: + raise ValueError('OCR minimum confidence must be within (0, 1]') + height, width = image.shape[:2] + if width <= 0 or height <= 0 or page_width <= 0 or page_height <= 0: + raise ValueError('OCR page dimensions must be positive') + result, _elapsed = _ocr_engine()(image) + lines: list[OcrLine] = [] + for item in result or []: + if len(item) < 3: + continue + polygon, raw_text, raw_confidence = item[0], item[1], item[2] + text = str(raw_text or '').strip() + confidence = float(raw_confidence or 0) + if not text or not normalize_layout_text(text) or confidence < minimum_confidence: + continue + try: + xs = [float(point[0]) for point in polygon] + ys = [float(point[1]) for point in polygon] + bbox = LayoutBBox( + x0=min(xs) * page_width / width, + y0=min(ys) * page_height / height, + x1=max(xs) * page_width / width, + y1=max(ys) * page_height / height, + ) + if bbox.x1 > page_width or bbox.y1 > page_height: + continue + lines.append(OcrLine(text=text, bbox=bbox, confidence=confidence)) + except (TypeError, ValueError, IndexError): + continue + return lines + + +def build_ocr_table_evidence( + *, image: Any, page_width: float, page_height: float, + table_bbox: LayoutBBox, grid: HtmlGrid, +) -> OcrTableEvidence: + """对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。""" + try: + lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height) + except Exception: + return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable']) + if not lines: + return OcrTableEvidence(ready=False, issues=['ocr_text_missing']) + geometry = reconstruct_opencv_table_geometry( + image, page_width=page_width, page_height=page_height, + table_bbox=table_bbox, grid=grid, + ) + validation = validate_opencv_cell_text( + geometry, grid=grid, + bounded_text_reader=lambda bbox: _text_within(lines, bbox), + minimum_match_rate=1, + required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()}, + ) + if not validation.accepted: + return OcrTableEvidence( + ready=False, issues=sorted(set(geometry.issues + validation.issues)), + ) + cells = [] + for item in geometry.cells: + indices = _line_indices_within(lines, item.bbox) + expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id) + if expected.text.strip() and not indices: + return OcrTableEvidence(ready=False, issues=['ocr_cell_tokens_missing']) + cells.append(OcrCellEvidence(cell_id=item.cell_id, bbox=item.bbox, line_indices=indices)) + return OcrTableEvidence(ready=True, lines=lines, cells=cells, issues=[]) + + +def _line_indices_within(lines: list[OcrLine], bbox: LayoutBBox) -> list[int]: + """返回中心点位于 cell 内的 OCR 行索引。""" + return [ + index for index, item in enumerate(lines) + if bbox.x0 <= (item.bbox.x0 + item.bbox.x1) / 2 <= bbox.x1 + and bbox.y0 <= (item.bbox.y0 + item.bbox.y1) / 2 <= bbox.y1 + ] + + +def _text_within(lines: list[OcrLine], bbox: LayoutBBox) -> str: + """按 OCR 顺序读取 cell 内文本行,供独立一致性校验。""" + return ' '.join(lines[index].text for index in _line_indices_within(lines, bbox)) 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 19789de2..ae676f6e 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -11,6 +11,7 @@ from __future__ import annotations import hashlib import json import re +from decimal import Decimal from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, model_validator @@ -80,6 +81,9 @@ class OrderDocumentProfile(OrderProfileModel): columns = [item.column_index for item in self.column_rules] if len(columns) != len(set(columns)): raise ValueError('order profile source columns must be unique') + targets = [code for item in self.column_rules for code in item.target_field_codes] + if len(targets) != len(set(targets)): + raise ValueError('order profile target fields must be unique across columns') if self.data_start_row_index <= self.header_row_index: raise ValueError('order profile data rows must start after the header') if self.row_structure == 'unsupported_row_structure' and self.column_rules: @@ -228,7 +232,7 @@ def _parse_profile_row( if value is None: issues.append(f'order_profile_field_invalid:{code}') continue - fields[code] = value.isoformat() if hasattr(value, 'isoformat') else value + fields[code] = _profile_json_value(value) if profile.drop_zero_qty and explicit_qty == 0: return OrderProfileRowResult(row_index=row_index, status='deleted') required_build = {'part_number', 'qty'} @@ -278,3 +282,10 @@ def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any: return value if value is not None and validate_order_field_value(value, config) else None except (ArithmeticError, TypeError, ValueError, ValidationError): return None + + +def _profile_json_value(value: Any) -> Any: + """把字段规则返回值转换为数据库 JSON 可序列化标量。""" + if isinstance(value, Decimal): + return int(value) if value == value.to_integral_value() else float(value) + return value.isoformat() if hasattr(value, 'isoformat') else value diff --git a/backend/app/services/shipping_notice/document_layout/runtime.py b/backend/app/services/shipping_notice/document_layout/runtime.py new file mode 100644 index 00000000..f390fe8e --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/runtime.py @@ -0,0 +1,238 @@ +""" +backend/app/services/shipping_notice/document_layout/runtime.py + +用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。 +依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。 +逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;Provider 错误安全降级,不保存原始响应。 +""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any + +from flask import current_app + +from app.core.errors import AppError +from app.services.shipping_notice.document_layout.mineru import ( + MINERU_SUPPORTED_EXTENSIONS, + MinerUClient, + MinerUClientConfig, + parse_mineru_candidate, +) + + +LAYOUT_SNAPSHOT_VERSION = 'shipping_document_table_snapshot.v1' + + +def _enabled() -> bool: + """读取显式 MinerU 开关;未配置时不得在上传链静默增加外部调用。""" + return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False)) + + +def mineru_layout_capture_enabled(filename: str) -> bool: + """判断文件是否需要读取二进制并调用 MinerU,供上传链避免默认关闭时重复对象存储 I/O。""" + return _enabled() and Path(str(filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS + + +def build_mineru_table_snapshot( + *, + filename: str, + content: bytes, + read_timeout_seconds: int | None = None, + document_id: int | None = None, + content_hash: str | None = None, +) -> dict[str, Any] | None: + """ + 为一个受支持附件生成紧凑 MinerU 文本与表格快照。 + + 核心逻辑:保留分页非表格文本块和表格 HTML,分别执行字符预算;不持久化 + task_id、Provider 原始响应、模型中间输出或逐字符坐标。 + + Args: + filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。 + content: 原始文件字节;不写数据库和日志。 + document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。 + Returns: + 关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。 + """ + extension = Path(str(filename or '')).suffix.lower() + if not mineru_layout_capture_enabled(filename) or not content: + return None + base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip() + if not base_url: + return { + 'snapshot_version': LAYOUT_SNAPSHOT_VERSION, + 'provider': 'mineru', + 'backend': 'pipeline', + 'status': 'config_missing', + 'tables': [], + 'issues': ['mineru_base_url_missing'], + } + config = MinerUClientConfig( + base_url=base_url, + backend='pipeline', + connect_timeout_seconds=int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS', 10, + )), + read_timeout_seconds=int(read_timeout_seconds or min( + int(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', 300)), + max(int(current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300)) - 30, 1), + )), + ) + try: + candidate = parse_mineru_candidate( + MinerUClient(config).parse_file_async(filename=filename, content=content), + ) + except AppError as exc: + return { + 'snapshot_version': LAYOUT_SNAPSHOT_VERSION, + 'provider': 'mineru', + 'backend': 'pipeline', + 'status': 'failed', + 'tables': [], + 'issues': [str(exc.code)], + } + except (TypeError, ValueError): + return { + 'snapshot_version': LAYOUT_SNAPSHOT_VERSION, + 'provider': 'mineru', + 'backend': 'pipeline', + 'status': 'failed', + 'tables': [], + 'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'], + } + max_html_chars = max(int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', 1_000_000, + )), 1) + max_text_chars = max(int(current_app.config.get( + 'SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS', 200_000, + ) or 200_000), 1) + tables: list[dict[str, Any]] = [] + text_blocks: list[dict[str, Any]] = [] + total_html_chars = 0 + total_text_chars = 0 + issues = list(candidate.capability.issues) + for page in candidate.pages: + for block in sorted( + page.text_blocks, + key=lambda item: ( + item.normalized_bbox.y0, item.normalized_bbox.x0, + item.normalized_bbox.y1, item.normalized_bbox.x1, + ), + ): + text = ' '.join(str(block.text or '').split()).strip() + if not text: + continue + if total_text_chars + len(text) > max_text_chars: + issues.append('mineru_text_budget_exceeded') + continue + total_text_chars += len(text) + text_blocks.append({ + 'page_no': block.page_no, + 'normalized_bbox': block.normalized_bbox.model_dump(mode='json'), + 'text': text, + 'content_type': block.content_type, + }) + for table in page.tables: + html = str(table.html or '') + if total_html_chars + len(html) > max_html_chars: + issues.append('mineru_table_html_budget_exceeded') + continue + total_html_chars += len(html) + tables.append({ + 'table_id': table.candidate_id, + 'page_no': table.page_no, + 'bbox': table.bbox.model_dump(mode='json'), + 'normalized_bbox': table.normalized_bbox.model_dump(mode='json'), + 'html': html, + 'row_count': table.row_count, + 'cell_count': table.cell_count, + 'has_rowspan': table.has_rowspan, + 'has_colspan': table.has_colspan, + }) + snapshot = { + 'snapshot_version': LAYOUT_SNAPSHOT_VERSION, + 'provider': 'mineru', + 'provider_version': candidate.provider_version, + 'backend': candidate.backend or 'pipeline', + 'status': 'ready', + 'text_blocks': text_blocks, + 'tables': tables, + 'capability': candidate.capability.model_dump(mode='json'), + 'issues': sorted(set(issues)), + } + if extension == '.pdf' and document_id and content_hash: + try: + from app.services.shipping_notice.document_layout.native_pdf import ( + build_native_pdf_layout_candidate, + ) + + layout = build_native_pdf_layout_candidate( + document_id=int(document_id), content_hash=str(content_hash), + content=content, mineru=candidate, + ) + snapshot['layout_candidate'] = layout.model_dump(mode='json') + except Exception: + snapshot['issues'] = sorted(set( + list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'], + )) + return snapshot + + +def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None: + """就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。""" + meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {} + attachments = meta.get('attachments') if isinstance(meta.get('attachments'), list) else [] + if attachments: + app = current_app._get_current_object() + eligible = [ + item for item in attachments + if isinstance(item, dict) + and isinstance(item.get('_payload_bytes'), bytes) + and mineru_layout_capture_enabled(str(item.get('filename') or '')) + ] + max_documents = max(int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4, + )), 0) + concurrency = max(int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', 2, + )), 1) + selected = eligible[:max_documents] + for item in eligible[max_documents:]: + item['layout_snapshot'] = { + 'snapshot_version': LAYOUT_SNAPSHOT_VERSION, + 'provider': 'mineru', 'backend': 'pipeline', 'status': 'skipped_budget', + 'tables': [], 'issues': ['mineru_intake_document_budget_exceeded'], + } + + batch_count = max((len(selected) + concurrency - 1) // concurrency, 1) + configured_timeout = int(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', 300, + )) + total_timeout = int(current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300)) + per_request_timeout = max(min(configured_timeout, (max(total_timeout - 30, 1) // batch_count)), 1) + + def parse_attachment(item: dict[str, Any]) -> dict[str, Any] | None: + """在线程独立应用上下文中解析一个附件,不访问 ORM Session。""" + with app.app_context(): + return build_mineru_table_snapshot( + filename=str(item.get('filename') or ''), + content=item['_payload_bytes'], + read_timeout_seconds=per_request_timeout, + ) + + if selected: + with ThreadPoolExecutor(max_workers=min(concurrency, len(selected))) as pool: + snapshots = list(pool.map(parse_attachment, selected)) + for item, snapshot in zip(selected, snapshots, strict=True): + if snapshot is not None: + item['layout_snapshot'] = snapshot + return + if isinstance(root_asset_bytes, bytes): + snapshot = build_mineru_table_snapshot( + filename=str(getattr(result, 'filename', '') or ''), content=root_asset_bytes, + ) + if snapshot is not None: + meta['layout_snapshot'] = snapshot diff --git a/backend/app/services/shipping_notice/document_layout/schema_mapping.py b/backend/app/services/shipping_notice/document_layout/schema_mapping.py new file mode 100644 index 00000000..775c94b9 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/schema_mapping.py @@ -0,0 +1,112 @@ +""" +backend/app/services/shipping_notice/document_layout/schema_mapping.py + +用途:将 shipping_document_layout.v1 的真实 cell/token 证据映射到 Run 冻结订单 Schema。 +依赖:布局契约、HTML 网格统一映射器、TableHeaderContract。 +逻辑:只消费契约已验证行列和显式 continuation;不猜跨页、不提升质量状态、不接受无 cell 证据字段。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.shipping_notice.document_layout.contracts import LayoutDocument, LayoutTable, validate_layout_document +from app.services.shipping_notice.document_layout.html_table import ( + HtmlGrid, + HtmlGridCell, + HtmlGridSlot, + map_html_grid_to_schema, +) +from app.services.shipping_notice.order_schema.table_contract import TableHeaderContract + + +def map_layout_document_to_schema( + layout: LayoutDocument | dict[str, Any], *, contract: TableHeaderContract, +) -> list[dict[str, Any]]: + """ + 映射完整布局文档,并输出保留 cell/token 证据的安全候选。 + + Args: + layout: 必须通过 shipping_document_layout.v1 完整校验。 + contract: 当前 Run 冻结订单 Schema 表头契约。 + Returns: + 每张表的映射、质量和显式跨页父表;needs_review 永不伪装 accepted。 + """ + document = validate_layout_document(layout) + result: list[dict[str, Any]] = [] + for page in document.pages: + for table in page.tables: + grid = layout_table_to_grid(table) + mapped = map_html_grid_to_schema( + grid, page_no=page.page_no, table_id=table.table_id, contract=contract, + ) + token_ids_by_cell = { + cell.cell_id: list(cell.token_ids) + for row in table.rows for cell in row.cells + } + result.append({ + 'page_no': page.page_no, + 'table_id': table.table_id, + 'continuation_of': table.continuation_of, + 'layout_status': table.status, + 'mapping_status': 'candidate' if table.status != 'accepted' else 'accepted', + 'header_row_index': mapped.header_row_index, + 'issues': sorted(set( + list(mapped.issues) + + ([] if table.status == 'accepted' else ['layout_table_not_accepted']) + )), + 'columns': [item.model_dump(mode='json') for item in mapped.columns], + 'rows': [{ + **row.model_dump(mode='json'), + 'fields': [{ + **field.model_dump(mode='json'), + 'token_ids': token_ids_by_cell.get(field.cell_id, []), + 'evidence_ref': ( + f'layout:{document.document_id}:p{page.page_no}:' + f'{table.table_id}:{field.cell_id}' + ), + } for field in row.fields], + } for row in mapped.rows], + }) + return result + + +def layout_table_to_grid(table: LayoutTable) -> HtmlGrid: + """把 layout.v1 Table 转换为矩形 Grid,同时保留真实 cell_id、span 和角色。""" + occupied: dict[tuple[int, int], HtmlGridSlot] = {} + cells: list[HtmlGridCell] = [] + max_row = 0 + max_column = 0 + for row in table.rows: + for cell in row.cells: + is_header = cell.role == 'header' or row.role == 'header' + cells.append(HtmlGridCell( + cell_id=cell.cell_id, + row_index=cell.row_index, + column_index=cell.column_index, + row_span=cell.row_span, + column_span=cell.column_span, + text=cell.text, + normalized_text=cell.normalized_text, + is_header=is_header, + )) + for row_index in range(cell.row_index, cell.row_index + cell.row_span): + for column_index in range(cell.column_index, cell.column_index + cell.column_span): + occupied[(row_index, column_index)] = HtmlGridSlot( + row_index=row_index, column_index=column_index, + cell_id=cell.cell_id, text=cell.text, + normalized_text=cell.normalized_text, is_header=is_header, + origin_row_index=cell.row_index, + origin_column_index=cell.column_index, + ) + max_row = max(max_row, row_index + 1) + max_column = max(max_column, column_index + 1) + return HtmlGrid( + row_count=max_row, + column_count=max_column, + rows=[ + [occupied.get((row_index, column_index)) for column_index in range(max_column)] + for row_index in range(max_row) + ], + cells=cells, + ) diff --git a/backend/app/services/shipping_notice/document_layout/text_cell_alignment.py b/backend/app/services/shipping_notice/document_layout/text_cell_alignment.py new file mode 100644 index 00000000..006e15ae --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/text_cell_alignment.py @@ -0,0 +1,212 @@ +""" +backend/app/services/shipping_notice/document_layout/text_cell_alignment.py + +用途:用原生 PDF 字符坐标为 MinerU HTML cell 生成严格、可追溯的几何候选。 +依赖:document_layout contracts/html_table、Pydantic。 +逻辑:只接受表格区域内唯一且不重叠的规范化文本匹配;重复、空白或冲突 cell 不猜框。 +""" + +from __future__ import annotations + +import re +import unicodedata +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, ValidationError as PydanticValidationError, model_validator + +from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.html_table import HtmlGrid + + +class TextCellAlignmentModel(BaseModel): + """为字符和 cell 候选启用严格字段校验,防止评测辅助结果静默漂移。""" + + model_config = ConfigDict(extra='forbid') + + +class PositionedCharacter(TextCellAlignmentModel): + """保存 PDF 原生文本层的单个可见字符及页面坐标。""" + + text: str = Field(min_length=1, max_length=8) + bbox: LayoutBBox + source_index: int | None = Field(default=None, ge=0) + + +class TextAlignedCell(TextCellAlignmentModel): + """保存唯一文本匹配得到的 HTML cell 候选框;仍需人工视觉确认。""" + + cell_id: str + row_index: int = Field(ge=0) + column_index: int = Field(ge=0) + bbox: LayoutBBox + normalized_bbox: LayoutBBox + glyph_indices: list[int] = Field(default_factory=list) + + +class TextCellAlignmentResult(TextCellAlignmentModel): + """汇总严格文本对齐覆盖率和不准入原因,不复制文档原文。""" + + complete: bool + expected_cell_count: int = Field(ge=0) + matched_cell_count: int = Field(ge=0) + cells: list[TextAlignedCell] = Field(default_factory=list) + issues: list[str] = Field(default_factory=list) + + @model_validator(mode='after') + def validate_completeness(self) -> 'TextCellAlignmentResult': + """完整结果必须覆盖所有原始 cell;不完整结果不得伪报 complete。""" + expected = self.expected_cell_count > 0 and self.matched_cell_count == self.expected_cell_count + if self.complete != expected: + raise ValueError('text cell alignment completeness is inconsistent') + if self.matched_cell_count != len(self.cells): + raise ValueError('text cell alignment count is inconsistent') + return self + + +def align_html_cells_from_positioned_text( + grid: HtmlGrid, + *, + characters: list[PositionedCharacter | dict[str, Any]], + table_bbox: LayoutBBox, + page_width: float, + page_height: float, +) -> TextCellAlignmentResult: + """ + 在整表区域内按唯一规范化文本匹配 HTML 原始 cell,并合并字符 bbox。 + + Args: + grid: 已展开但仍保留原始 cell 身份的 HTML 网格。 + characters: PDF 原生文本层字符及左上原点页面坐标。 + table_bbox: MinerU 整表页面 bbox,仅在该范围内搜索。 + page_width/page_height: 页面尺寸,用于生成 0..1 标准化坐标。 + Returns: + 可供人工叠框 Review 的候选;任何歧义都保留 issue,绝不进入生产证据。 + """ + if page_width <= 0 or page_height <= 0: + raise ValueError('text cell alignment page dimensions must be positive') + if table_bbox.x1 > page_width or table_bbox.y1 > page_height: + raise ValueError('text cell alignment table bbox must be within the page') + glyphs: list[PositionedCharacter] = [] + invalid_character_bbox = False + for item in characters: + try: + glyph = item if isinstance(item, PositionedCharacter) else PositionedCharacter.model_validate(item) + except PydanticValidationError: + invalid_character_bbox = True + continue + if glyph.bbox.x1 > page_width or glyph.bbox.y1 > page_height: + invalid_character_bbox = True + continue + glyphs.append(glyph) + glyphs = [item for item in glyphs if _bbox_center_within(table_bbox, item.bbox)] + normalized_stream, stream_to_glyph = _normalized_character_stream(glyphs) + used_glyphs: set[int] = set() + matched: list[TextAlignedCell] = [] + issues: set[str] = set() + if invalid_character_bbox: + issues.add('text_cell_alignment_invalid_character_bbox') + + for cell in grid.cells: + expected = _normalize_text(cell.text) + if not expected: + issues.add('text_cell_alignment_empty_cell') + continue + starts = [match.start() for match in re.finditer(re.escape(expected), normalized_stream)] + if len(starts) != 1: + issues.add( + 'text_cell_alignment_text_not_found' + if not starts else 'text_cell_alignment_text_not_unique' + ) + continue + indices = set(stream_to_glyph[starts[0]:starts[0] + len(expected)]) + if not indices or indices & used_glyphs: + issues.add('text_cell_alignment_glyph_overlap') + continue + matched_glyphs = [glyphs[index] for index in sorted(indices)] + if not _glyphs_form_contiguous_text(matched_glyphs): + issues.add('text_cell_alignment_geometry_discontinuous') + continue + bbox = _union_bbox([item.bbox for item in matched_glyphs]) + used_glyphs.update(indices) + matched.append(TextAlignedCell( + cell_id=cell.cell_id, + row_index=cell.row_index, + column_index=cell.column_index, + bbox=bbox, + normalized_bbox=LayoutBBox( + x0=bbox.x0 / page_width, + y0=bbox.y0 / page_height, + x1=bbox.x1 / page_width, + y1=bbox.y1 / page_height, + ), + glyph_indices=sorted( + glyphs[index].source_index if glyphs[index].source_index is not None else index + for index in indices + ), + )) + + return TextCellAlignmentResult( + complete=bool(grid.cells) and len(matched) == len(grid.cells), + expected_cell_count=len(grid.cells), + matched_cell_count=len(matched), + cells=matched, + issues=sorted(issues), + ) + + +def _normalized_character_stream( + characters: list[PositionedCharacter], +) -> tuple[str, list[int]]: + """生成规范化字符流,并保留每个输出字符到原 glyph 的反向索引。""" + stream: list[str] = [] + mapping: list[int] = [] + for index, item in enumerate(characters): + normalized = _normalize_text(item.text) + stream.extend(normalized) + mapping.extend([index] * len(normalized)) + return ''.join(stream), mapping + + +def _normalize_text(value: Any) -> str: + """以 NFKC/casefold 保留字母数字和中日韩字符,忽略版面空白及标点。""" + text = unicodedata.normalize('NFKC', str(value or '')).casefold() + return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text) + + +def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool: + """使用字符中心点筛选整表区域,允许字体 bbox 轻微越过表格边界。""" + center_x = (child.x0 + child.x1) / 2 + center_y = (child.y0 + child.y1) / 2 + return parent.x0 <= center_x <= parent.x1 and parent.y0 <= center_y <= parent.y1 + + +def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox: + """合并唯一匹配字符范围;调用方保证列表非空。""" + return LayoutBBox( + x0=min(item.x0 for item in boxes), + y0=min(item.y0 for item in boxes), + x1=max(item.x1 for item in boxes), + y1=max(item.y1 for item in boxes), + ) + + +def _glyphs_form_contiguous_text(characters: list[PositionedCharacter]) -> bool: + """要求匹配字符处于同一视觉行且水平间距连续,禁止跨 cell/跨行拼接。""" + if not characters: + return False + heights = [item.bbox.y1 - item.bbox.y0 for item in characters] + median_height = sorted(heights)[len(heights) // 2] + allowed_vertical_drift = max(2.0, median_height * 0.75) + center_y = sum((item.bbox.y0 + item.bbox.y1) / 2 for item in characters) / len(characters) + if any(abs((item.bbox.y0 + item.bbox.y1) / 2 - center_y) > allowed_vertical_drift for item in characters): + return False + ordered = sorted(characters, key=lambda item: item.bbox.x0) + if characters != ordered: + return False + widths = [item.bbox.x1 - item.bbox.x0 for item in characters] + median_width = sorted(widths)[len(widths) // 2] + allowed_gap = max(4.0, median_width * 3.0) + return all( + right.bbox.x0 - left.bbox.x1 <= allowed_gap + for left, right in zip(characters, characters[1:]) + ) diff --git a/backend/app/services/shipping_notice/eml_parse.py b/backend/app/services/shipping_notice/eml_parse.py index 25d5bb2d..89ccd78f 100644 --- a/backend/app/services/shipping_notice/eml_parse.py +++ b/backend/app/services/shipping_notice/eml_parse.py @@ -2,7 +2,7 @@ services/shipping_notice/eml_parse.py 用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。 -依赖:标准库 email/html;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。 +依赖:标准库 email/html、BeautifulSoup;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。 逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图; 嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件; 外层 body 不穿透 rfc822 / 附件型 multipart,避免订单文本误入正文或重复; @@ -24,11 +24,15 @@ from email.utils import parsedate_to_datetime from pathlib import Path from typing import Any, Callable +from bs4 import BeautifulSoup, Comment + # 签名/Logo 文件名启发式(仅对 image/* 生效) _SIGNATURE_LOGO_NAME_RE = re.compile( r"(?:^|[_.\-])(logo|signature|sig|banner|icon|spacer|pixel|footer|header)(?:[_.\-]|$)", re.IGNORECASE, ) +_HTML_TABLE_TAGS = frozenset({'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td'}) +_HTML_DROP_TAGS = frozenset({'script', 'style', 'img', 'svg', 'object', 'embed', 'iframe', 'template'}) @dataclass @@ -330,6 +334,52 @@ def _extract_body_text(msg: Message) -> str: return plain or html +def _extract_body_html_tables(msg: Message) -> list[str]: + """ + 提取根邮件正文中的 HTML 表格并做最小白名单清洗。 + + 核心逻辑:即使 multipart/alternative 同时存在 plain,也读取对应 HTML 的 table; + 仅保留表格结构、cell 文本及 rowspan/colspan,禁止脚本、样式、链接和图片进入布局快照。 + + Args: + msg: 当前 EML 根消息;不穿透 rfc822 或附件型 multipart。 + Returns: + 最多 20 张、合计不超过 200000 字符的安全 HTML table 片段。 + """ + result: list[str] = [] + total_chars = 0 + for part in _iter_local_body_candidates(msg): + if str(part.get_content_type() or '').lower() != 'text/html': + continue + raw = _decode_part_text(part, _read_part_payload(part)) + soup = BeautifulSoup(raw or '', 'html.parser') + for table in soup.find_all('table'): + if table.find_parent('table') is not None: + continue + fragment = BeautifulSoup(str(table), 'html.parser') + for comment in fragment.find_all(string=lambda value: isinstance(value, Comment)): + comment.extract() + for tag in list(fragment.find_all(True)): + if tag.name in _HTML_DROP_TAGS: + tag.decompose() + continue + if tag.name not in _HTML_TABLE_TAGS: + tag.unwrap() + continue + allowed = {'rowspan', 'colspan'} if tag.name in {'th', 'td'} else set() + tag.attrs = { + key: value for key, value in tag.attrs.items() + if str(key).lower() in allowed + } + cleaned = str(fragment.find('table') or '').strip() + if not cleaned or total_chars + len(cleaned) > 200_000 or len(result) >= 20: + continue + result.append(cleaned) + total_chars += len(cleaned) + break + return result + + def _is_collectible_text_leaf(msg: Message) -> bool: """判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。""" ctype = str(msg.get_content_type() or "").lower() @@ -1126,6 +1176,7 @@ def parse_eml_bytes( date_val = _format_date(msg) message_id = _normalize_message_id(_header_str(msg, "Message-ID") or _header_str(msg, "Message-Id")) body_text = _extract_body_text(msg) + body_html_tables = _extract_body_html_tables(msg) state = _ParseState(limits=limits, extract_text=extract_text) _walk_message(msg, state, depth=depth) @@ -1143,6 +1194,7 @@ def parse_eml_bytes( "to": to_addr, "date": date_val, "body_text": combined_body, + "body_html_tables": body_html_tables, } flat = _compose_flat_text( subject=subject, diff --git a/backend/app/services/shipping_notice/extract.py b/backend/app/services/shipping_notice/extract.py index 2f2e3333..e6b5801a 100644 --- a/backend/app/services/shipping_notice/extract.py +++ b/backend/app/services/shipping_notice/extract.py @@ -150,10 +150,10 @@ def _heuristic_extract( for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text): lines.append({"part_number": m.group(1), "qty": float(m.group(2))}) - # 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2) + # 尝试 5 位或 10 位 Reservation ID + SKU + Qty 的自由文本模式。 if not lines: for m in re.finditer( - r"(?P\d{8,12})\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)", + r"(?P(?:\d{5}|\d{10}))\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)", text, ): lines.append( diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py new file mode 100644 index 00000000..5c6cab39 --- /dev/null +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -0,0 +1,525 @@ +""" +backend/app/services/shipping_notice/order_document_profile_service.py + +用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。 +依赖:ShippingOrderDocumentProfile、订单 Schema 版本、document_layout.order_profile 纯契约。 +逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本。 +""" + +from __future__ import annotations + +import hashlib +import json +import re +from datetime import datetime +from typing import Any + +from sqlalchemy import func + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + ShippingNoticeDocument, + ShippingOrderDocumentProfile, + ShippingOrderSchemaVersion, +) +from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.document_layout.order_profile import ( + OrderDocumentProfile, + OrderProfileColumnRule, + order_profile_structure_fingerprint, +) + + +PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$') + + +def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]: + """返回绑定 Schema 中已启用的订单明细字段,并拒绝重复 field_code。""" + definition = version.definition_json if isinstance(version.definition_json, dict) else {} + result: dict[str, dict[str, Any]] = {} + for raw in definition.get('fields') or []: + if not isinstance(raw, dict) or not raw.get('enabled', True) or raw.get('scope') != 'line': + continue + code = str(raw.get('field_code') or '').strip() + field_id = str(raw.get('field_id') or '').strip() + if not code or not field_id or code in result: + raise ValidationError( + 'Order profile Schema fields are invalid', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + result[code] = dict(raw) + return result + + +def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion: + """读取不可变 published/retired Schema;草稿不可作为 Profile 运行契约。""" + try: + version_id = int(raw_id) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'schema_version_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) from exc + version = db.session.get(ShippingOrderSchemaVersion, version_id) + if version is None or version.status not in {'published', 'retired'} or not version.checksum: + raise ValidationError( + 'Order profile requires an immutable Schema version', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID', + ) + return version + + +def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersion) -> dict[str, Any]: + """校验纯 Profile 契约并把每个目标字段冻结为 field_id + field_code。""" + if not isinstance(raw, dict): + raise ValidationError( + 'Order profile definition must be an object', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + fields = _schema_fields(schema_version) + normalized_rules: list[dict[str, Any]] = [] + for raw_rule in raw.get('column_rules') or []: + if not isinstance(raw_rule, dict): + raise ValidationError( + 'Order profile column rule is invalid', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + codes = raw_rule.get('target_field_codes') + if not isinstance(codes, list) or any(str(code or '').strip() not in fields for code in codes): + raise ValidationError( + 'Order profile target field is unavailable in its Schema version', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID', + ) + rule = OrderProfileColumnRule( + column_index=raw_rule.get('column_index'), + extractor_key=raw_rule.get('extractor_key'), + target_field_codes=[str(code).strip() for code in codes], + ) + normalized_rules.append({ + **rule.model_dump(), + 'target_fields': [ + {'field_id': str(fields[code]['field_id']), 'field_code': code} + for code in rule.target_field_codes + ], + }) + try: + contract = OrderDocumentProfile( + profile_code='VALIDATION_PROFILE', + version=1, + structure_fingerprint=raw.get('structure_fingerprint'), + header_row_index=raw.get('header_row_index'), + data_start_row_index=raw.get('data_start_row_index'), + row_structure=raw.get('row_structure', 'preserved'), + column_rules=[OrderProfileColumnRule(**{ + key: value for key, value in item.items() if key != 'target_fields' + }) for item in normalized_rules], + drop_zero_qty=raw.get('drop_zero_qty', True), + ) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Order profile definition is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) from exc + return { + 'contract_version': contract.contract_version, + 'structure_fingerprint': contract.structure_fingerprint, + 'header_row_index': contract.header_row_index, + 'data_start_row_index': contract.data_start_row_index, + 'row_structure': contract.row_structure, + 'column_rules': normalized_rules, + 'drop_zero_qty': contract.drop_zero_qty, + } + + +def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderDocumentProfile: + """把数据库冻结定义还原为纯执行契约,额外存储的 field_id 不进入解析器。""" + definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + return OrderDocumentProfile( + profile_code=profile.profile_code, + version=profile.version, + structure_fingerprint=definition.get('structure_fingerprint'), + header_row_index=definition.get('header_row_index'), + data_start_row_index=definition.get('data_start_row_index'), + row_structure=definition.get('row_structure', 'preserved'), + column_rules=[OrderProfileColumnRule(**{ + key: value for key, value in rule.items() if key != 'target_fields' + }) for rule in definition.get('column_rules') or [] if isinstance(rule, dict)], + drop_zero_qty=definition.get('drop_zero_qty', True), + ) + + +def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: + """返回不含文档正文的 Profile 管理 DTO。""" + schema = profile.schema_version + return { + 'id': profile.id, + 'profile_code': profile.profile_code, + 'display_name': profile.display_name, + 'version': profile.version, + 'status': profile.status, + 'schema_version_id': profile.schema_version_id, + 'schema_version': schema.version if schema is not None else None, + 'schema_checksum': schema.checksum if schema is not None else None, + 'structure_fingerprint': profile.structure_fingerprint, + 'definition': dict(profile.definition_json or {}), + 'checksum': profile.checksum, + 'lock_version': profile.lock_version, + 'change_note': profile.change_note, + 'source_profile_id': profile.source_profile_id, + 'published_at': profile.published_at.isoformat() if profile.published_at else None, + 'retired_at': profile.retired_at.isoformat() if profile.retired_at else None, + } + + +def list_profiles() -> list[dict[str, Any]]: + """按模板编码和版本倒序列出全部 Profile。""" + return [payload(item) for item in ShippingOrderDocumentProfile.query.order_by( + ShippingOrderDocumentProfile.profile_code.asc(), + ShippingOrderDocumentProfile.version.desc(), + ).all()] + + +def _document_layout(document: ShippingNoticeDocument) -> dict[str, Any]: + """读取可用于建 Profile 的 ready MinerU 表格快照,不接受失败/超预算候选。""" + from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + + layout = current_layout_snapshot(document) or {} + tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] + if layout.get('status') != 'ready' or not tables: + raise ValidationError( + 'Document has no ready MinerU tables', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) + return layout + + +def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]: + """列出最近含 ready MinerU 表格的订单附件;不返回正文、HTML 或原始布局。""" + safe_limit = max(1, min(int(limit), 100)) + rows = ShippingNoticeDocument.query.filter( + ShippingNoticeDocument.document_type == 'attachment', + ShippingNoticeDocument.current_layout_version_id.is_not(None), + ).order_by(ShippingNoticeDocument.created_at.desc()).limit(safe_limit * 4).all() + result: list[dict[str, Any]] = [] + for document in rows: + from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + + layout = current_layout_snapshot(document) or {} + tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] + if layout.get('status') != 'ready' or not tables: + continue + result.append({ + 'document_id': document.id, + 'intake_id': document.intake_id, + 'filename': document.filename, + 'content_hash': document.content_hash, + 'provider': layout.get('provider'), + 'provider_version': layout.get('provider_version'), + 'table_count': len(tables), + 'created_at': document.created_at.isoformat() if document.created_at else None, + }) + if len(result) >= safe_limit: + break + return result + + +def get_sample_tables(document_id: int) -> dict[str, Any]: + """返回样本文档的表格网格预览;预览只含 cell 文本,不返回 bbox、正文或原始 HTML。""" + document = db.session.get(ShippingNoticeDocument, int(document_id)) + if document is None: + raise NotFoundError( + 'Order profile sample document not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + ) + layout = _document_layout(document) + tables: list[dict[str, Any]] = [] + for raw in layout.get('tables') or []: + if not isinstance(raw, dict) or not str(raw.get('html') or '').strip(): + continue + table_id = str(raw.get('table_id') or '') + grid = parse_html_grid(str(raw['html']), table_id=table_id) + tables.append({ + 'table_id': table_id, + 'page_no': int(raw.get('page_no') or 1), + 'row_count': grid.row_count, + 'column_count': grid.column_count, + 'rows': [ + [slot.text if slot is not None else '' for slot in row] + for row in grid.rows + ], + }) + return { + 'document': { + 'document_id': document.id, + 'intake_id': document.intake_id, + 'filename': document.filename, + 'content_hash': document.content_hash, + }, + 'tables': tables, + } + + +def create_draft_from_sample( + data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None, +) -> dict[str, Any]: + """ + 按持久化样本表格和管理员结构化选择生成 Profile 草稿。 + + 浏览器只提交 document/table、表头行、数据起始行和受控列规则;结构指纹由后端真实 HTML 计算。 + """ + try: + document_id = int(data.get('document_id')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) from exc + document = db.session.get(ShippingNoticeDocument, document_id) + if document is None: + raise NotFoundError( + 'Order profile sample document not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + ) + layout = _document_layout(document) + table_id = str(data.get('table_id') or '').strip() + raw_table = next(( + item for item in layout.get('tables') or [] + if isinstance(item, dict) and str(item.get('table_id') or '') == table_id + ), None) + if raw_table is None: + raise ValidationError( + 'Selected sample table is unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) + try: + header_row_index = int(data.get('header_row_index')) + data_start_row_index = int(data.get('data_start_row_index')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Sample row selection is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) from exc + grid = parse_html_grid(str(raw_table.get('html') or ''), table_id=table_id) + if ( + header_row_index < 0 or header_row_index >= grid.row_count + or data_start_row_index <= header_row_index or data_start_row_index >= grid.row_count + ): + raise ValidationError( + 'Sample row selection is out of range', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) + definition = { + 'structure_fingerprint': order_profile_structure_fingerprint( + grid, header_row_index=header_row_index, + ), + 'header_row_index': header_row_index, + 'data_start_row_index': data_start_row_index, + 'row_structure': str(data.get('row_structure') or 'preserved'), + 'column_rules': data.get('column_rules'), + 'drop_zero_qty': data.get('drop_zero_qty', True), + } + return save_draft({ + 'profile_code': data.get('profile_code'), + 'display_name': data.get('display_name'), + 'schema_version_id': data.get('schema_version_id'), + 'definition': definition, + 'change_note': data.get('change_note'), + 'expected_lock_version': data.get('expected_lock_version'), + }, actor_id=actor_id, profile_id=profile_id) + + +def save_draft( + data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None, +) -> dict[str, Any]: + """创建或整体替换草稿;更新要求乐观锁一致,发布版本不可修改。""" + profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile_id else None + if profile_id and profile is None: + raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') + if profile is not None and profile.status != 'draft': + raise ConflictError( + 'Published order document profile is immutable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE', + ) + code = str(data.get('profile_code') or (profile.profile_code if profile else '')).strip().upper() + if not PROFILE_CODE_PATTERN.fullmatch(code): + raise ValidationError('profile_code is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') + if profile is not None and code != profile.profile_code: + raise ConflictError( + 'Draft profile_code is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE', + ) + if profile is None and ShippingOrderDocumentProfile.query.filter_by( + profile_code=code, status='draft', + ).count(): + raise ConflictError( + 'An order document profile draft already exists', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS', + ) + schema_version = _require_schema_version( + data.get('schema_version_id', profile.schema_version_id if profile else None), + ) + if profile is not None: + expected = data.get('expected_lock_version') + if not isinstance(expected, int): + raise ValidationError( + 'expected_lock_version is required', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED', + ) + if expected != profile.lock_version: + raise ConflictError( + 'Order document profile draft was changed by another user', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT', + details={'expected_lock_version': expected, 'current_lock_version': profile.lock_version}, + ) + if schema_version.id != profile.schema_version_id: + raise ConflictError( + 'Draft Schema binding is immutable; create a new version', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE', + ) + definition = _normalize_definition(data.get('definition'), schema_version=schema_version) + if profile is None: + version = int(db.session.query(func.max(ShippingOrderDocumentProfile.version)).filter_by( + profile_code=code, + ).scalar() or 0) + 1 + profile = ShippingOrderDocumentProfile( + profile_code=code, + version=version, + schema_version_id=schema_version.id, + created_by_id=actor_id, + lock_version=1, + ) + db.session.add(profile) + else: + profile.lock_version += 1 + profile.display_name = str(data.get('display_name') or profile.display_name or code).strip() + profile.structure_fingerprint = definition['structure_fingerprint'] + profile.definition_json = definition + profile.change_note = str(data.get('change_note') or '').strip() or None + db.session.commit() + return payload(profile) + + +def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: + """从不可变版本复制新草稿;同编码只允许一个草稿。""" + source = db.session.get(ShippingOrderDocumentProfile, profile_id) + if source is None: + raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') + if source.status not in {'published', 'retired'}: + raise ConflictError( + 'Only immutable profile can be cloned', code='SHIPPING.ORDER_DOCUMENT_PROFILE_CLONE_INVALID', + ) + if ShippingOrderDocumentProfile.query.filter_by(profile_code=source.profile_code, status='draft').count(): + raise ConflictError( + 'An order document profile draft already exists', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS', + ) + version = int(db.session.query(func.max(ShippingOrderDocumentProfile.version)).filter_by( + profile_code=source.profile_code, + ).scalar() or 0) + 1 + clone = ShippingOrderDocumentProfile( + profile_code=source.profile_code, + display_name=source.display_name, + version=version, + status='draft', + schema_version_id=source.schema_version_id, + structure_fingerprint=source.structure_fingerprint, + definition_json=dict(source.definition_json or {}), + source_profile_id=source.id, + created_by_id=actor_id, + lock_version=1, + ) + db.session.add(clone) + db.session.commit() + return payload(clone) + + +def publish( + profile_id: int, *, actor_id: int | None, expected_lock_version: Any, +) -> dict[str, Any]: + """发布草稿并原子退役同编码旧版本;checksum 包含 Schema 身份与完整定义。""" + profile = db.session.get(ShippingOrderDocumentProfile, profile_id) + if profile is None: + raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') + if profile.status != 'draft': + raise ConflictError( + 'Only draft order document profile can be published', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', + ) + if not isinstance(expected_lock_version, int): + raise ValidationError( + 'expected_lock_version is required', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED', + ) + if expected_lock_version != profile.lock_version: + raise ConflictError( + 'Order document profile draft was changed by another user', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT', + ) + schema_version = _require_schema_version(profile.schema_version_id) + normalized = _normalize_definition(profile.definition_json, schema_version=schema_version) + profile.definition_json = normalized + profile.structure_fingerprint = normalized['structure_fingerprint'] + _definition_contract(profile) + encoded = json.dumps({ + 'profile_code': profile.profile_code, + 'version': profile.version, + 'schema_version_id': schema_version.id, + 'schema_checksum': schema_version.checksum, + 'definition': normalized, + }, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() + now = datetime.utcnow() + previous = ShippingOrderDocumentProfile.query.filter_by( + profile_code=profile.profile_code, status='published', + ).first() + if previous is not None: + previous.status = 'retired' + previous.retired_at = now + db.session.flush() + profile.checksum = hashlib.sha256(encoded).hexdigest() + profile.status = 'published' + profile.published_by_id = actor_id + profile.published_at = now + db.session.commit() + return payload(profile) + + +def retire(profile_id: int) -> dict[str, Any]: + """手工退役当前发布版本;历史 Run 仍使用自身冻结快照。""" + profile = db.session.get(ShippingOrderDocumentProfile, profile_id) + if profile is None: + raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') + if profile.status != 'published': + raise ConflictError( + 'Only published order document profile can be retired', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_RETIRE_INVALID', + ) + profile.status = 'retired' + profile.retired_at = datetime.utcnow() + db.session.commit() + return payload(profile) + + +def delete_draft(profile_id: int) -> None: + """删除未发布草稿;不可变版本永久保留审计。""" + profile = db.session.get(ShippingOrderDocumentProfile, profile_id) + if profile is None: + raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') + if profile.status != 'draft': + raise ConflictError( + 'Only draft order document profile can be deleted', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED', + ) + db.session.delete(profile) + db.session.commit() + + +def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any]]: + """生成 Run 可直接冻结的 published Profile 快照,不返回 ORM 或当前引用。""" + rows = ShippingOrderDocumentProfile.query.filter_by( + schema_version_id=int(schema_version_id), status='published', + ).order_by(ShippingOrderDocumentProfile.profile_code.asc()).all() + return [{ + 'profile_id': item.id, + 'profile_code': item.profile_code, + 'version': item.version, + 'checksum': item.checksum, + 'schema_version_id': item.schema_version_id, + 'structure_fingerprint': item.structure_fingerprint, + 'definition': dict(item.definition_json or {}), + } for item in rows] diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index e74880d4..45489079 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -43,6 +43,7 @@ from app.services.shipping_notice.duplicate_detection import ( from app.services.shipping_notice.document_candidate_persist import generate_candidate_no from app.services.shipping_notice.order_schema.runtime import persist_dynamic_order from app.services.shipping_notice.context_fields.runtime import canonical_mail_context +from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_dify def _load_intakes( @@ -184,6 +185,8 @@ def persist_order_extraction_result( schema_version_id: int, extraction_source: str = 'dify_workflow', frozen_context_by_intake: dict[int, dict[str, Any]] | None = None, + frozen_layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None, + frozen_evidence_text_by_document: dict[int, str] | None = None, auto_create_enabled: bool = False, ) -> dict[str, Any]: """ @@ -200,6 +203,8 @@ def persist_order_extraction_result( schema_version_id: Run 冻结的 published Schema 版本。 extraction_source: 固定为后台 Workflow 来源,不接受用户输入。 frozen_context_by_intake: Run 按 Intake 冻结的确定性上下文;后台 Run 必须提供。 + frozen_layout_candidates_by_document: Run 按 Document 冻结的 L4 字段候选;只接受 accepted cell 证据。 + frozen_evidence_text_by_document: Run 实际发送给 Dify 的冻结文本;用于同源 quote 核验。 auto_create_enabled: 冻结发布门禁;关闭时只落 Candidate,不自动创建/打开 Task。 Returns: 自动创建/打开的任务、待处理订单及缺失流程字段摘要。 @@ -252,11 +257,16 @@ def persist_order_extraction_result( document_has_pending: dict[int, bool] = {int(row.id): False for row in documents} document_non_shipping_indexes: dict[int, list[int]] = {int(row.id): [] for row in documents} - # [STEP 1] 本轮选择状态完全由最新 LLM 结果决定,避免旧的 selected Candidate 混入自动建批集合。 - db.session.query(ShippingNoticeCandidate).filter( + # [STEP 1] 新 Run 先撤销旧版本候选的可消费资格;旧记录仍保留用于审计与重识别失败回退。 + current_candidates = db.session.query(ShippingNoticeCandidate).filter( ShippingNoticeCandidate.intake_id.in_([int(row.id) for row in intakes]), ShippingNoticeCandidate.consumed_task_id.is_(None), - ).update({'selected': False}, synchronize_session=False) + ShippingNoticeCandidate.is_current_version.is_(True), + ) + if run_id is not None: + current_candidates = current_candidates.filter(ShippingNoticeCandidate.order_extraction_run_id != int(run_id)) + current_candidates.update({'selected': False, 'is_current_version': False}, synchronize_session=False) + current_candidates.update({'selected': False}, synchronize_session=False) for index, raw_order in enumerate(orders): if not isinstance(raw_order, dict): @@ -310,9 +320,27 @@ def persist_order_extraction_result( actor_id=int(session.user_id), schema_version_id=schema_version_id, frozen_mail_context=(frozen_context_by_intake or {}).get(int(intake.id)), + layout_candidates_by_document={ + int(item.id): list((frozen_layout_candidates_by_document or {}).get(int(item.id)) or []) + for item in owned_docs + }, + frozen_evidence_text_by_document=frozen_evidence_text_by_document, ) if run_id is not None: dynamic['extraction'].run_id = int(run_id) + layout_evidence_issues = [ + { + 'field': ','.join(str(code) for code in item.get('field_codes') or []) or 'document_layout', + 'severity': 'blocking', + 'reason': str(item.get('reason') or 'layout_evidence_unavailable'), + 'document_id': item.get('document_id'), + } + for item in ( + (dynamic['extraction'].validation_result_json or {}).get('deterministic_table_issues') or [] + ) + if isinstance(item, dict) + ] + blocking_conflicts.extend(layout_evidence_issues) summary = {**dynamic['header'], 'lines': dynamic['lines']} # Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。 if summary.get('bill_to_customer'): @@ -330,6 +358,21 @@ def persist_order_extraction_result( 'field': ','.join(dynamic['blocked_fields']), 'severity': 'blocking', 'reason': 'dynamic_schema_required_or_evidence_gate', }]) + field_confidence: dict[str, float] = {} + for decision in dynamic['decisions']: + field_code = str(decision.get('field_code') or '') + if not field_code: + continue + confidence = float(decision.get('confidence') or 0.0) + existing_confidence = field_confidence.get(field_code) + field_confidence[field_code] = ( + confidence if existing_confidence is None else min(existing_confidence, confidence) + ) + low_confidence_fields = sorted({ + field_code + for field_code, minimum_confidence in dynamic['auto_create_key_field_thresholds'].items() + if field_confidence.get(field_code, 0.0) < minimum_confidence + }) assessment = assess_candidate_business_summary(summary) normalized = assessment['normalized_summary'] reasons: list[str] = [] @@ -341,6 +384,8 @@ def persist_order_extraction_result( reasons.append('low_classification_confidence') if dynamic['blocked_fields']: reasons.append('dynamic_schema_gate') + if low_confidence_fields: + reasons.append('low_key_field_confidence') if blocking_conflicts: reasons.append('blocking_conflict') @@ -348,7 +393,11 @@ def persist_order_extraction_result( active_keys_by_intake[int(intake.id)].add(candidate_key) candidate = ( db.session.query(ShippingNoticeCandidate) - .filter_by(intake_id=int(intake.id), candidate_key=candidate_key) + .filter_by( + intake_id=int(intake.id), + candidate_key=candidate_key, + order_extraction_run_id=int(run_id) if run_id is not None else None, + ) .first() ) if candidate is not None and candidate.consumed_task_id is not None: @@ -360,15 +409,17 @@ def persist_order_extraction_result( intake_id=int(intake.id), primary_document_id=int(document.id), candidate_key=candidate_key, + order_extraction_run_id=int(run_id) if run_id is not None else None, ) db.session.add(candidate) candidate.primary_document_id = int(document.id) candidate.source_order_index = index candidate.order_extraction_id = int(dynamic['extraction'].id) candidate.order_extraction_run_id = int(run_id) if run_id is not None else None + candidate.is_current_version = True candidate.extraction_source = extraction_source candidate.classification_confidence = classification_confidence - candidate.field_confidence_json = {} + candidate.field_confidence_json = field_confidence candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields']) candidate.evidence_json = list(dynamic['observations']) candidate.po_number = str(normalized.get('po_number') or '').strip() or None @@ -391,7 +442,7 @@ def persist_order_extraction_result( 'request_id': request_id, 'classification': classification, 'classification_confidence': classification_confidence, - 'field_confidence': {}, + 'field_confidence': field_confidence, 'field_adjudication': { 'schema_version_id': int(dynamic['extraction'].schema_version_id), 'extraction_id': int(dynamic['extraction'].id), @@ -404,6 +455,8 @@ def persist_order_extraction_result( 'missing_process_fields': assessment['missing_process_fields'], 'process_issues': assessment['process_issues'], 'auto_create_reasons': reasons, + 'low_confidence_fields': low_confidence_fields, + 'key_field_confidence_thresholds': dynamic['auto_create_key_field_thresholds'], 'verified_reservation_evidence': [ { 'line_index': int(item.get('line_position') or 0), @@ -489,13 +542,14 @@ def persist_order_extraction_result( document.order_extraction_error_code = None document.order_extraction_error_message = None - # [STEP 3] 清理同一抽取版本中消失、且尚未消费的旧 Candidate。 + # [STEP 3] 只清理同一 Run 回放中消失的候选;不同 Run 的旧版本不得删除。 for intake in intakes: active_keys = active_keys_by_intake[int(intake.id)] stale = db.session.query(ShippingNoticeCandidate).filter( ShippingNoticeCandidate.intake_id == int(intake.id), ShippingNoticeCandidate.consumed_task_id.is_(None), ShippingNoticeCandidate.extraction_source == extraction_source, + ShippingNoticeCandidate.order_extraction_run_id == (int(run_id) if run_id is not None else None), ) if active_keys: stale = stale.filter(ShippingNoticeCandidate.candidate_key.notin_(tuple(active_keys))) @@ -632,6 +686,20 @@ def submit_order_extraction_run_result( for item in snapshot_intakes if isinstance(item, dict) and str(item.get('intake_id') or '').isdigit() } + frozen_layout_candidates_by_document = { + int(document['document_id']): list(document.get('layout_schema_candidates') or []) + for intake in snapshot_intakes if isinstance(intake, dict) + for document in intake.get('documents') or [] + if isinstance(document, dict) and str(document.get('document_id') or '').isdigit() + } + frozen_evidence_text_by_document = { + int(document['document_id']): ( + frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '') + ) + for intake in snapshot_intakes if isinstance(intake, dict) + for document in intake.get('documents') or [] + if isinstance(document, dict) and str(document.get('document_id') or '').isdigit() + } intake_nos = [str(item.get('intake_no') or '').strip().upper() for item in snapshot_intakes] intake_nos = [item for item in intake_nos if item] intakes = db.session.query(ShippingNoticeIntake).filter( @@ -772,5 +840,9 @@ def submit_order_extraction_run_result( schema_version_id=int(run.schema_version_id), extraction_source='dify_workflow', frozen_context_by_intake=frozen_context_by_intake, - auto_create_enabled=bool((run.provider_config_json or {}).get('auto_create_enabled', False)), + frozen_layout_candidates_by_document=frozen_layout_candidates_by_document, + frozen_evidence_text_by_document=frozen_evidence_text_by_document, + auto_create_enabled=bool( + ((run.input_snapshot_json or {}).get('auto_creation_policy') or {}).get('enabled', False) + ), ) diff --git a/backend/app/services/shipping_notice/order_extraction_merge.py b/backend/app/services/shipping_notice/order_extraction_merge.py index 03519bbe..ae49dadc 100644 --- a/backend/app/services/shipping_notice/order_extraction_merge.py +++ b/backend/app/services/shipping_notice/order_extraction_merge.py @@ -11,6 +11,8 @@ from __future__ import annotations import copy from typing import Any +from app.services.shipping_notice.reservation_id import is_valid_reservation_id + def _field_values(fields: Any, field_code: str, codes: dict[str, str]) -> set[str]: """读取某稳定字段的非空 Observation 值,供身份和冲突比较。""" @@ -34,6 +36,60 @@ def _line_identity(line: dict[str, Any], codes: dict[str, str]) -> tuple[str, st return None +def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> str | None: + """返回唯一合法的 Reservation;缺失、冲突或错位值都不能作为跨文档关联依据。""" + values = { + value for value in _field_values(line.get('fields'), 'reservation_id', codes) + if is_valid_reservation_id(value) + } + return next(iter(values)) if len(values) == 1 else None + + +def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]: + """读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。""" + anchors: dict[str, str] = {} + for field_code in ('part_number', 'line_no'): + values = _field_values(line.get('fields'), field_code, codes) + if len(values) == 1: + anchors[field_code] = next(iter(values)) + return anchors + + +def _find_unique_reservation_completion_line( + lines: list[dict[str, Any]], incoming: dict[str, Any], codes: dict[str, str], +) -> dict[str, Any] | None: + """ + 在同 PO 的既有行中找到可安全补齐 Reservation 的唯一行。 + + 只有一侧有唯一合法 Reservation、另一侧完全缺失 Reservation,且可用料号或项次唯一匹配时返回。 + 多行重复料号、锚点冲突和不完整邮件片段一律不自动关联,交由后续人工复核。 + """ + incoming_reservation = _single_valid_reservation(incoming, codes) + incoming_anchors = _completion_anchor_values(incoming, codes) + if not incoming_anchors: + return None + + # Unit 以并发完成顺序聚合:既支持邮件先返回 Reservation、PDF 后返回订单行, + # 也支持 PDF 先返回订单行、邮件后返回 Reservation。 + requires_candidate_reservation = incoming_reservation is None + + candidate_sets: list[set[int]] = [] + for field_code, value in incoming_anchors.items(): + matches = { + index for index, candidate in enumerate(lines) + if (_single_valid_reservation(candidate, codes) is not None) == requires_candidate_reservation + and _completion_anchor_values(candidate, codes).get(field_code) == value + } + # 两侧同时带有多个锚点时必须全部一致;只靠其中一个匹配会把同料号不同项次错并。 + if not matches: + return None + candidate_sets.append(matches) + if not candidate_sets: + return None + candidates = set.intersection(*candidate_sets) + return lines[next(iter(candidates))] if len(candidates) == 1 else None + + def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[str], set[tuple[str, str]]]: """返回可用于保守合并的 PO 集合和强行身份集合。""" po_numbers = _field_values(order.get('header_fields'), 'po_number', codes) @@ -68,8 +124,10 @@ def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None: seen.add(key) -def _merge_order(target: dict[str, Any], incoming: dict[str, Any], codes: dict[str, str]) -> None: - """合并 Header 与同身份 Line;新 Line 按来源顺序追加。""" +def _merge_order( + target: dict[str, Any], incoming: dict[str, Any], codes: dict[str, str], *, matched_by_po: bool, +) -> None: + """合并 Header 与同身份 Line;同 PO 下仅允许唯一强锚点补齐缺失 Reservation。""" _merge_fields(target.setdefault('header_fields', []), incoming.get('header_fields')) target_lines = target.setdefault('lines', []) target_by_identity = { @@ -81,10 +139,17 @@ def _merge_order(target: dict[str, Any], incoming: dict[str, Any], codes: dict[s continue identity = _line_identity(raw_line, codes) if identity is None or identity not in target_by_identity: - cloned = copy.deepcopy(raw_line) - target_lines.append(cloned) - if identity is not None: - target_by_identity[identity] = cloned + completion_target = ( + _find_unique_reservation_completion_line(target_lines, raw_line, codes) + if matched_by_po else None + ) + if completion_target is not None: + _merge_fields(completion_target.setdefault('fields', []), raw_line.get('fields')) + else: + cloned = copy.deepcopy(raw_line) + target_lines.append(cloned) + if identity is not None: + target_by_identity[identity] = cloned else: _merge_fields(target_by_identity[identity].setdefault('fields', []), raw_line.get('fields')) target.setdefault('source_document_ids', []).append(incoming.get('primary_document_id')) @@ -106,12 +171,13 @@ def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[s if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no: continue candidate_pos, candidate_lines = _order_identity(candidate, codes) - if (len(po_numbers) == 1 and po_numbers == candidate_pos) or bool(line_keys & candidate_lines): + matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos + if matched_by_po or bool(line_keys & candidate_lines): match = candidate break if match is None: order['source_document_ids'] = [order.get('primary_document_id')] merged.append(order) else: - _merge_order(match, order, codes) + _merge_order(match, order, codes, matched_by_po=matched_by_po) return merged diff --git a/backend/app/services/shipping_notice/order_extraction_quality_service.py b/backend/app/services/shipping_notice/order_extraction_quality_service.py new file mode 100644 index 00000000..0450e8cf --- /dev/null +++ b/backend/app/services/shipping_notice/order_extraction_quality_service.py @@ -0,0 +1,271 @@ +""" +backend/app/services/shipping_notice/order_extraction_quality_service.py + +用途:管理 L7 影子验收批次、双人标签、质量指标和双角色批准门禁。 +依赖:订单抽取 Run/Schema/质量模型、统一 AppError。 +逻辑:只保存匿名计数和错误标志;双人完全一致的 Run 才计入指标,批准批次供 Runtime Binding 自动建单门禁引用。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + Agent, + ShippingOrderExtractionQualityBatch, + ShippingOrderExtractionQualityLabel, + ShippingOrderExtractionRun, + ShippingOrderSchemaVersion, + User, +) + + +THRESHOLDS = { + 'version': 'l7.v1', 'minimum_samples': 100, + 'minimum_precision': 0.995, 'minimum_recall': 0.98, + 'maximum_wrong_merge_rate': 0.005, 'maximum_wrong_split_rate': 0.005, + 'maximum_wrong_auto_create_count': 0, +} + + +def _batch_no() -> str: + """生成不含业务内容的影子验收批次编号。""" + return f"SOQ-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def _label_signature(label: ShippingOrderExtractionQualityLabel) -> tuple[Any, ...]: + """生成双人一致性签名;只包含匿名计数和错误标志。""" + return ( + int(label.core_expected_count), int(label.core_extracted_count), int(label.core_correct_count), + bool(label.wrong_merge), bool(label.wrong_split), bool(label.wrong_auto_create), + ) + + +def quality_metrics(batch: ShippingOrderExtractionQualityBatch) -> dict[str, Any]: + """汇总双人一致标签并计算固定 L7 指标,分歧/单人标签不计有效样本。""" + grouped: dict[int, list[ShippingOrderExtractionQualityLabel]] = {} + for label in batch.labels: + grouped.setdefault(int(label.run_id), []).append(label) + agreed = [] + disagreed = 0 + pending = 0 + for labels in grouped.values(): + if len(labels) < 2: + pending += 1 + continue + if len({_label_signature(item) for item in labels}) != 1: + disagreed += 1 + continue + agreed.append(labels[0]) + expected = sum(int(item.core_expected_count) for item in agreed) + extracted = sum(int(item.core_extracted_count) for item in agreed) + correct = sum(int(item.core_correct_count) for item in agreed) + precision = correct / extracted if extracted else 0.0 + recall = correct / expected if expected else 0.0 + sample_count = len(agreed) + wrong_merge_count = sum(1 for item in agreed if item.wrong_merge) + wrong_split_count = sum(1 for item in agreed if item.wrong_split) + wrong_auto_create_count = sum(1 for item in agreed if item.wrong_auto_create) + reasons = [] + if sample_count < THRESHOLDS['minimum_samples']: + reasons.append('insufficient_samples') + if precision < THRESHOLDS['minimum_precision']: + reasons.append('precision_below_threshold') + if recall < THRESHOLDS['minimum_recall']: + reasons.append('recall_below_threshold') + if sample_count and wrong_merge_count / sample_count > THRESHOLDS['maximum_wrong_merge_rate']: + reasons.append('wrong_merge_rate_above_threshold') + if sample_count and wrong_split_count / sample_count > THRESHOLDS['maximum_wrong_split_rate']: + reasons.append('wrong_split_rate_above_threshold') + if wrong_auto_create_count > THRESHOLDS['maximum_wrong_auto_create_count']: + reasons.append('wrong_auto_create_detected') + return { + 'thresholds': dict(THRESHOLDS), 'agreed_sample_count': sample_count, + 'pending_review_count': pending, 'disagreed_review_count': disagreed, + 'core_expected_count': expected, 'core_extracted_count': extracted, + 'core_correct_count': correct, 'precision': round(precision, 6), 'recall': round(recall, 6), + 'wrong_merge_count': wrong_merge_count, 'wrong_split_count': wrong_split_count, + 'wrong_auto_create_count': wrong_auto_create_count, + 'wrong_merge_rate': round(wrong_merge_count / sample_count, 6) if sample_count else 0.0, + 'wrong_split_rate': round(wrong_split_count / sample_count, 6) if sample_count else 0.0, + 'eligible': not reasons, 'blocking_reasons': reasons, + } + + +def serialize_quality_batch(batch: ShippingOrderExtractionQualityBatch) -> dict[str, Any]: + """返回脱敏批次、指标和批准人 ID,不返回 Run 内容或字段值。""" + metrics = quality_metrics(batch) + return { + 'id': batch.id, 'batch_no': batch.batch_no, 'owner_agent_id': batch.owner_agent_id, + 'schema_version_id': batch.schema_version_id, + 'threshold_version': batch.threshold_version, 'status': batch.status, + 'business_approved_by_id': batch.business_approved_by_id, + 'technical_approved_by_id': batch.technical_approved_by_id, + 'approved_at': batch.approved_at.isoformat() + 'Z' if batch.approved_at else None, + 'metrics': metrics, + } + + +def create_quality_batch(*, owner_agent_id: int, schema_version_id: int, actor_id: int) -> ShippingOrderExtractionQualityBatch: + """创建 collecting 批次;Owner 和 Schema 必须存在,阈值固定为当前规则。""" + schema_version = db.session.get(ShippingOrderSchemaVersion, schema_version_id) + if db.session.get(Agent, owner_agent_id) is None or schema_version is None: + raise NotFoundError('Owner Agent or Schema version not found') + if schema_version.status != 'published': + raise ValidationError('Quality batch requires the currently published Schema version') + batch = ShippingOrderExtractionQualityBatch( + batch_no=_batch_no(), owner_agent_id=owner_agent_id, schema_version_id=schema_version_id, + threshold_version=THRESHOLDS['version'], created_by_id=actor_id, + ) + db.session.add(batch) + db.session.commit() + return batch + + +def list_approved_quality_batches(*, owner_agent_id: int) -> list[dict[str, Any]]: + """列出指定 Owner 当前仍达标的批准批次,供 Runtime Binding 管理端显式选择。""" + if db.session.get(Agent, owner_agent_id) is None: + raise NotFoundError('Owner Agent not found') + from app.services.shipping_notice.order_schema.runtime import published_version + + current_schema_id = published_version().id + batches = ( + ShippingOrderExtractionQualityBatch.query + .filter_by( + owner_agent_id=owner_agent_id, schema_version_id=current_schema_id, status='approved', + ) + .order_by(ShippingOrderExtractionQualityBatch.approved_at.desc()) + .all() + ) + return [ + serialize_quality_batch(batch) for batch in batches + if batch.threshold_version == THRESHOLDS['version'] + and quality_metrics(batch)['eligible'] + ] + + +def save_quality_label(*, batch_id: int, run_no: str, actor_id: int, payload: Any) -> ShippingOrderExtractionQualityBatch: + """新增或覆盖当前管理员标签;任一批准开始后即冻结标签,Run 必须符合批次边界。""" + batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id) + if batch is None: + raise NotFoundError('Quality batch not found') + actor = db.session.get(User, actor_id) + if actor is None or actor.role != 'admin': + raise ValidationError('Quality reviewer must be an administrator') + if ( + batch.status in {'approved', 'rejected'} + or batch.business_approved_by_id is not None + or batch.technical_approved_by_id is not None + ): + raise ConflictError('Quality batch is immutable', code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE') + run = ShippingOrderExtractionRun.query.filter_by(run_no=str(run_no or '').strip()).first() + if run is None: + raise NotFoundError('Order extraction run not found') + if ( + int(run.owner_agent_id) != int(batch.owner_agent_id) + or int(run.schema_version_id) != int(batch.schema_version_id) + or run.status not in {'completed', 'needs_review'} + # 自动建单 Run 属于生产执行,不能反向作为影子质量验收样本。 + or bool((run.provider_config_json or {}).get('auto_create_enabled')) + ): + raise ValidationError( + 'Run is not eligible for this quality batch', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID', + ) + if not isinstance(payload, dict): + raise ValidationError('Label payload must be an object') + try: + expected = int(payload.get('core_expected_count')) + extracted = int(payload.get('core_extracted_count')) + correct = int(payload.get('core_correct_count')) + except (TypeError, ValueError) as exc: + raise ValidationError('Quality counts must be integers') from exc + if min(expected, extracted, correct) < 0 or correct > min(expected, extracted): + raise ValidationError('Quality counts are inconsistent') + flags = {key: payload.get(key, False) for key in ('wrong_merge', 'wrong_split', 'wrong_auto_create')} + if any(not isinstance(value, bool) for value in flags.values()): + raise ValidationError('Quality error flags must be boolean') + label = ShippingOrderExtractionQualityLabel.query.filter_by( + batch_id=batch.id, run_id=run.id, reviewer_id=actor_id, + ).first() + if label is None: + label = ShippingOrderExtractionQualityLabel(batch_id=batch.id, run_id=run.id, reviewer_id=actor_id) + db.session.add(label) + label.core_expected_count = expected + label.core_extracted_count = extracted + label.core_correct_count = correct + label.wrong_merge = flags['wrong_merge'] + label.wrong_split = flags['wrong_split'] + label.wrong_auto_create = flags['wrong_auto_create'] + db.session.flush() + batch.status = 'ready' if quality_metrics(batch)['eligible'] else 'collecting' + db.session.commit() + return batch + + +def approve_quality_batch(*, batch_id: int, role: str, actor_id: int) -> ShippingOrderExtractionQualityBatch: + """按 business/technical 角色批准;两角色必须不同管理员且指标仍达标。""" + batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id) + if batch is None: + raise NotFoundError('Quality batch not found') + if batch.status == 'rejected': + raise ConflictError('Quality batch was rejected') + actor = db.session.get(User, actor_id) + if actor is None or actor.role != 'admin': + raise ValidationError('Quality approver must be an administrator') + if not quality_metrics(batch)['eligible']: + raise ConflictError( + 'Quality thresholds are not satisfied', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_NOT_READY', + ) + now = datetime.utcnow() + if role == 'business': + if batch.business_approved_by_id is not None: + if batch.business_approved_by_id == actor_id: + return batch + raise ConflictError('Business approval is immutable') + if batch.technical_approved_by_id == actor_id: + raise ValidationError('Business and technical approvers must be different') + batch.business_approved_by_id = actor_id + batch.business_approved_at = now + elif role == 'technical': + if batch.technical_approved_by_id is not None: + if batch.technical_approved_by_id == actor_id: + return batch + raise ConflictError('Technical approval is immutable') + if batch.business_approved_by_id == actor_id: + raise ValidationError('Business and technical approvers must be different') + batch.technical_approved_by_id = actor_id + batch.technical_approved_at = now + else: + raise ValidationError('Approval role must be business or technical') + if batch.business_approved_by_id and batch.technical_approved_by_id: + batch.status = 'approved' + batch.approved_at = now + else: + batch.status = 'ready' + db.session.commit() + return batch + + +def require_approved_quality_batch( + *, batch_id: int | None, owner_agent_id: int, schema_version_id: int, +) -> ShippingOrderExtractionQualityBatch: + """校验引用的是同 Owner/Schema、当前阈值且双人批准的批次。""" + batch = db.session.get(ShippingOrderExtractionQualityBatch, int(batch_id or 0)) + if ( + batch is None or batch.status != 'approved' + or int(batch.owner_agent_id) != int(owner_agent_id) + or int(batch.schema_version_id) != int(schema_version_id) + or batch.threshold_version != THRESHOLDS['version'] + or not quality_metrics(batch)['eligible'] + ): + raise ConflictError( + 'Approved order extraction quality batch is required', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED', + ) + return batch 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 556107c0..ce3200b7 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -29,6 +29,7 @@ from app.models import ( Job, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingOrderExtractionRunIntake, ShippingOrderSchemaVersion, @@ -201,7 +202,11 @@ def _build_snapshot( intakes: list[ShippingNoticeIntake], schema_version: ShippingOrderSchemaVersion, ) -> dict[str, Any]: - """冻结 Worker 所需的完整输入;保存文档正文,后续执行不再回读可变 Document。""" + """冻结 Worker 所需的正文、布局和 Schema 映射;后续执行不再回读可变 Document。""" + from app.services.shipping_notice.order_document_profile_service import ( + published_snapshots_for_schema, + ) + intake_ids = [intake.id for intake in intakes] documents = ( db.session.query(ShippingNoticeDocument) @@ -216,8 +221,31 @@ def _build_snapshot( for asset in db.session.query(FileAsset).filter(FileAsset.id.in_(asset_ids)).all() } if asset_ids else {} documents_by_intake: dict[int, list[dict[str, Any]]] = {intake.id: [] for intake in intakes} + from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot + from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema + from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + + table_contract = compile_table_header_contract(dict(schema_version.definition_json or {})) + for document in documents: asset = assets.get(document.asset_id) if document.asset_id is not None else None + layout_snapshot = current_layout_snapshot(document) + layout_candidate = ( + layout_snapshot.get('layout_candidate') + if isinstance(layout_snapshot, dict) and isinstance(layout_snapshot.get('layout_candidate'), dict) + else None + ) + layout_schema_candidates: list[dict[str, Any]] = [] + if layout_candidate is not None: + try: + layout_schema_candidates = map_layout_document_to_schema( + layout_candidate, contract=table_contract, + ) + except (TypeError, ValueError): + layout_schema_candidates = [{ + 'mapping_status': 'failed', + 'issues': ['layout_schema_mapping_invalid'], + }] documents_by_intake[document.intake_id].append({ 'document_id': document.id, 'document_type': document.document_type, @@ -230,6 +258,8 @@ def _build_snapshot( 'parse_status': document.parse_status, 'extracted_text': document.extracted_text or '', 'parse_warnings': document.parse_warnings_json or [], + 'layout_snapshot': layout_snapshot, + 'layout_schema_candidates': layout_schema_candidates, }) incomplete = [ intake.intake_no @@ -246,7 +276,7 @@ def _build_snapshot( details={'intake_nos': incomplete}, ) return { - 'snapshot_version': 1, + 'snapshot_version': 3, 'user_id': user_id, 'owner_agent_id': owner_agent_id, 'conversation_id': conversation_id, @@ -257,6 +287,7 @@ def _build_snapshot( 'extraction_contract': dify_contract(schema_version), 'definition': schema_version.definition_json, }, + 'order_document_profiles': published_snapshots_for_schema(schema_version.id), 'intakes': [ { 'intake_id': intake.id, @@ -315,6 +346,9 @@ def create_order_extraction_run( agent_id: int, conversation_id: str, intake_nos: list[str], + reparse_of_run: ShippingOrderExtractionRun | None = None, + reparse_reason: str | None = None, + reparse_comment: str | None = None, ) -> tuple[ShippingOrderExtractionRun, bool]: """ 创建订单抽取 Run;相同服务器快照幂等复用,不同输入抢占同一 Intake 时返回冲突。 @@ -324,18 +358,47 @@ def create_order_extraction_run( agent_id: 用户入口货代 Agent 主键,不是后台 Provider ID。 conversation_id: HXOPS ChatSession.session_id;首次后台 Run 可为空,由服务端创建并绑定 Intake。 intake_nos: 1-50 个已解析且未消费的 Intake 编号。 + reparse_of_run: 可选的终态来源 Run;提供时创建新的版本化识别 Run。 + reparse_reason/reparse_comment: 用户选择的重识别原因及可选备注,仅用于审计。 Returns: `(run, reused)`;Run 与通用 Job 在同一事务创建。 """ owner_agent = _require_owner_agent(user=user, agent_id=agent_id) + if reparse_of_run is not None and ( + int(reparse_of_run.user_id) != int(user.id) + or str(reparse_of_run.status or '') not in {'completed', 'needs_review', 'failed', 'cancelled'} + ): + raise ConflictError( + 'Only a terminal run owned by the current user can be reparsed', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE', + ) intakes = _load_intakes(user_id=user.id, intake_nos=intake_nos) - from app.services.agent_runtime_binding_service import resolve_runtime_binding + from app.services.agent_runtime_binding_service import resolve_executor_governance, resolve_runtime_binding binding = resolve_runtime_binding( owner_agent_id=owner_agent.id, capability_code='shipping.order_extraction', ) schema_version = published_version() + quality_batch_id = binding.quality_batch_id + if bool((binding.config_json or {}).get('auto_create_enabled')): + from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch + + require_approved_quality_batch( + batch_id=quality_batch_id, + owner_agent_id=owner_agent.id, + schema_version_id=int(schema_version.id), + ) + # 绑定决定本业务如何执行;执行器决定所有调用方共享的容量与熔断保护,两者一起冻结到 Run。 + binding_config = { + **dict(binding.config_json or {}), + # 单元执行参数属于实现细节,使用统一保守默认值而不在应用管理形成配置分支。 + 'unit_concurrency': 2, + 'unit_max_attempts': 2, + 'unit_retry_backoff_ms': 500, + 'max_model_units': 20, + **resolve_executor_governance(binding.provider_agent), + } session = _resolve_conversation( user_id=user.id, agent_id=owner_agent.id, @@ -350,6 +413,9 @@ def create_order_extraction_run( intakes=intakes, schema_version=schema_version, ) + # 自动建单总开关与字段模板一起冻结,后续管理员变更不影响已创建 Run。 + from app.services.shipping_notice.order_schema.service import get_auto_creation_policy + snapshot['auto_creation_policy'] = get_auto_creation_policy() snapshot_hash = _sha256(snapshot) idempotency_key = _sha256({ 'user_id': user.id, @@ -359,7 +425,9 @@ def create_order_extraction_run( 'input_snapshot_hash': snapshot_hash, 'runtime_binding_id': binding.id, 'provider_agent_id': binding.provider_agent_id, - 'provider_config': binding.config_json or {}, + 'provider_config': binding_config, + 'quality_batch_id': quality_batch_id, + 'reparse_of_run_id': reparse_of_run.id if reparse_of_run is not None else None, }) existing = _run_by_idempotency_key(idempotency_key) if existing is not None: @@ -389,7 +457,8 @@ def create_order_extraction_run( owner_agent_id=owner_agent.id, runtime_binding_id=binding.id, provider_agent_id=binding.provider_agent_id, - provider_config_json=dict(binding.config_json or {}), + quality_batch_id=quality_batch_id, + provider_config_json=binding_config, provider_snapshot_json={ 'provider_agent_id': binding.provider_agent_id, 'runtime_provider': binding.provider_agent.runtime_provider, @@ -398,6 +467,9 @@ def create_order_extraction_run( 'dify_app_id': binding.provider_agent.dify_app_id, 'api_base_url': binding.provider_agent.api_base_url, }, + reparse_of_run_id=reparse_of_run.id if reparse_of_run is not None else None, + reparse_reason=str(reparse_reason or '').strip()[:64] or None, + reparse_comment=str(reparse_comment or '').strip()[:2000] or None, conversation_id=conversation_id, schema_version_id=schema_version.id, input_snapshot_hash=snapshot_hash, @@ -463,6 +535,77 @@ def create_order_extraction_run( return run, False +def reparse_order_extraction_run( + *, user_id: int, run_no: str, reason: str, comment: str | None = None, +) -> tuple[ShippingOrderExtractionRun, bool]: + """ + 基于原始未消费 Intake 创建新的订单识别版本,并冻结当前发布的规则快照。 + + 核心逻辑:锁定来源 Run 并复用同一活跃后继 Run;新 Run 不复用 Provider 成功缓存, + 因此 Schema、Binding、Profile 与布局快照均从当前发布态重新冻结。 + + Args: + user_id: 当前用户 ID;只能重识别自己的终态 Run。 + run_no: 来源 Run 编号。 + reason: 必填的受控业务原因;用于审计和后续差异解释。 + comment: 可选补充说明,不写入 Provider 输入。 + + Returns: + `(run, reused)`;重复请求返回同一活跃后继 Run。 + """ + source = ( + db.session.query(ShippingOrderExtractionRun) + .filter_by(user_id=user_id, run_no=str(run_no or '').strip()) + .with_for_update() + .first() + ) + if source is None: + raise NotFoundError('Shipping order extraction run not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND') + if str(source.status or '') not in {'completed', 'needs_review', 'failed', 'cancelled'}: + raise ConflictError( + 'Only terminal order extraction runs can be reparsed', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE', details={'status': source.status}, + ) + normalized_reason = str(reason or '').strip().lower() + if normalized_reason not in {'rule_updated', 'field_mapping_error', 'document_quality', 'other'}: + raise ValidationError('Invalid reparse reason', code='SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID') + successors = ( + ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=source.id) + .order_by(ShippingOrderExtractionRun.created_at.desc()).all() + ) + active = next((item for item in successors if item.status in {'queued', 'running', 'result_persisted'}), None) + if active is not None: + return active, True + intake_nos = [ + str(item.get('intake_no') or '').strip().upper() + for item in (source.input_snapshot_json or {}).get('intakes', []) + if isinstance(item, dict) and str(item.get('intake_no') or '').strip() + ] + if not intake_nos: + raise ConflictError('The source run has no reusable intake snapshot', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE') + owner_agent = db.session.get(Agent, int(source.owner_agent_id)) + user = db.session.get(User, int(user_id)) + if owner_agent is None or user is None: + raise ConflictError('The source run cannot be reparsed', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE') + run, reused = create_order_extraction_run( + user=user, agent_id=owner_agent.id, conversation_id=source.conversation_id, intake_nos=intake_nos, + reparse_of_run=source, reparse_reason=normalized_reason, reparse_comment=comment, + ) + if not reused: + # [STEP 1] 新版尚未完成时先撤销旧候选的建单资格,防止用户在两个版本之间误建单。 + source_candidates = db.session.query(ShippingNoticeCandidate).filter( + ShippingNoticeCandidate.order_extraction_run_id == source.id, + ShippingNoticeCandidate.consumed_task_id.is_(None), + ).all() + for candidate in source_candidates: + candidate.selected_before_superseded = bool(candidate.selected) + candidate.selected = False + candidate.is_current_version = False + source.superseded_by_run_id = run.id + source.superseded_at = datetime.utcnow() + return run, reused + + def get_order_extraction_run(*, user_id: int, run_no: str) -> ShippingOrderExtractionRun: """按用户与 Run 编号查询;跨用户访问统一表现为不存在。""" run = ShippingOrderExtractionRun.query.filter_by(user_id=user_id, run_no=run_no).first() @@ -516,6 +659,13 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr ) snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {} + if config.get('retired_protocol') is True: + raise ConflictError( + 'The failed run uses a retired order extraction protocol. Create a new extraction instead.', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_PROTOCOL_RETIRED', + details={'run_no': run.run_no}, + ) snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else [] if not snapshot_intakes or any( not isinstance(item, dict) or not isinstance(item.get('deterministic_context'), dict) @@ -579,6 +729,33 @@ def list_order_extraction_runs( return query.order_by(ShippingOrderExtractionRun.created_at.desc()).limit(min(max(limit, 1), 100)).all() +def _reparse_difference_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None: + """返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。""" + source = run.reparse_source + if source is None: + return None + current = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + previous = source.input_snapshot_json if isinstance(source.input_snapshot_json, dict) else {} + current_schema = current.get('schema') if isinstance(current.get('schema'), dict) else {} + previous_schema = previous.get('schema') if isinstance(previous.get('schema'), dict) else {} + current_profiles = current.get('order_document_profiles') if isinstance(current.get('order_document_profiles'), list) else [] + previous_profiles = previous.get('order_document_profiles') if isinstance(previous.get('order_document_profiles'), list) else [] + profile_checksums = lambda values: sorted( + str(item.get('checksum') or '') for item in values if isinstance(item, dict) + ) + def layout_versions(snapshot: dict[str, Any]) -> list[str]: + return sorted( + str((document.get('layout_snapshot') or {}).get('version') or '') + for intake in snapshot.get('intakes') or [] if isinstance(intake, dict) + for document in intake.get('documents') or [] if isinstance(document, dict) + ) + return { + 'schema_changed': str(current_schema.get('checksum') or '') != str(previous_schema.get('checksum') or ''), + 'profile_changed': profile_checksums(current_profiles) != profile_checksums(previous_profiles), + 'layout_changed': layout_versions(current) != layout_versions(previous), + } + + def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, Any]: """输出用户态 Run 与通用进度投影;不返回正文、Provider、Job 或节点诊断字段。""" intake_snapshot = run.input_snapshot_json.get('intakes', []) if isinstance(run.input_snapshot_json, dict) else [] @@ -601,6 +778,13 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, 'schema_version': schema_snapshot.get('version'), 'schema_checksum': schema_snapshot.get('checksum'), 'attempt_count': int(run.attempt_count or 0), + 'reparse': { + 'source_run_no': run.reparse_source.run_no if run.reparse_source is not None else None, + 'superseding_run_no': run.superseding_run.run_no if run.superseding_run is not None else None, + 'reason': run.reparse_reason, + 'superseded_at': run.superseded_at.isoformat() + 'Z' if run.superseded_at else None, + 'difference_summary': _reparse_difference_summary(run), + }, 'progress': { 'version': int(run.progress_version or 0), 'current_stage_code': run.current_stage_code or ('queued' if run.status == 'queued' else None), @@ -611,10 +795,9 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, 'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None, }, 'result': run.result_json, - 'error': ( - {'code': run.error_code, 'message': run.error_message} - if run.error_code or run.error_message else None - ), + # Worker/provider error text can contain upstream details. Workspace cards only need a + # stable code to select a safe, actionable user hint; full diagnostics stay admin-only. + 'error': {'code': run.error_code} if run.error_code else None, 'created_at': run.created_at.isoformat() + 'Z' if run.created_at else None, 'updated_at': run.updated_at.isoformat() + 'Z' if run.updated_at else None, 'started_at': run.started_at.isoformat() + 'Z' if run.started_at else None, @@ -631,7 +814,9 @@ def serialize_order_extraction_message_state(run: ShippingOrderExtractionRun) -> return { 'status': 'failed' if failed else 'partially_completed' if partial else 'completed' if completed else 'extracting', 'phase': 'failed' if failed else 'result_persisted' if run.status == 'result_persisted' else 'llm_extraction', - 'message': str(run.error_message or '') if failed else '', + # The chat log is user-visible on history replay. It must follow the same redaction + # boundary as the workspace Run API and never persist upstream error text. + 'message': '', 'created_count': int(result.get('created_count') or 0), 'opened_existing_count': int(result.get('opened_existing_count') or 0), 'pending_count': int(result.get('pending_count') or 0), @@ -866,8 +1051,8 @@ def list_order_extraction_diagnostic_runs( def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | None, run_no: str) -> dict[str, Any]: - """读取一个 Run 的脱敏诊断详情、Job 尝试与节点生命周期,并审计管理员访问。""" - from app.models import Job, ShippingOrderExtractionProgressEvent, ShippingOrderExtractionUnit + """读取 Run 的脱敏诊断、单元状态和证据门禁原因;不返回值、引文或版面内部 ID。""" + from app.models import Job, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderExtractionUnit run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no).first() if run is None: @@ -885,6 +1070,25 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | .order_by(ShippingOrderExtractionUnit.position.asc()).all() if run.extraction_plan else [] ) + extractions = ShippingOrderExtraction.query.filter_by(run_id=run.id).order_by( + ShippingOrderExtraction.id.asc(), + ).all() + evidence_issue_counts: dict[str, int] = {} + traceable_observation_count = 0 + accepted_observation_count = 0 + for extraction in extractions: + validation = extraction.validation_result_json if isinstance(extraction.validation_result_json, dict) else {} + for issue in validation.get('deterministic_table_issues') or []: + if not isinstance(issue, dict): + continue + reason = str(issue.get('reason') or 'unknown_layout_evidence_issue')[:128] + evidence_issue_counts[reason] = evidence_issue_counts.get(reason, 0) + 1 + for observation in extraction.observations: + if not observation.evidence_verified: + continue + accepted_observation_count += 1 + if observation.evidence_ref: + traceable_observation_count += 1 payload = { 'run': _serialize_order_extraction_diagnostic_run(run), 'job_attempts': [{ @@ -918,6 +1122,15 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | 'duration_ms': _diagnostic_elapsed_ms(unit.started_at, unit.finished_at), 'error_code': unit.error_code, } for unit in units], + 'evidence_gate': { + 'accepted_observation_count': accepted_observation_count, + 'traceable_observation_count': traceable_observation_count, + 'traceable_rate': ( + round(traceable_observation_count / accepted_observation_count, 4) + if accepted_observation_count else 1.0 + ), + 'issue_counts': evidence_issue_counts, + }, } _write_order_extraction_diagnostic_audit( admin_user_id=admin_user_id, @@ -1004,6 +1217,7 @@ def transition_order_extraction_run( intake.order_extraction_status = 'failed' intake.order_extraction_error_code = run.error_code intake.order_extraction_error_message = run.error_message + _restore_candidates_after_failed_reparse(run) elif target_status == 'cancelled': run.finished_at = now for intake in intake_rows: @@ -1022,6 +1236,26 @@ def transition_order_extraction_run( return run +def _restore_candidates_after_failed_reparse(run: ShippingOrderExtractionRun) -> None: + """新版重识别失败时恢复来源版本候选,避免业务被失败 Run 永久锁死。""" + source_id = run.reparse_of_run_id + if source_id is None: + return + source = db.session.get(ShippingOrderExtractionRun, int(source_id)) + if source is None or source.superseded_by_run_id != run.id: + return + candidates = db.session.query(ShippingNoticeCandidate).filter( + ShippingNoticeCandidate.order_extraction_run_id == source.id, + ShippingNoticeCandidate.consumed_task_id.is_(None), + ).all() + for candidate in candidates: + candidate.is_current_version = True + candidate.selected = bool(candidate.selected_before_superseded) + candidate.selected_before_superseded = None + source.superseded_by_run_id = None + source.superseded_at = None + + def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -> None: """在主业务事务内投影HXOPS落库阶段,避免与冻结输入校验产生跨Session写竞争。""" if run.status in {'completed', 'needs_review', 'failed', 'cancelled'}: diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index cbe64bee..19e22d72 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -2,8 +2,8 @@ backend/app/services/shipping_notice/order_extraction_workflow.py 用途:把订单抽取 Run 冻结快照编译为 Dify Workflow inputs,并校验结构化 outputs。 -依赖:DifyService、context_fields.dify_exposure、ShippingOrderExtractionRun、统一错误类型。 -逻辑:Provider 只接收字符串化抽取契约、文档及受控只读上下文;输出必须是成功 Workflow 中的 orders 数组。 +依赖:DifyService、MinerU 紧凑快照、context_fields.dify_exposure、统一错误类型。 +逻辑:PDF 优先使用 MinerU 分页文本和表格网格,Provider 只接收剥离布局内部载荷后的文档及受控上下文。 """ from __future__ import annotations @@ -16,7 +16,12 @@ import requests from app.core.errors import ServiceUnavailableError, ValidationError from app.services.dify import DifyService from app.services.shipping_notice.context_fields.dify_exposure import compile_readonly_context -from app.services.shipping_notice.notice_line_table import inspect_notice_table_text +from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.document_layout.order_profile import ( + OrderDocumentProfile, + OrderProfileColumnRule, + parse_html_table_with_order_profile, +) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract @@ -37,7 +42,7 @@ def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]] def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]: """ - 从 Run 不可变快照构建版本化 Dify 执行清单。 + 从 Run 不可变快照构建唯一的 Dify 执行清单。 核心逻辑:将 Run 标识、完整性哈希、LLM 抽取契约、冻结文档和受控只读提示 收敛为唯一 Start 输入,防止 Workflow 变量随契约演进而漂移。 @@ -48,37 +53,315 @@ def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str, Returns: dict[str, str]: 仅含 execution_manifest JSON 字符串的 Dify inputs。 """ + return _build_unique_workflow_inputs(run, unit=unit) + + +def _compact_layout_schema_candidates(document: dict[str, Any]) -> list[dict[str, Any]]: + """ + 把 L4 字段候选压缩为 unit.v3 模型上下文。 + + 核心逻辑:仅保留页、表、行列、稳定 field_id、值、短引文、质量状态和问题码; + 严禁把 bbox、token、HTML、cell 内部标识或 field_code 发送给模型。 + + Args: + document: Run 中冻结的单个 Document 快照。 + + Returns: + list[dict[str, Any]]: 可供 LLM 补充的紧凑结构化表格候选。 + """ + result: list[dict[str, Any]] = [] + for candidate in document.get('layout_schema_candidates') or []: + if not isinstance(candidate, dict): + continue + rows: list[dict[str, Any]] = [] + for row in candidate.get('rows') or []: + if not isinstance(row, dict): + continue + rows.append({ + 'row_index': int(row.get('row_index') or 0), + 'role': str(row.get('role') or 'data'), + 'fields': [{ + 'column_index': int(field.get('column_index') or 0), + 'field_id': str(field.get('field_id') or ''), + 'value': field.get('value'), + 'quote': str(field.get('quote') or field.get('value') or '')[:1000], + } for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_id')], + 'issues': sorted({str(item) for item in row.get('issues') or [] if str(item)}), + }) + result.append({ + 'candidate_id': f"p{int(candidate.get('page_no') or 1)}:{str(candidate.get('table_id') or '')}", + 'page_no': int(candidate.get('page_no') or 1), + 'table_id': str(candidate.get('table_id') or ''), + 'continuation_of': candidate.get('continuation_of'), + 'status': str(candidate.get('mapping_status') or 'candidate'), + 'field_policy': 'locked' if candidate.get('mapping_status') == 'accepted' else 'suggested', + 'rows': rows, + 'issues': sorted({str(item) for item in candidate.get('issues') or [] if str(item)}), + }) + return result + + +def frozen_document_text_for_dify(document: dict[str, Any]) -> str: + """ + 将冻结 MinerU 文本块和 HTML 表格转换为 LLM 可读的分页纯文本。 + + 核心逻辑:按页和页面坐标恢复阅读顺序;表格展开为 TSV 以保留行列关系。 + HTML、bbox、cell_id 和 Provider 原始响应不得出现在返回文本中。 + + Args: + document: Run 中冻结的 PDF Document 快照。 + + Returns: + str: 可替换旧 PDF `extracted_text` 的紧凑文本;快照不可用时返回空字符串。 + """ + if str(document.get('filename') or '').lower().rsplit('.', 1)[-1] != 'pdf': + return '' + layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {} + if layout.get('status') != 'ready': + return '' + entries: list[tuple[int, float, float, int, str]] = [] + for block in layout.get('text_blocks') or []: + if not isinstance(block, dict): + continue + text = ' '.join(str(block.get('text') or '').split()).strip() + bbox = block.get('normalized_bbox') if isinstance(block.get('normalized_bbox'), dict) else {} + if text: + entries.append(( + int(block.get('page_no') or 1), float(bbox.get('y0') or 0), + float(bbox.get('x0') or 0), 0, text, + )) + for table_index, table in enumerate(layout.get('tables') or [], 1): + if not isinstance(table, dict) or not str(table.get('html') or '').strip(): + continue + try: + grid = parse_html_grid(str(table['html']), table_id=str(table.get('table_id') or table_index)) + except ValidationError: + continue + rows = [] + for row in grid.rows: + values = [ + ' '.join(slot.text.split()).strip() if slot is not None else '' + for slot in row + ] + rows.append('\t'.join(values).rstrip()) + table_text = f"[TABLE {table_index}]\n" + '\n'.join(item for item in rows if item.strip()) + bbox = table.get('normalized_bbox') if isinstance(table.get('normalized_bbox'), dict) else {} + entries.append(( + int(table.get('page_no') or 1), float(bbox.get('y0') or 0), + float(bbox.get('x0') or 0), 1, table_text, + )) + if not entries: + return '' + pages: list[str] = [] + current_page: int | None = None + for page_no, _y, _x, _kind, text in sorted(entries): + if page_no != current_page: + pages.append(f'[PAGE {page_no}]') + current_page = page_no + pages.append(text) + return '\n'.join(pages).strip() + + +def _build_unique_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]: + """ + 构建唯一清单,给 LLM 发送紧凑表格候选而非版面原始数据。 + + 核心逻辑:PDF 优先使用 MinerU 分页文本与 TSV 表格,失败时保留旧文本;Document + 删除所有布局载荷,字段候选独立放入 structured_table_candidates。 + + Args: + run: 已冻结输入快照的抽取 Run。 + unit: 当前抽取计划单元。 + + Returns: + dict[str, str]: 仅含 execution_manifest 的 Dify Start 输入。 + """ snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} - schema = ( - schema_snapshot.get('extraction_contract') - if isinstance(schema_snapshot.get('extraction_contract'), dict) - else {} - ) + schema = schema_snapshot.get('extraction_contract') if isinstance(schema_snapshot.get('extraction_contract'), dict) else {} intake, document = _unit_snapshot(run, unit) readonly_snapshot = {**snapshot, 'intakes': [intake]} + document_for_dify = dict(document) + candidates = _compact_layout_schema_candidates(document_for_dify) + mineru_text = frozen_document_text_for_dify(document_for_dify) + if mineru_text: + document_for_dify['extracted_text'] = mineru_text + document_for_dify['text_source'] = 'mineru' + else: + document_for_dify['text_source'] = 'legacy' + for key in ('layout_snapshot', 'layout_schema_candidates', 'layout_candidate', 'deterministic_table_candidates'): + document_for_dify.pop(key, None) manifest = { - 'contract_version': 'shipping_order_extraction.unit.v2', 'run': {'run_no': str(run.run_no)}, 'unit': { - 'unit_id': int(unit.id), - 'unit_type': str(unit.unit_type), - 'intake_id': int(unit.intake_id), - 'intake_no': str(intake.get('intake_no') or ''), - 'document_id': int(unit.document_id), - 'document_type': str(unit.document_type), + 'unit_id': int(unit.id), 'unit_type': str(unit.unit_type), + 'intake_id': int(unit.intake_id), 'intake_no': str(intake.get('intake_no') or ''), + 'document_id': int(unit.document_id), 'document_type': str(unit.document_type), }, 'integrity': {'input_snapshot_hash': str(run.input_snapshot_hash)}, 'extraction_contract': schema, - 'documents': [{ - 'intake_id': int(unit.intake_id), - 'intake_no': str(intake.get('intake_no') or ''), - 'document': dict(document), - }], + 'document': document_for_dify, + 'structured_table_candidates': candidates, 'readonly_hints': compile_readonly_context(readonly_snapshot), } + return {'execution_manifest': json.dumps(manifest, ensure_ascii=False, separators=(',', ':'))} + + +def _frozen_order_profile(raw: dict[str, Any]) -> OrderDocumentProfile: + """从 Run 快照恢复 Profile 纯契约;不查询当前数据库版本。""" + definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {} + return OrderDocumentProfile( + profile_code=str(raw.get('profile_code') or ''), + version=int(raw.get('version') or 0), + structure_fingerprint=str(definition.get('structure_fingerprint') or ''), + header_row_index=definition.get('header_row_index'), + data_start_row_index=definition.get('data_start_row_index'), + row_structure=definition.get('row_structure', 'preserved'), + column_rules=[OrderProfileColumnRule(**{ + key: value for key, value in rule.items() if key != 'target_fields' + }) for rule in definition.get('column_rules') or [] if isinstance(rule, dict)], + drop_zero_qty=definition.get('drop_zero_qty', True), + ) + + +def _profile_snapshot_targets_valid(raw: dict[str, Any], *, contract: Any) -> bool: + """确认 Profile 冻结的 field_id/code 与 Run Schema 完全一致,禁止仅凭可变名称执行。""" + definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {} + for rule in definition.get('column_rules') or []: + if not isinstance(rule, dict): + return False + codes = [str(item or '') for item in rule.get('target_field_codes') or []] + targets = rule.get('target_fields') if isinstance(rule.get('target_fields'), list) else [] + if len(codes) != len(targets): + return False + for code, target in zip(codes, targets, strict=True): + config = contract.fields_by_code.get(code) + if ( + not isinstance(target, dict) or config is None + or str(target.get('field_code') or '') != code + or str(target.get('field_id') or '') != str(config.get('field_id') or '') + ): + return False + return True + + +def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any]]: + """剥离内部 field_code,只向 Dify 暴露稳定 field_id、值和短逐字证据。""" + result: list[dict[str, Any]] = [] + for table in tables: + result.append({ + 'profile_code': table.get('profile_code'), + 'profile_version': table.get('profile_version'), + 'profile_checksum': table.get('profile_checksum'), + 'table_id': table.get('table_id'), + 'page_no': table.get('page_no'), + 'rows': [{ + 'row_index': row.get('row_index'), + 'status': row.get('status'), + 'fields': [{ + 'field_id': field.get('field_id'), + 'value': field.get('value'), + 'quote': field.get('quote'), + } for field in row.get('fields') or [] if isinstance(field, dict)], + 'issues': list(row.get('issues') or []), + } for row in table.get('rows') or [] if isinstance(row, dict)], + }) + return result + + +def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]: + """ + 用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。 + + 同一表命中多个 Profile 或命中 unsupported Profile 时设 blocking,调用方不得自动选择。 + """ + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {} + contract = compile_table_header_contract(definition) + profiles = [ + item for item in snapshot.get('order_document_profiles') or [] + if isinstance(item, dict) + and int(item.get('schema_version_id') or 0) == int(run.schema_version_id) + ] + _intake, document = _unit_snapshot(run, unit) + layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {} + if layout.get('status') != 'ready' or not profiles: + return {'matched': False, 'blocking': False, 'tables': [], 'issues': []} + result_tables: list[dict[str, Any]] = [] + issues: list[str] = [] + matched_any = False + for raw_table in layout.get('tables') or []: + if not isinstance(raw_table, dict) or not str(raw_table.get('html') or '').strip(): + continue + table_id = str(raw_table.get('table_id') or '') + matches: list[tuple[dict[str, Any], Any]] = [] + for raw_profile in profiles: + if not _profile_snapshot_targets_valid(raw_profile, contract=contract): + issues.append('order_profile_snapshot_field_mismatch') + continue + try: + parsed = parse_html_table_with_order_profile( + str(raw_table['html']), + table_id=table_id, + profile=_frozen_order_profile(raw_profile), + contract=contract, + ) + except (TypeError, ValueError): + issues.append('order_profile_snapshot_invalid') + continue + if parsed.matched: + matches.append((raw_profile, parsed)) + if not matches: + continue + matched_any = True + if len(matches) != 1: + issues.append('order_profile_multiple_matches') + continue + raw_profile, parsed = matches[0] + if parsed.issues: + issues.extend(parsed.issues) + continue + grid = parse_html_grid(str(raw_table['html']), table_id=table_id) + compact_rows: list[dict[str, Any]] = [] + for row in parsed.rows: + if row.status == 'deleted': + compact_rows.append({'row_index': row.row_index, 'status': 'deleted', 'fields': []}) + continue + quote = ' | '.join( + slot.text.strip() for slot in grid.rows[row.row_index] + if slot is not None and slot.text.strip() + )[:1000] + fields: list[dict[str, Any]] = [] + for code, value in row.fields.items(): + config = contract.fields_by_code.get(code) + if config is None: + continue + fields.append({ + 'field_id': str(config.get('field_id') or ''), + 'field_code': code, + 'value': value, + 'quote': quote, + }) + compact_rows.append({ + 'row_index': row.row_index, + 'status': row.status, + 'fields': fields, + 'issues': row.issues, + }) + result_tables.append({ + 'profile_code': str(raw_profile.get('profile_code') or ''), + 'profile_version': int(raw_profile.get('version') or 0), + 'profile_checksum': str(raw_profile.get('checksum') or ''), + 'table_id': table_id, + 'page_no': int(raw_table.get('page_no') or 1), + 'rows': compact_rows, + }) return { - 'execution_manifest': json.dumps(manifest, ensure_ascii=False, separators=(',', ':')), + 'matched': matched_any, + 'blocking': bool(issues), + 'tables': result_tables, + 'issues': sorted(set(issues)), } @@ -140,8 +423,8 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[ def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]: - """强制单元结果只能引用当前 Intake/Document,阻止跨附件伪造关联或证据。""" - intake, _document = _unit_snapshot(run, unit) + """强制单元来源边界及 accepted 字段锁,阻止跨附件引用或覆盖确定性值。""" + intake, document = _unit_snapshot(run, unit) intake_no = str(intake.get('intake_no') or '').strip().upper() for order in orders: if str(order.get('source_intake_no') or '').strip().upper() != intake_no: @@ -168,11 +451,59 @@ def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) - 'Unit observation references another document', code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', ) + _validate_locked_layout_fields(document, orders=orders) return orders +def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dict[str, Any]]) -> None: + """ + 校验模型完整保留 accepted 版面字段,不允许删改后端确定性映射。 + + Args: + document: 当前 Unit 的冻结 Document,可能含 accepted 或 needs_review 候选。 + orders: Dify 返回的单 Unit 订单。 + + Raises: + ValidationError: accepted 候选值缺失或被替换;needs_review 候选不参与锁定。 + """ + locked: dict[str, set[str]] = {} + for candidate in document.get('layout_schema_candidates') or []: + if not isinstance(candidate, dict) or candidate.get('mapping_status') != 'accepted': + continue + for row in candidate.get('rows') or []: + if not isinstance(row, dict) or row.get('role') == 'deleted': + continue + for field in row.get('fields') or []: + if not isinstance(field, dict) or not field.get('field_id'): + continue + locked.setdefault(str(field['field_id']), set()).add( + json.dumps(field.get('value'), ensure_ascii=False, sort_keys=True), + ) + if not locked: + return + returned: dict[str, set[str]] = {} + for order in orders: + groups = [order.get('header_fields') or []] + groups.extend(line.get('fields') or [] for line in order.get('lines') or [] if isinstance(line, dict)) + for fields in groups: + for field in fields if isinstance(fields, list) else []: + if not isinstance(field, dict) or str(field.get('field_id') or '') not in locked: + continue + field_id = str(field['field_id']) + for observation in field.get('observations') or []: + if isinstance(observation, dict): + returned.setdefault(field_id, set()).add( + json.dumps(observation.get('value'), ensure_ascii=False, sort_keys=True), + ) + if any(returned.get(field_id, set()) != values for field_id, values in locked.items()): + raise ValidationError( + 'Workflow changed or omitted an accepted layout field', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', + ) + + def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None: - """完整确定性表格单元直接生成动态订单;无法覆盖必填字段时返回 None 交给模型。""" + """仅 accepted layout 完整表可零 Provider;其他结构或纯文本一律交给模型补充。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} schema = ( @@ -182,83 +513,92 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An ) definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {} intake, document = _unit_snapshot(run, unit) - inspected = inspect_notice_table_text( - str(document.get('extracted_text') or ''), - contract=compile_table_header_contract(definition), + layout_order = _build_accepted_layout_order( + unit=unit, intake=intake, document=document, schema=schema, definition=definition, ) - rows = inspected.get('lines') if isinstance(inspected.get('lines'), list) else [] - if not rows or inspected.get('ambiguous_fields'): + if layout_order is not None: + return [layout_order] + return None + + +def _build_accepted_layout_order( + *, unit: Any, intake: dict[str, Any], document: dict[str, Any], + schema: dict[str, Any], definition: dict[str, Any], +) -> dict[str, Any] | None: + """ + 把唯一且完整的 accepted L4 表格转换为零 Provider 订单。 + + Args: + unit: 当前抽取单元,用于固定 document_id。 + intake: 当前冻结 Intake,用于固定 source_intake_no。 + document: 含 layout_schema_candidates 的冻结 Document。 + schema: Dify 抽取契约元信息。 + definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。 + + Returns: + 完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。 + """ + candidates = [ + item for item in document.get('layout_schema_candidates') or [] + if isinstance(item, dict) and item.get('mapping_status') == 'accepted' + ] + if len(candidates) != 1 or candidates[0].get('issues'): return None fields = [ item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True) and item.get('collection_mode', 'llm_extraction') == 'llm_extraction' ] - by_code = {str(item.get('field_code') or ''): item for item in fields} - text = str(document.get('extracted_text') or '') - - def quote_for(row: dict[str, Any]) -> str: - part_number = str(row.get('part_number') or '') - return next((line.strip() for line in text.splitlines() if part_number and part_number in line), part_number) - + by_id = {str(item.get('field_id') or ''): item for item in fields} line_groups: list[dict[str, Any]] = [] - for row in rows: - quote = quote_for(row) - raw_fields = [] - for code, value in row.items(): - config = by_code.get(str(code)) - if config is None or config.get('scope') != 'line' or value in (None, ''): - continue - raw_fields.append({ - 'field_id': str(config['field_id']), - 'observations': [{ - 'value': value, - 'document_id': int(unit.document_id), - 'quote': quote, - 'confidence': 1.0, - }], - }) - line_groups.append({'fields': raw_fields}) - - header_fields = [] - for code, config in by_code.items(): - if config.get('scope') != 'header': + header_values: dict[str, list[dict[str, Any]]] = {} + for row in candidates[0].get('rows') or []: + if not isinstance(row, dict) or row.get('role') in {'deleted', 'empty', 'summary', 'repeated_header'}: continue - values = {str(row.get(code)) for row in rows if row.get(code) not in (None, '')} - if len(values) == 1: - value = next(iter(values)) - header_fields.append({ - 'field_id': str(config['field_id']), - 'observations': [{ - 'value': value, - 'document_id': int(unit.document_id), - 'quote': quote_for(rows[0]), - 'confidence': 1.0, - }], - }) - + line_fields: list[dict[str, Any]] = [] + for raw in row.get('fields') or []: + if not isinstance(raw, dict): + continue + field_id = str(raw.get('field_id') or '') + config = by_id.get(field_id) + if config is None or raw.get('value') in (None, ''): + continue + observation = { + 'value': raw.get('value'), 'document_id': int(unit.document_id), + 'quote': str(raw.get('quote') or raw.get('value') or '')[:1000], 'confidence': 1.0, + } + if config.get('scope') == 'header': + header_values.setdefault(field_id, []).append(observation) + else: + line_fields.append({'field_id': field_id, 'observations': [observation]}) + if line_fields: + line_groups.append({'fields': line_fields}) + header_fields = [] + for field_id, observations in header_values.items(): + unique = {json.dumps(item['value'], ensure_ascii=False, sort_keys=True) for item in observations} + if len(unique) != 1: + return None + header_fields.append({'field_id': field_id, 'observations': [observations[0]]}) + if not line_groups: + return None present_header = {item['field_id'] for item in header_fields} for config in fields: if not config.get('required'): continue - field_id = str(config['field_id']) + field_id = str(config.get('field_id') or '') if config.get('scope') == 'header' and field_id not in present_header: return None if config.get('scope') == 'line' and any( field_id not in {item['field_id'] for item in group['fields']} for group in line_groups ): return None - return [{ - 'schema_version_id': schema.get('schema_version_id'), - 'schema_checksum': schema.get('checksum'), - 'classification': 'shipping_request', - 'classification_confidence': 1.0, + return { + 'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'), + 'classification': 'shipping_request', 'classification_confidence': 1.0, 'source_intake_no': str(intake.get('intake_no') or ''), 'primary_document_id': int(unit.document_id), - 'header_fields': header_fields, - 'lines': line_groups, - 'conflicts': [], - }] + 'header_fields': header_fields, 'lines': line_groups, 'conflicts': [], + } def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]: diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 52eabc51..13269a07 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -8,6 +8,7 @@ backend/app/services/shipping_notice/order_schema/runtime.py from __future__ import annotations +import hashlib import re from datetime import date, datetime from decimal import Decimal, InvalidOperation @@ -162,9 +163,11 @@ def _quote_supports_value(value: Any, config: dict[str, Any], quote: str) -> boo return bool(normalized_value) and normalized_value in normalized_quote -def _verified_observations(raw: dict[str, Any], config: dict[str, Any], - documents: dict[int, ShippingNoticeDocument]) -> list[dict[str, Any]]: - """验证动态 Observation 的字段值、Document 归属、逐字 quote 与类型化值支持关系。""" +def _verified_observations( + raw: dict[str, Any], config: dict[str, Any], documents: dict[int, ShippingNoticeDocument], + frozen_evidence_text_by_document: dict[int, str] | None = None, +) -> list[dict[str, Any]]: + """验证动态 Observation;优先使用该 Run 实际发送给 Dify 的冻结文本,旧正文仅作回退。""" items = raw.get('observations') if isinstance(raw.get('observations'), list) else [] verified: list[dict[str, Any]] = [] for item in items: @@ -175,7 +178,9 @@ def _verified_observations(raw: dict[str, Any], config: dict[str, Any], quote = str(item.get('quote') or '').strip() if document is None or value is None or not _validate(value, config): continue - if not quote or quote not in str(document.extracted_text or ''): + frozen_text = str((frozen_evidence_text_by_document or {}).get(int(document.id)) or '') + source_texts = [frozen_text, str(document.extracted_text or '')] + if not quote or not any(quote in text for text in source_texts if text): continue if not _quote_supports_value(value, config, quote): continue @@ -189,6 +194,11 @@ def _verified_observations(raw: dict[str, Any], config: dict[str, Any], 'quote': quote, 'confidence': confidence, 'source_type': _source_type(document), + 'evidence_ref': ( + f'document:{int(document.id)}:quote:' + f'{hashlib.sha256(quote.encode("utf-8")).hexdigest()[:24]}' + ), + 'evidence_metadata': {'kind': 'text_quote'}, }) return verified @@ -223,9 +233,11 @@ def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, raw: dict[str, Any], config: dict[str, Any], documents: dict[int, ShippingNoticeDocument], - backend_candidates: list[dict[str, Any]]) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]: + backend_candidates: list[dict[str, Any]], + frozen_evidence_text_by_document: dict[int, str] | None = None, +) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]: """持久化字段全部 Observation、最终 Decision 和可查询类型化 Value。""" - candidates = _verified_observations(raw, config, documents) + candidates = _verified_observations(raw, config, documents, frozen_evidence_text_by_document) candidates.extend(backend_candidates) observation_rows: list[ShippingOrderFieldObservation] = [] for item in candidates: @@ -234,6 +246,8 @@ def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, source_document_id=int(item['document'].id), source_type=item['source_type'], extractor=item.get('extractor') or 'dify_dynamic_schema', raw_value_json=_json_value(item['value']), normalized_value_json=_json_value(item['value']), evidence_quote=item['quote'], + evidence_ref=item.get('evidence_ref'), + evidence_metadata_json=item.get('evidence_metadata'), confidence=Decimal(str(item['confidence'])), evidence_verified=True, ) db.session.add(row) @@ -263,57 +277,138 @@ def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, 'id': int(item.id), 'field_id': config['field_id'], 'line_id': line_id, 'source_type': item.source_type, 'document_id': item.source_document_id, 'value': item.normalized_value_json, 'evidence_verified': bool(item.evidence_verified), + 'confidence': float(item.confidence), + 'evidence_ref': item.evidence_ref, + 'evidence_kind': ( + item.evidence_metadata_json.get('kind') + if isinstance(item.evidence_metadata_json, dict) else None + ), } for item in observation_rows] decision_payload = { 'id': int(decision.id), 'field_id': config['field_id'], 'field_code': config['field_code'], 'line_id': line_id, 'status': status, 'value': _json_value(value), 'reason_code': reason, 'observation_ids': list(decision.supporting_observation_ids_json or []), + # 保守取所有已采纳证据的最低置信度,防止一条低可信来源被高可信来源掩盖。 + 'confidence': min((float(item.confidence) for item in observation_rows), default=0.0), } return value, status, observations, decision_payload -def _backend_rows( +def _layout_rows( documents: list[ShippingNoticeDocument], *, schema_definition: dict[str, Any], + layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """从 EML/PDF Document 保留列边界的文本生成后端表格观察原料。""" - contract = compile_table_header_contract(schema_definition) + """ + 读取 Run 冻结的 accepted layout cell 候选;纯文本猜列只生成复核原因。 + + Args: + documents: 当前 Intake 锁定 Document。 + schema_definition: Run 冻结 Schema,用于 field_id/code 一致性校验。 + layout_candidates_by_document: document_id 到冻结 L4 candidates 的映射。 + + Returns: + 可形成 verified Observation 的 accepted 行,以及机器可读阻断原因。 + """ + fields_by_id = { + str(item.get('field_id') or ''): str(item.get('field_code') or '') + for item in schema_definition.get('fields') or [] if isinstance(item, dict) + } + document_map = {int(item.id): item for item in documents} rows: list[dict[str, Any]] = [] issues: list[dict[str, Any]] = [] + frozen = layout_candidates_by_document or {} for document in documents: - inspected = inspect_notice_table_text(str(document.extracted_text or ''), contract=contract) - parsed_rows = inspected['lines'] - if inspected['ambiguous_fields']: - issues.append({ - 'document_id': int(document.id), - 'reason': 'ambiguous_table_headers', - 'field_codes': list(inspected['ambiguous_fields']), - }) - for position, raw in enumerate(parsed_rows): - if isinstance(raw, dict): - rows.append({**raw, '_document': document, '_position': position}) + candidates = frozen.get(int(document.id)) or [] + if not candidates: + inspected = inspect_notice_table_text( + str(document.extracted_text or ''), + contract=compile_table_header_contract(schema_definition), + ) + if inspected.get('lines') or inspected.get('ambiguous_fields'): + issues.append({ + 'document_id': int(document.id), + 'reason': 'plain_text_table_has_no_cell_evidence', + 'field_codes': sorted({ + str(code) for row in inspected.get('lines') or [] if isinstance(row, dict) + for code, value in row.items() if value not in (None, '') + } | {str(code) for code in inspected.get('ambiguous_fields') or []}), + }) + continue + for candidate in candidates: + if not isinstance(candidate, dict) or candidate.get('mapping_status') != 'accepted': + issues.append({ + 'document_id': int(document.id), + 'reason': 'layout_table_needs_review', + 'field_codes': sorted({ + fields_by_id.get(str(field.get('field_id') or ''), '') + for row in candidate.get('rows') or [] if isinstance(row, dict) + for field in row.get('fields') or [] if isinstance(field, dict) + } - {''}), + }) + continue + for raw_row in candidate.get('rows') or []: + if not isinstance(raw_row, dict) or raw_row.get('role') in {'deleted', 'empty', 'summary', 'repeated_header'}: + continue + row: dict[str, Any] = { + '_document': document, + '_page_no': int(candidate.get('page_no') or 1), + '_table_id': str(candidate.get('table_id') or ''), + '_row_index': int(raw_row.get('row_index') or 0), + '_evidence': {}, + } + for field in raw_row.get('fields') or []: + if not isinstance(field, dict): + continue + field_id = str(field.get('field_id') or '') + code = fields_by_id.get(field_id) + if not code or not field.get('cell_id') or not field.get('evidence_ref'): + continue + row[code] = field.get('value') + row['_evidence'][code] = { + 'evidence_ref': str(field['evidence_ref']), + 'quote': str(field.get('quote') or field.get('value') or '')[:1000], + 'metadata': { + 'kind': 'layout_cell', 'page_no': row['_page_no'], + 'table_id': row['_table_id'], 'row_index': row['_row_index'], + 'column_index': int(field.get('column_index') or 0), + 'cell_id': str(field['cell_id']), + }, + } + if row['_evidence']: + rows.append(row) + unknown_ids = set(frozen) - set(document_map) + if unknown_ids: + issues.append({'document_id': None, 'reason': 'layout_candidate_document_mismatch', 'field_codes': []}) return rows, issues def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, Any]], rows: list[dict[str, Any]]) -> list[dict[str, Any]]: - """使用当前动态行任一稳定字段值关联后端表格行,避免按行号或目标字段自证。""" - signatures: list[tuple[str, Any]] = [] + """仅用同 Document 的强身份字段关联 layout 行,禁止 Qty 等常见值导致跨文档串行。""" + strong_codes = { + 'part_number', 'customer_part_number', 'aws_part_number', + 'reservation_id', 'line_no', 'po_number', + } + signatures: list[tuple[str, Any, int]] = [] for raw in raw_fields: if not isinstance(raw, dict): continue config = configs.get(str(raw.get('field_id') or '')) - if config is None: + if config is None or str(config.get('field_code') or '') not in strong_codes: continue for item in raw.get('observations') or []: if not isinstance(item, dict): continue value = _normalize(item.get('value'), config) - if value is not None: - signatures.append((str(config['field_code']), value)) + document_id = item.get('document_id') + if value is not None and str(document_id or '').isdigit(): + signatures.append((str(config['field_code']), value, int(document_id))) configs_by_code = {str(item['field_code']): item for item in configs.values()} matched = [] for row in rows: - for code, expected in signatures: + for code, expected, document_id in signatures: + if int(row['_document'].id) != document_id: + continue config = configs_by_code.get(code) if config is None or row.get(code) in (None, ''): continue @@ -324,7 +419,7 @@ def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: - """从已关联后端表格行读取当前字段候选,用于一致或冲突裁决。""" + """从已关联 accepted layout cell 读取当前字段候选,用于一致或冲突裁决。""" if not rows: return [] code = str(config['field_code']) @@ -335,9 +430,13 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) - value = _normalize(row.get(code), config) if value is None or not _validate(value, config): continue + evidence = row.get('_evidence', {}).get(code) if isinstance(row.get('_evidence'), dict) else None + if not isinstance(evidence, dict): + continue result.append({ - 'value': value, 'document': row['_document'], 'quote': None, 'confidence': 0.9, - 'source_type': 'backend_table', 'extractor': 'backend_table', + 'value': value, 'document': row['_document'], 'quote': evidence['quote'], 'confidence': 1.0, + 'source_type': 'attachment_table', 'extractor': 'layout_schema_mapping', + 'evidence_ref': evidence['evidence_ref'], 'evidence_metadata': evidence['metadata'], }) return result @@ -351,6 +450,8 @@ def persist_dynamic_order( actor_id: int | None, schema_version_id: int | None = None, frozen_mail_context: dict[str, Any] | None = None, + layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None, + frozen_evidence_text_by_document: dict[int, str] | None = None, ) -> dict[str, Any]: """按当前 published 或 Run 锁定版本裁决订单,返回下游投影与阻断字段。""" version = ( @@ -407,7 +508,10 @@ def persist_dynamic_order( observations.extend(context_observations) decisions.extend(context_decisions) blocked.extend(context_blocked) - backend_rows, table_issues = _backend_rows(documents, schema_definition=version.definition_json or {}) + backend_rows, table_issues = _layout_rows( + documents, schema_definition=version.definition_json or {}, + layout_candidates_by_document=layout_candidates_by_document, + ) for issue in table_issues: blocked.extend(str(code) for code in issue['field_codes']) groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [ @@ -438,6 +542,7 @@ def persist_dynamic_order( value, status, field_observations, decision = _persist_field( extraction=extraction, line_id=line_id, raw=raw, config=config, documents=document_map, backend_candidates=_backend_candidates(config, rows=associated_rows), + frozen_evidence_text_by_document=frozen_evidence_text_by_document, ) observations.extend(field_observations) decision['line_position'] = position @@ -455,6 +560,7 @@ def persist_dynamic_order( value, status, field_observations, decision = _persist_field( extraction=extraction, line_id=line_id, raw={}, config=config, documents=document_map, backend_candidates=_backend_candidates(config, rows=associated_rows), + frozen_evidence_text_by_document=frozen_evidence_text_by_document, ) decision['line_position'] = position observations.extend(field_observations) @@ -490,4 +596,17 @@ def persist_dynamic_order( 'observations': observations, 'decisions': decisions, 'customer_matches': customer_matches, + 'auto_create_key_field_thresholds': { + str(item['field_code']): float(item['minimum_confidence']) + for item in all_configs.values() + if item.get('auto_create_key_field') is True and item.get('minimum_confidence') is not None + }, + 'required_key_field_codes': sorted({ + str(item['field_code']) + for item in all_configs.values() + if item.get('required') and ( + item.get('business_purpose') in {'part_number', 'quantity', 'reservation_id'} + or item.get('field_code') == 'po_number' + ) + }), } diff --git a/backend/app/services/shipping_notice/order_schema/service.py b/backend/app/services/shipping_notice/order_schema/service.py index 4fb430fe..6cf7c28a 100644 --- a/backend/app/services/shipping_notice/order_schema/service.py +++ b/backend/app/services/shipping_notice/order_schema/service.py @@ -112,6 +112,30 @@ def _definition(version: ShippingOrderSchemaVersion) -> dict[str, Any]: return _copy_json(version.definition_json or {'schema_code': SCHEMA_CODE, 'version': version.version, 'fields': []}) +def _auto_creation_policy(raw: Any) -> dict[str, Any]: + """校验订单解析自动建单开关;字段阈值由各字段配置独立维护。""" + policy = raw if isinstance(raw, dict) else {} + enabled = policy.get('enabled', False) + if not isinstance(enabled, bool): + raise ValidationError('auto_creation_policy.enabled must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + return {'enabled': enabled} + + +def get_auto_creation_policy() -> dict[str, Any]: + """返回订单解析运行策略;Schema 未初始化时默认关闭自动建单。""" + schema = _schema() + return _auto_creation_policy(schema.auto_creation_policy_json if schema else {}) + + +def save_auto_creation_policy(raw: Any, *, actor_id: int | None) -> dict[str, Any]: + """更新订单解析自动建单总开关,不修改字段模板或历史版本。""" + schema = _require_schema() + schema.auto_creation_policy_json = _auto_creation_policy(raw) + schema.updated_by_id = actor_id + db.session.commit() + return get_auto_creation_policy() + + def _enabled_fields(definition: dict[str, Any]) -> list[dict[str, Any]]: """筛选当前版本实际生效字段,供发布门禁和 Dify 运行契约复用。""" return [dict(item) for item in definition.get('fields') or [] if item.get('enabled', True)] @@ -308,6 +332,7 @@ def get_state() -> dict[str, Any]: 'display_name': schema.display_name, 'description': schema.description, 'status': schema.status, + 'auto_creation_policy': get_auto_creation_policy(), }, # Retired fields remain available to historical records, not the current configuration workspace. 'fields': [_field_payload(item) for item in ShippingOrderField.query.filter_by( @@ -793,7 +818,7 @@ def delete_field( def _field_runtime_references(field_id: str) -> list[str]: """返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。""" from app.models import ( - ShippingExcelTemplate, ShippingInventoryParsingProfile, + ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingOrderDocumentProfile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ) references: list[str] = [] @@ -810,6 +835,18 @@ def _field_runtime_references(field_id: str) -> list[str]: ) if parsing_reference: references.append('inventory_parsing_profile') + order_profile_reference = any( + any( + str(target.get('field_id') or '') == field_id + for rule in (profile.definition_json or {}).get('column_rules', []) if isinstance(rule, dict) + for target in rule.get('target_fields', []) if isinstance(target, dict) + ) + for profile in ShippingOrderDocumentProfile.query.filter( + ShippingOrderDocumentProfile.status.in_(['draft', 'published']) + ).all() + ) + if order_profile_reference: + references.append('order_document_profile') template_reference = any( any( item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id @@ -968,6 +1005,19 @@ def save_draft( if field.value_type != 'enum' and enum_options: raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') business_purpose = _business_purpose(raw.get('business_purpose'), field=field) + auto_create_key_field = raw.get('auto_create_key_field', False) + if not isinstance(auto_create_key_field, bool): + raise ValidationError('auto_create_key_field must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + raw_threshold = raw.get('minimum_confidence') + if auto_create_key_field: + try: + minimum_confidence = float(raw_threshold) + except (TypeError, ValueError) as exc: + raise ValidationError('minimum_confidence is required for key field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') from exc + if not 0 <= minimum_confidence <= 1: + raise ValidationError('minimum_confidence must be between 0 and 1', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + else: + minimum_confidence = None context_source = _context_source_snapshot(raw, field=field) dify_exposure_policy, available_for_customer_identity = _version_context_policy( raw, source=context_source, @@ -996,6 +1046,8 @@ def save_draft( 'display_name': display_name, 'description': str(raw.get('description') or '').strip() or None, 'business_purpose': business_purpose, + 'auto_create_key_field': auto_create_key_field, + 'minimum_confidence': round(minimum_confidence, 2) if minimum_confidence is not None else None, 'required': required, 'aliases': aliases, 'normalizer_key': normalizer, @@ -1011,7 +1063,11 @@ def save_draft( 'available_for_customer_identity': available_for_customer_identity, 'sequence': sequence, }) - after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields} + after = { + 'schema_code': version.schema.schema_code, + 'version': version.version, + 'fields': normalized_fields, + } compile_table_header_contract(after) version.definition_json = after version.lock_version += 1 diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 25b2c5bf..2da61ba6 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -146,16 +146,27 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]: job_type=JobType.SHIPPING_NOTICE_PARSE, on_recovered=sync_intake_after_parse_job_recovery, ) - count = int(run_count) + int(parse_count) + from app.services.shipping_notice.document_layout.lifecycle import sync_layout_after_job_recovery + + layout_count = recover_stale_jobs( + domain=SHIPPING_NOTICE_JOB_DOMAIN, + timeout_seconds=float(current_app.config.get( + 'SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', 360, + ) or 360), + job_type=JobType.SHIPPING_DOCUMENT_LAYOUT, + on_recovered=sync_layout_after_job_recovery, + ) + count = int(run_count) + int(parse_count) + int(layout_count) cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs() if cleanup_warnings: logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5])) if count: logger.warning( - 'recovered %s stale shipping_notice job(s) (run=%s parse=%s)', + 'recovered %s stale shipping_notice job(s) (run=%s parse=%s layout=%s)', count, run_count, parse_count, + layout_count, ) if cleanup_count: logger.info('processed %s rpa callback cleanup job(s)', cleanup_count) @@ -178,6 +189,7 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_NOTICE_RUN, JobType.SHIPPING_NOTICE_PARSE, JobType.SHIPPING_ORDER_EXTRACTION, + JobType.SHIPPING_DOCUMENT_LAYOUT, ], ) diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 27a2f4cc..271630c2 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -11,10 +11,8 @@ from __future__ import annotations import re from typing import Any -# 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位) -RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$") -# 部分库存源使用带字母/连字符的业务单号,如 AWS-311、ORD-3002、R-1。 -RESERVATION_ID_BUSINESS_RE = re.compile(r"^[A-Z0-9][A-Z0-9._/-]{1,63}$", re.IGNORECASE) +# Reservation ID 业务契约固定为 5 位或 10 位纯数字。 +RESERVATION_ID_NUMERIC_RE = re.compile(r"^(?:\d{5}|\d{10})$") # 数据库主键、哈希或 UUID 不属于业务 Reservation ID。 INTERNAL_HEX_ID_RE = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE) INTERNAL_UUID_RE = re.compile( @@ -22,7 +20,7 @@ INTERNAL_UUID_RE = re.compile( re.IGNORECASE, ) # Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351 -RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{8,12})\b") +RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{10}|\d{5})\b") PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, @@ -101,7 +99,7 @@ def find_reservation_id_in_document(text: str) -> str: def looks_like_reservation_id(value: Any) -> bool: - """判断标准化后的值是否符合 8~12 位纯数字 Reservation ID 格式。""" + """判断标准化后的值是否符合 5 位或 10 位纯数字 Reservation ID 格式。""" text = normalize_reservation_id(value) return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text)) @@ -110,10 +108,10 @@ def is_valid_reservation_id(value: Any, *, numeric_only: bool = False) -> bool: """ 判断候选值是否可作为业务 Reservation ID。 - 核心逻辑:默认兼容数字型与现有字母型业务单号,但明确拒绝 32 位 hex、UUID、纯字母等内部或弱语义值。 + 核心逻辑:只接受 5 位或 10 位纯数字;字母型编号、其他长度数字、hex 和 UUID 均拒绝。 Args: value: 待校验的原始值。 - numeric_only: 为 True 时仅接受 8~12 位纯数字,用于明确的 External Reservation 模板。 + numeric_only: 兼容既有调用签名;当前统一契约始终只接受 5 位或 10 位纯数字。 Returns: bool: 值是否满足当前 Reservation ID 契约。 @@ -121,15 +119,7 @@ def is_valid_reservation_id(value: Any, *, numeric_only: bool = False) -> bool: text = extract_reservation_id(value) if not text or INTERNAL_HEX_ID_RE.fullmatch(text) or INTERNAL_UUID_RE.fullmatch(text): return False - if RESERVATION_ID_NUMERIC_RE.fullmatch(text): - return True - if numeric_only: - return False - return bool( - RESERVATION_ID_BUSINESS_RE.fullmatch(text) - and re.search(r"[A-Z]", text, re.IGNORECASE) - and re.search(r"\d", text) - ) + return bool(RESERVATION_ID_NUMERIC_RE.fullmatch(text)) def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str: diff --git a/backend/migrations/versions/a68f8091a2b4_add_order_document_profiles.py b/backend/migrations/versions/a68f8091a2b4_add_order_document_profiles.py new file mode 100644 index 00000000..97e3158c --- /dev/null +++ b/backend/migrations/versions/a68f8091a2b4_add_order_document_profiles.py @@ -0,0 +1,94 @@ +"""Add versioned shipping order document profiles. + +Revision ID: a68f8091a2b4 +Revises: a67f8091a2b3 +Create Date: 2026-07-21 23:40:00.000000 + +用途:持久化订单模板结构指纹、固定列规则、Schema 绑定和发布生命周期。 +依赖:shipping_order_schema_versions、users。 +逻辑:同一 profile_code 版本递增且只能有一个 published;Run 使用完整 JSON 快照而不是依赖可变当前行。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'a68f8091a2b4' +down_revision = 'a67f8091a2b3' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建订单文档 Profile 版本表及发布唯一门禁。""" + op.add_column( + 'shipping_notice_documents', + sa.Column('layout_snapshot_json', sa.JSON(), nullable=True), + ) + op.create_table( + 'shipping_order_document_profiles', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('profile_code', sa.String(length=64), nullable=False), + sa.Column('display_name', sa.String(length=128), nullable=False), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=16), server_default='draft', nullable=False), + sa.Column('schema_version_id', sa.Integer(), nullable=False), + sa.Column('structure_fingerprint', sa.String(length=64), nullable=False), + sa.Column('definition_json', sa.JSON(), nullable=False), + sa.Column('checksum', sa.String(length=64), nullable=True), + sa.Column('lock_version', sa.Integer(), server_default='1', nullable=False), + sa.Column('change_note', sa.Text(), nullable=True), + sa.Column('source_profile_id', sa.Integer(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=True), + sa.Column('published_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('published_at', sa.DateTime(), nullable=True), + sa.Column('retired_at', sa.DateTime(), nullable=True), + sa.CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_shipping_order_document_profiles_status', + ), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['published_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']), + sa.ForeignKeyConstraint(['source_profile_id'], ['shipping_order_document_profiles.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint( + 'profile_code', 'version', name='uq_shipping_order_document_profiles_code_version', + ), + ) + op.create_index( + 'ix_shipping_order_document_profiles_schema_status', + 'shipping_order_document_profiles', ['schema_version_id', 'status'], unique=False, + ) + op.create_index( + 'ix_shipping_order_document_profiles_fingerprint', + 'shipping_order_document_profiles', ['structure_fingerprint'], unique=False, + ) + op.create_index( + 'uq_shipping_order_document_profiles_one_published', + 'shipping_order_document_profiles', ['profile_code'], unique=True, + postgresql_where=sa.text("status = 'published'"), + sqlite_where=sa.text("status = 'published'"), + ) + + +def downgrade() -> None: + """移除订单文档 Profile 表。""" + op.drop_index( + 'uq_shipping_order_document_profiles_one_published', + table_name='shipping_order_document_profiles', + ) + op.drop_index( + 'ix_shipping_order_document_profiles_fingerprint', + table_name='shipping_order_document_profiles', + ) + op.drop_index( + 'ix_shipping_order_document_profiles_schema_status', + table_name='shipping_order_document_profiles', + ) + op.drop_table('shipping_order_document_profiles') + op.drop_column('shipping_notice_documents', 'layout_snapshot_json') diff --git a/backend/migrations/versions/a69f8091a2b5_add_document_layout_lifecycle.py b/backend/migrations/versions/a69f8091a2b5_add_document_layout_lifecycle.py new file mode 100644 index 00000000..e56a9bca --- /dev/null +++ b/backend/migrations/versions/a69f8091a2b5_add_document_layout_lifecycle.py @@ -0,0 +1,182 @@ +"""Add versioned shipping document layout lifecycle. + +Revision ID: a69f8091a2b5 +Revises: a68f8091a2b4 +Create Date: 2026-07-22 02:20:00.000000 + +用途:将 Document 单 JSON 布局快照迁移为版本化状态、checksum、质量结果和 Worker 租约。 +依赖:shipping_notice_documents、jobs。 +逻辑:旧快照回填为 version=1/current;downgrade 恢复当前 payload,再移除生命周期表。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime + +import sqlalchemy as sa +from alembic import op + + +revision = 'a69f8091a2b5' +down_revision = 'a68f8091a2b4' +branch_labels = None +depends_on = None + + +def _encoded_payload(value) -> tuple[str, int]: + """返回旧 JSON 快照的稳定 checksum 和 UTF-8 字节数。""" + encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() + return hashlib.sha256(encoded).hexdigest(), len(encoded) + + +def upgrade() -> None: + """创建布局版本表、回填旧快照并切换 Document 当前版本外键。""" + op.create_index( + 'uq_jobs_shipping_document_layout_active_ref', 'jobs', + ['domain', 'job_type', 'business_ref'], unique=True, + postgresql_where=sa.text( + "job_type = 'shipping_document_layout' AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + sqlite_where=sa.text( + "job_type = 'shipping_document_layout' AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + ) + op.create_table( + 'shipping_document_layout_versions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('document_id', sa.Integer(), nullable=False), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=24), server_default='queued', nullable=False), + sa.Column('source_content_hash', sa.String(length=64), nullable=False), + sa.Column('parser_key', sa.String(length=128), nullable=False), + sa.Column('parser_name', sa.String(length=32), nullable=False), + sa.Column('parser_version', sa.String(length=64), nullable=True), + sa.Column('backend', sa.String(length=32), nullable=True), + sa.Column('contract_version', sa.String(length=64), nullable=False), + sa.Column('payload_json', sa.JSON(), nullable=True), + sa.Column('payload_checksum', sa.String(length=64), nullable=True), + sa.Column('payload_size_bytes', sa.Integer(), server_default='0', nullable=False), + sa.Column('quality_json', sa.JSON(), nullable=True), + sa.Column('issues_json', sa.JSON(), nullable=False), + sa.Column('job_id', sa.Integer(), nullable=True), + sa.Column('lease_token', sa.String(length=64), nullable=True), + sa.Column('attempt_count', sa.Integer(), server_default='0', nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.CheckConstraint( + "status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')", + name='ck_shipping_document_layout_status', + ), + sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['job_id'], ['jobs.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('document_id', 'version', name='uq_shipping_document_layout_document_version'), + ) + op.create_index( + 'ix_shipping_document_layout_document_status', 'shipping_document_layout_versions', + ['document_id', 'status'], unique=False, + ) + op.create_index( + 'ix_shipping_document_layout_content_parser', 'shipping_document_layout_versions', + ['source_content_hash', 'parser_key'], unique=False, + ) + op.create_index( + 'ix_shipping_document_layout_versions_job_id', 'shipping_document_layout_versions', + ['job_id'], unique=False, + ) + op.create_index( + 'uq_shipping_document_layout_one_active', 'shipping_document_layout_versions', + ['document_id'], unique=True, + postgresql_where=sa.text("status IN ('queued', 'running')"), + sqlite_where=sa.text("status IN ('queued', 'running')"), + ) + with op.batch_alter_table('shipping_notice_documents') as batch: + batch.add_column(sa.Column('current_layout_version_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_notice_documents_current_layout_version', + 'shipping_document_layout_versions', ['current_layout_version_id'], ['id'], + ondelete='SET NULL', + ) + + bind = op.get_bind() + documents = sa.table( + 'shipping_notice_documents', + sa.column('id', sa.Integer()), + sa.column('content_hash', sa.String()), + sa.column('layout_snapshot_json', sa.JSON()), + sa.column('current_layout_version_id', sa.Integer()), + ) + versions = sa.table( + 'shipping_document_layout_versions', + sa.column('id', sa.Integer()), sa.column('document_id', sa.Integer()), + sa.column('version', sa.Integer()), sa.column('status', sa.String()), + sa.column('source_content_hash', sa.String()), sa.column('parser_key', sa.String()), + sa.column('parser_name', sa.String()), sa.column('parser_version', sa.String()), + sa.column('backend', sa.String()), sa.column('contract_version', sa.String()), + sa.column('payload_json', sa.JSON()), sa.column('payload_checksum', sa.String()), + sa.column('payload_size_bytes', sa.Integer()), sa.column('quality_json', sa.JSON()), + sa.column('issues_json', sa.JSON()), sa.column('attempt_count', sa.Integer()), + sa.column('created_at', sa.DateTime()), sa.column('updated_at', sa.DateTime()), + sa.column('finished_at', sa.DateTime()), + ) + now = datetime.utcnow() + rows = bind.execute(sa.select( + documents.c.id, documents.c.content_hash, documents.c.layout_snapshot_json, + ).where(documents.c.layout_snapshot_json.is_not(None))).mappings().all() + for row in rows: + payload = row['layout_snapshot_json'] if isinstance(row['layout_snapshot_json'], dict) else {} + checksum, size = _encoded_payload(payload) + status = str(payload.get('status') or 'failed') + if status not in {'ready', 'failed', 'unsupported'}: + status = 'failed' + bind.execute(versions.insert().values( + document_id=row['id'], version=1, status=status, + source_content_hash=str(row['content_hash'] or checksum)[:64].ljust(64, '0'), + # 旧单列快照没有可验证的 parser revision,必须显式隔离以触发新生命周期重解析。 + parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:legacy', + parser_name=str(payload.get('provider') or 'mineru')[:32], + parser_version=str(payload.get('provider_version') or '')[:64] or None, + backend=str(payload.get('backend') or 'pipeline')[:32], + contract_version=str(payload.get('snapshot_version') or 'shipping_document_table_snapshot.v1')[:64], + payload_json=payload, payload_checksum=checksum, payload_size_bytes=size, + quality_json=payload.get('capability') if isinstance(payload.get('capability'), dict) else None, + issues_json=list(payload.get('issues') or []), attempt_count=1, + created_at=now, updated_at=now, finished_at=now, + )) + version_id = bind.execute(sa.select(versions.c.id).where( + versions.c.document_id == row['id'], versions.c.version == 1, + )).scalar_one() + bind.execute(documents.update().where(documents.c.id == row['id']).values( + current_layout_version_id=version_id, + )) + with op.batch_alter_table('shipping_notice_documents') as batch: + batch.drop_column('layout_snapshot_json') + + +def downgrade() -> None: + """恢复 Document 当前 JSON 快照并移除版本化布局生命周期。""" + with op.batch_alter_table('shipping_notice_documents') as batch: + batch.add_column(sa.Column('layout_snapshot_json', sa.JSON(), nullable=True)) + bind = op.get_bind() + bind.execute(sa.text( + 'UPDATE shipping_notice_documents ' + 'SET layout_snapshot_json = (' + 'SELECT payload_json FROM shipping_document_layout_versions ' + 'WHERE shipping_document_layout_versions.id = shipping_notice_documents.current_layout_version_id' + ') WHERE current_layout_version_id IS NOT NULL' + )) + with op.batch_alter_table('shipping_notice_documents') as batch: + batch.drop_constraint('fk_shipping_notice_documents_current_layout_version', type_='foreignkey') + batch.drop_column('current_layout_version_id') + op.drop_index('uq_shipping_document_layout_one_active', table_name='shipping_document_layout_versions') + op.drop_index('ix_shipping_document_layout_versions_job_id', table_name='shipping_document_layout_versions') + op.drop_index('ix_shipping_document_layout_content_parser', table_name='shipping_document_layout_versions') + op.drop_index('ix_shipping_document_layout_document_status', table_name='shipping_document_layout_versions') + op.drop_table('shipping_document_layout_versions') + op.drop_index('uq_jobs_shipping_document_layout_active_ref', table_name='jobs') diff --git a/backend/migrations/versions/a70f8091a2b6_add_order_observation_layout_evidence.py b/backend/migrations/versions/a70f8091a2b6_add_order_observation_layout_evidence.py new file mode 100644 index 00000000..c94b8c68 --- /dev/null +++ b/backend/migrations/versions/a70f8091a2b6_add_order_observation_layout_evidence.py @@ -0,0 +1,35 @@ +"""Add traceable layout evidence to order observations. + +Revision ID: a70f8091a2b6 +Revises: a69f8091a2b5 +Create Date: 2026-07-22 08:30:00.000000 + +用途:为动态订单 Observation 保存稳定 evidence_ref 与脱敏版面定位元数据。 +依赖:shipping_order_field_observations、L4 冻结 layout schema candidates。 +逻辑:upgrade 仅新增可空审计列;downgrade 完整移除,不改写历史业务值。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'a70f8091a2b6' +down_revision = 'a69f8091a2b5' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增稳定证据引用与结构化版面定位列。""" + with op.batch_alter_table('shipping_order_field_observations') as batch: + batch.add_column(sa.Column('evidence_ref', sa.String(length=512), nullable=True)) + batch.add_column(sa.Column('evidence_metadata_json', sa.JSON(), nullable=True)) + + +def downgrade() -> None: + """移除 L6 版面证据列,保留既有 Observation 值和文本 quote。""" + with op.batch_alter_table('shipping_order_field_observations') as batch: + batch.drop_column('evidence_metadata_json') + batch.drop_column('evidence_ref') diff --git a/backend/migrations/versions/a71f8091a2b7_add_order_extraction_quality_gate.py b/backend/migrations/versions/a71f8091a2b7_add_order_extraction_quality_gate.py new file mode 100644 index 00000000..a5929cb3 --- /dev/null +++ b/backend/migrations/versions/a71f8091a2b7_add_order_extraction_quality_gate.py @@ -0,0 +1,97 @@ +"""Add L7 order extraction quality gate. + +Revision ID: a71f8091a2b7 +Revises: a70f8091a2b6 +Create Date: 2026-07-22 11:10:00.000000 + +用途:新增订单抽取影子验收批次/双人标签,并允许 Runtime Binding 引用批准批次。 +依赖:agents、users、shipping_order_schema_versions、shipping_order_extraction_runs、agent_runtime_bindings。 +逻辑:质量事实独立持久化;绑定只保存批准批次外键,downgrade 先移除引用再删除质量表。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'a71f8091a2b7' +down_revision = 'a70f8091a2b6' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建 L7 质量批次/标签并增加 Runtime Binding 批准批次引用。""" + op.create_table( + 'shipping_order_extraction_quality_batches', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('batch_no', sa.String(64), nullable=False), + sa.Column('owner_agent_id', sa.Integer(), sa.ForeignKey('agents.id'), nullable=False), + sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False), + sa.Column('contract_version', sa.String(64), nullable=False, server_default='unit_v3'), + sa.Column('threshold_version', sa.String(32), nullable=False, server_default='l7.v1'), + sa.Column('status', sa.String(32), nullable=False, server_default='collecting'), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False), + sa.Column('business_approved_by_id', sa.Integer(), sa.ForeignKey('users.id')), + sa.Column('business_approved_at', sa.DateTime()), + sa.Column('technical_approved_by_id', sa.Integer(), sa.ForeignKey('users.id')), + sa.Column('technical_approved_at', sa.DateTime()), + sa.Column('approved_at', sa.DateTime()), + sa.Column('rejected_by_id', sa.Integer(), sa.ForeignKey('users.id')), + sa.Column('rejected_at', sa.DateTime()), + sa.Column('rejection_reason', sa.Text()), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint("status IN ('collecting', 'ready', 'approved', 'rejected')", name='ck_shipping_order_extraction_quality_batches_status'), + sa.UniqueConstraint('batch_no', name='uq_shipping_order_extraction_quality_batches_no'), + ) + op.create_index( + 'ix_shipping_order_extraction_quality_batches_owner_created', + 'shipping_order_extraction_quality_batches', ['owner_agent_id', 'created_at'], + ) + op.create_table( + 'shipping_order_extraction_quality_labels', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('batch_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False), + sa.Column('run_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_runs.id'), nullable=False), + sa.Column('reviewer_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False), + sa.Column('core_expected_count', sa.Integer(), nullable=False), + sa.Column('core_extracted_count', sa.Integer(), nullable=False), + sa.Column('core_correct_count', sa.Integer(), nullable=False), + sa.Column('wrong_merge', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('wrong_split', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('wrong_auto_create', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint('core_expected_count >= 0', name='ck_shipping_order_quality_expected_nonnegative'), + sa.CheckConstraint('core_extracted_count >= 0', name='ck_shipping_order_quality_extracted_nonnegative'), + sa.CheckConstraint('core_correct_count >= 0', name='ck_shipping_order_quality_correct_nonnegative'), + sa.UniqueConstraint('batch_id', 'run_id', 'reviewer_id', name='uq_shipping_order_quality_label_reviewer'), + ) + op.create_index( + 'ix_shipping_order_quality_labels_batch_run', + 'shipping_order_extraction_quality_labels', ['batch_id', 'run_id'], + ) + with op.batch_alter_table('agent_runtime_bindings') as batch: + batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_agent_runtime_bindings_quality_batch', + 'shipping_order_extraction_quality_batches', ['quality_batch_id'], ['id'], + ) + batch.create_index('ix_agent_runtime_bindings_quality_batch', ['quality_batch_id']) + + +def downgrade() -> None: + """移除 Runtime Binding 引用及 L7 质量事实表。""" + with op.batch_alter_table('agent_runtime_bindings') as batch: + batch.drop_index('ix_agent_runtime_bindings_quality_batch') + batch.drop_constraint('fk_agent_runtime_bindings_quality_batch', type_='foreignkey') + batch.drop_column('quality_batch_id') + op.drop_index('ix_shipping_order_quality_labels_batch_run', table_name='shipping_order_extraction_quality_labels') + op.drop_table('shipping_order_extraction_quality_labels') + op.drop_index( + 'ix_shipping_order_extraction_quality_batches_owner_created', + table_name='shipping_order_extraction_quality_batches', + ) + op.drop_table('shipping_order_extraction_quality_batches') diff --git a/backend/migrations/versions/a72f8091a2b8_freeze_quality_batch_on_order_extraction_run.py b/backend/migrations/versions/a72f8091a2b8_freeze_quality_batch_on_order_extraction_run.py new file mode 100644 index 00000000..72469b12 --- /dev/null +++ b/backend/migrations/versions/a72f8091a2b8_freeze_quality_batch_on_order_extraction_run.py @@ -0,0 +1,40 @@ +"""Freeze quality batch on order extraction runs. + +Revision ID: a72f8091a2b8 +Revises: a71f8091a2b7 +Create Date: 2026-07-22 11:45:00.000000 + +用途:在订单抽取 Run 上冻结自动建单质量批次,保证配置批准事实与实际执行可追溯。 +依赖:shipping_order_extraction_runs、shipping_order_extraction_quality_batches。 +逻辑:Run 创建时复制 Runtime Binding 的质量批次外键;降级只移除 Run 引用。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'a72f8091a2b8' +down_revision = 'a71f8091a2b7' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """为订单抽取 Run 增加可空质量批次外键及索引。""" + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_order_extraction_runs_quality_batch', + 'shipping_order_extraction_quality_batches', ['quality_batch_id'], ['id'], + ) + batch.create_index('ix_shipping_order_extraction_runs_quality_batch', ['quality_batch_id']) + + +def downgrade() -> None: + """移除订单抽取 Run 的质量批次引用。""" + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.drop_index('ix_shipping_order_extraction_runs_quality_batch') + batch.drop_constraint('fk_shipping_order_extraction_runs_quality_batch', type_='foreignkey') + batch.drop_column('quality_batch_id') diff --git a/backend/migrations/versions/a73f8091a2b9_remove_order_extraction_contract_versions.py b/backend/migrations/versions/a73f8091a2b9_remove_order_extraction_contract_versions.py new file mode 100644 index 00000000..12135554 --- /dev/null +++ b/backend/migrations/versions/a73f8091a2b9_remove_order_extraction_contract_versions.py @@ -0,0 +1,67 @@ +"""Remove selectable order extraction protocol versions. + +Revision ID: a73f8091a2b9 +Revises: a72f8091a2b8 +Create Date: 2026-07-22 09:30:00.000000 + +用途:订单抽取只保留唯一 execution_manifest 结构,清理运行配置和质量批次中的协议版本分支。 +依赖:agent_runtime_bindings、shipping_order_extraction_runs、shipping_order_extraction_quality_batches。 +逻辑:移除旧 JSON 配置键和质量批次列;旧 Run 保留审计事实但不能按旧协议重试。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'a73f8091a2b9' +down_revision = 'a72f8091a2b8' +branch_labels = None +depends_on = None + + +_RETIRED_BINDING_KEYS = ('workflow_contract_version', 'unit_concurrency', 'unit_max_attempts', 'unit_retry_backoff_ms', 'max_model_units', 'provider_max_concurrency', 'circuit_failure_threshold', 'circuit_cooldown_seconds', 'auto_create_enabled') + + +def _remove_json_key(table: str, column: str, *, mark_retired_runs: bool = False) -> None: + """按数据库方言清理已迁移配置键;旧 Run 标记为不可按旧快照重试。 + + 核心逻辑:Postgres 的 `json` 列不支持 `?|` / `-`,先转 jsonb 再写回 json。 + """ + dialect = op.get_bind().dialect.name + if dialect == 'postgresql': + # [STEP] SQLAlchemy JSON 在 Postgres 默认为 json;操作符仅 jsonb 可用。 + keys = ' - '.join(f"'{key}'" for key in _RETIRED_BINDING_KEYS) + replacement = f"(({column}::jsonb - {keys})" + if mark_retired_runs: + replacement = f"{replacement} || jsonb_build_object('retired_protocol', true)" + replacement = f"{replacement})::json" + op.execute(sa.text( + f"UPDATE {table} SET {column} = {replacement} " + f"WHERE {column}::jsonb ?| ARRAY[{','.join(repr(key) for key in _RETIRED_BINDING_KEYS)}]" + )) + elif dialect == 'sqlite': + paths = ', '.join(repr(f'$.{key}') for key in _RETIRED_BINDING_KEYS) + replacement = ( + f"json_set(json_remove({column}, {paths}), '$.retired_protocol', json('true'))" + if mark_retired_runs else f"json_remove({column}, {paths})" + ) + op.execute(sa.text( + f"UPDATE {table} SET {column} = {replacement} " + f"WHERE {' OR '.join(f"json_type({column}, '$.{key}') IS NOT NULL" for key in _RETIRED_BINDING_KEYS)}" + )) + + +def upgrade() -> None: + """清理版本开关并删除质量批次的协议版本列。""" + _remove_json_key('agent_runtime_bindings', 'config_json') + _remove_json_key('shipping_order_extraction_runs', 'provider_config_json', mark_retired_runs=True) + with op.batch_alter_table('shipping_order_extraction_quality_batches') as batch: + batch.drop_column('contract_version') + + +def downgrade() -> None: + """仅恢复质量批次字段;不恢复已删除的多协议运行配置。""" + with op.batch_alter_table('shipping_order_extraction_quality_batches') as batch: + batch.add_column(sa.Column('contract_version', sa.String(64), nullable=False, server_default='legacy')) diff --git a/backend/migrations/versions/a74f8091a2ba_remove_order_extraction_quality_binding.py b/backend/migrations/versions/a74f8091a2ba_remove_order_extraction_quality_binding.py new file mode 100644 index 00000000..879b0b6b --- /dev/null +++ b/backend/migrations/versions/a74f8091a2ba_remove_order_extraction_quality_binding.py @@ -0,0 +1,41 @@ +"""Remove automatic-creation quality-batch coupling. + +Revision ID: a74f8091a2ba +Revises: a73f8091a2b9 +Create Date: 2026-07-22 11:20:00.000000 + +用途:自动建单策略改由订单字段模板的运行配置管理,移除应用能力绑定和 Run 的质量批次外键。 +依赖:agent_runtime_bindings、shipping_order_extraction_runs。 +逻辑:质量批次及其标签保留用于独立质量分析,不再是自动建单的配置来源或运行门禁。 +""" + +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + + +revision = 'a74f8091a2ba' +down_revision = 'a73f8091a2b9' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """删除已废弃的质量批次外键,并增加字段模板的自动建单总开关配置。""" + with op.batch_alter_table('agent_runtime_bindings') as batch: + batch.drop_column('quality_batch_id') + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.drop_column('quality_batch_id') + with op.batch_alter_table('shipping_order_schemas') as batch: + batch.add_column(sa.Column('auto_creation_policy_json', sa.JSON(), nullable=False, server_default='{}')) + + +def downgrade() -> None: + """恢复列结构;不会恢复已移除的历史绑定关系。""" + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True)) + with op.batch_alter_table('agent_runtime_bindings') as batch: + batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True)) + with op.batch_alter_table('shipping_order_schemas') as batch: + batch.drop_column('auto_creation_policy_json') diff --git a/backend/migrations/versions/a74f8091a2c0_add_order_extraction_reparse_lineage.py b/backend/migrations/versions/a74f8091a2c0_add_order_extraction_reparse_lineage.py new file mode 100644 index 00000000..22c2b110 --- /dev/null +++ b/backend/migrations/versions/a74f8091a2c0_add_order_extraction_reparse_lineage.py @@ -0,0 +1,70 @@ +"""Add immutable reparse lineage and versioned extraction candidates. + +Revision ID: a74f8091a2c0 +Revises: a73f8091a2b9 +Create Date: 2026-07-22 12:10:00.000000 + +用途:为订单重新识别保留来源/后继 Run 审计链,并让候选按 Run 版本保存。 +依赖:shipping_order_extraction_runs、shipping_notice_candidates。 +逻辑:旧候选初始保持 current;新 Run 成功写入候选后由服务层撤销旧版本的可消费资格。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'a74f8091a2c0' +down_revision = 'a73f8091a2b9' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """增加 Run 谱系字段,并把 Candidate 唯一键收敛至同一 Run 版本。""" + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.add_column(sa.Column('reparse_of_run_id', sa.Integer(), nullable=True)) + batch.add_column(sa.Column('superseded_by_run_id', sa.Integer(), nullable=True)) + batch.add_column(sa.Column('reparse_reason', sa.String(length=64), nullable=True)) + batch.add_column(sa.Column('reparse_comment', sa.Text(), nullable=True)) + batch.add_column(sa.Column('superseded_at', sa.DateTime(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_order_extraction_runs_reparse_source', + 'shipping_order_extraction_runs', ['reparse_of_run_id'], ['id'], + ) + batch.create_foreign_key( + 'fk_shipping_order_extraction_runs_superseding_run', + 'shipping_order_extraction_runs', ['superseded_by_run_id'], ['id'], + ) + batch.create_index('ix_shipping_order_extraction_runs_reparse_of', ['reparse_of_run_id']) + batch.create_index('ix_shipping_order_extraction_runs_superseded_by', ['superseded_by_run_id']) + with op.batch_alter_table('shipping_notice_candidates') as batch: + batch.drop_constraint('uq_shipping_notice_candidates_intake_key', type_='unique') + batch.add_column(sa.Column('is_current_version', sa.Boolean(), nullable=False, server_default=sa.text('true'))) + batch.add_column(sa.Column('selected_before_superseded', sa.Boolean(), nullable=True)) + batch.create_unique_constraint( + 'uq_shipping_notice_candidates_intake_key_run', + ['intake_id', 'candidate_key', 'order_extraction_run_id'], + ) + batch.create_index('ix_shipping_notice_candidates_current_version', ['is_current_version']) + + +def downgrade() -> None: + """移除重新识别谱系;仅用于未包含版本化候选的开发环境回退。""" + with op.batch_alter_table('shipping_notice_candidates') as batch: + batch.drop_index('ix_shipping_notice_candidates_current_version') + batch.drop_constraint('uq_shipping_notice_candidates_intake_key_run', type_='unique') + batch.drop_column('selected_before_superseded') + batch.drop_column('is_current_version') + batch.create_unique_constraint('uq_shipping_notice_candidates_intake_key', ['intake_id', 'candidate_key']) + with op.batch_alter_table('shipping_order_extraction_runs') as batch: + batch.drop_index('ix_shipping_order_extraction_runs_superseded_by') + batch.drop_index('ix_shipping_order_extraction_runs_reparse_of') + batch.drop_constraint('fk_shipping_order_extraction_runs_superseding_run', type_='foreignkey') + batch.drop_constraint('fk_shipping_order_extraction_runs_reparse_source', type_='foreignkey') + batch.drop_column('superseded_at') + batch.drop_column('reparse_comment') + batch.drop_column('reparse_reason') + batch.drop_column('superseded_by_run_id') + batch.drop_column('reparse_of_run_id') diff --git a/backend/migrations/versions/a75f8091a2c1_merge_quality_and_reparse_heads.py b/backend/migrations/versions/a75f8091a2c1_merge_quality_and_reparse_heads.py new file mode 100644 index 00000000..d845b7dc --- /dev/null +++ b/backend/migrations/versions/a75f8091a2c1_merge_quality_and_reparse_heads.py @@ -0,0 +1,28 @@ +"""Merge quality-binding removal and reparse lineage heads. + +Revision ID: a75f8091a2c1 +Revises: a74f8091a2ba, a74f8091a2c0 +Create Date: 2026-07-22 10:31:00.000000 + +用途:合并两条并行 head,恢复单一 Alembic 升级路径。 +依赖:a74f8091a2ba(移除质量批次外键)、a74f8091a2c0(重新识别谱系)。 +逻辑:纯合并节点,不改表结构;upgrade/downgrade 为空。 +""" + +from __future__ import annotations + + +revision = 'a75f8091a2c1' +down_revision = ('a74f8091a2ba', 'a74f8091a2c0') +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """合并节点无 DDL。""" + pass + + +def downgrade() -> None: + """合并节点无 DDL。""" + pass diff --git a/backend/migrations/versions/a76f8091a2c2_repair_order_schema_auto_creation_policy.py b/backend/migrations/versions/a76f8091a2c2_repair_order_schema_auto_creation_policy.py new file mode 100644 index 00000000..f7e8e46c --- /dev/null +++ b/backend/migrations/versions/a76f8091a2c2_repair_order_schema_auto_creation_policy.py @@ -0,0 +1,51 @@ +""" +backend/migrations/versions/a76f8091a2c2_repair_order_schema_auto_creation_policy.py + +用途:修复 Alembic 已到 head、但订单 Schema 缺少自动建单策略列的结构漂移。 +依赖:Alembic Operations、SQLAlchemy Inspector、a75f8091a2c1 merge head。 +逻辑:升级仅在实际列缺失时补列;已正确执行旧迁移的环境保持幂等,降级仅移除该列。 +""" + +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + + +revision = 'a76f8091a2c2' +down_revision = 'a75f8091a2c1' +branch_labels = None +depends_on = None + + +def _column_exists(table_name: str, column_name: str) -> bool: + """ + 查询迁移连接中的实际列,避免结构已正确的环境重复执行 DDL。 + + Args: + table_name: 当前数据库中的目标表名。 + column_name: 需要确认的目标列名。 + + Returns: + bool: 目标列是否已存在。 + """ + inspector = sa.inspect(op.get_bind()) + return column_name in {item['name'] for item in inspector.get_columns(table_name)} + + +def upgrade() -> None: + """缺列时补充自动建单策略 JSON;已有列的环境仅推进 Alembic 版本。""" + if _column_exists('shipping_order_schemas', 'auto_creation_policy_json'): + return + with op.batch_alter_table('shipping_order_schemas') as batch: + batch.add_column(sa.Column( + 'auto_creation_policy_json', sa.JSON(), nullable=False, server_default='{}', + )) + + +def downgrade() -> None: + """存在时移除自动建单策略列,使本增量迁移可安全往返。""" + if not _column_exists('shipping_order_schemas', 'auto_creation_policy_json'): + return + with op.batch_alter_table('shipping_order_schemas') as batch: + batch.drop_column('auto_creation_policy_json') diff --git a/backend/migrations/versions/a77f8091a2c3_add_order_extraction_quality_binding.py b/backend/migrations/versions/a77f8091a2c3_add_order_extraction_quality_binding.py new file mode 100644 index 00000000..3da362ca --- /dev/null +++ b/backend/migrations/versions/a77f8091a2c3_add_order_extraction_quality_binding.py @@ -0,0 +1,46 @@ +""" +用途:为订单抽取运行绑定和 Run 冻结 L7 已批准质量批次。 +依赖:agent_runtime_bindings、shipping_order_extraction_runs、质量批次表。 +逻辑:自动建单只能引用可审计质量批次;历史手动或复核 Run 保持空值。 +""" + +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + + +revision = 'a77f8091a2c3' +down_revision = 'a76f8091a2c2' +branch_labels = None +depends_on = None + + +def _column_exists(table_name: str, column_name: str) -> bool: + """检查列是否已存在,使修复性迁移可重复执行。""" + return column_name in {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table_name)} + + +def upgrade() -> None: + """为绑定和 Run 增加可空质量批次外键,兼容既有非自动建单记录。""" + for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): + if _column_exists(table_name, 'quality_batch_id'): + continue + with op.batch_alter_table(table_name) as batch: + batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + f'fk_{table_name}_quality_batch', + 'shipping_order_extraction_quality_batches', ['quality_batch_id'], ['id'], + ) + batch.create_index(f'ix_{table_name}_quality_batch_id', ['quality_batch_id']) + + +def downgrade() -> None: + """移除质量批次外键和列,恢复上一版本模型结构。""" + for table_name in ('shipping_order_extraction_runs', 'agent_runtime_bindings'): + if not _column_exists(table_name, 'quality_batch_id'): + continue + with op.batch_alter_table(table_name) as batch: + batch.drop_index(f'ix_{table_name}_quality_batch_id') + batch.drop_constraint(f'fk_{table_name}_quality_batch', type_='foreignkey') + batch.drop_column('quality_batch_id') diff --git a/backend/scripts/build_shipping_layout_truth_workbench.py b/backend/scripts/build_shipping_layout_truth_workbench.py new file mode 100644 index 00000000..5d344ae6 --- /dev/null +++ b/backend/scripts/build_shipping_layout_truth_workbench.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +""" +backend/scripts/build_shipping_layout_truth_workbench.py + +用途:从受控 EML 样本生成仓库外的离线 PDF cell 真值标注工作台,并校验导出结果。 +依赖:MinerU adapter、pypdfium2、Pillow、OpenCV 候选和 layout annotation 契约。 +逻辑:附件仅在内存中解析;页面图、候选文本和人工 JSON 只写显式仓库外目录,控制台只输出哈希与计数。 +""" + +from __future__ import annotations + +import argparse +import html +import json +import sys +from email import policy +from email.parser import BytesParser +from hashlib import sha256 +from pathlib import Path +from typing import Any + +import numpy as np +import pypdfium2 as pdfium +from PIL import Image + +BACKEND_ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = BACKEND_ROOT.parent +if str(BACKEND_ROOT) not in sys.path: + sys.path.insert(0, str(BACKEND_ROOT)) + +from app.services.shipping_notice.document_layout.evaluation import LayoutAnnotation +from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.document_layout.mineru import ( + MinerUClient, + MinerUClientConfig, + parse_mineru_candidate, +) +from app.services.shipping_notice.document_layout.opencv_table import ( + reconstruct_opencv_table_geometry, + validate_opencv_cell_text, +) +from app.services.shipping_notice.document_layout.text_cell_alignment import ( + align_html_cells_from_positioned_text, +) + + +def _external_output_path(raw: str | Path) -> Path: + """解析并验证输出目录必须位于 Git 仓库外,避免真实样本被误提交。""" + path = Path(raw).expanduser().resolve() + try: + path.relative_to(REPOSITORY_ROOT.resolve()) + except ValueError: + return path + raise ValueError('layout truth workbench output must be outside the repository') + + +def _iter_pdf_attachments(eml_dir: Path): + """从 EML 内存读取唯一 PDF 附件;不把文件名或邮件正文写入输出。""" + seen: set[str] = set() + for eml_path in sorted(eml_dir.glob('*.eml')): + message = BytesParser(policy=policy.default).parsebytes(eml_path.read_bytes()) + for part in message.walk(): + filename = str(part.get_filename() or '') + if not filename.lower().endswith('.pdf'): + continue + content = part.get_payload(decode=True) or b'' + digest = sha256(content).hexdigest() + if not content or digest in seen: + continue + seen.add(digest) + yield digest, content + + +def _positioned_characters(text_page: Any, *, page_height: float) -> list[dict[str, Any]]: + """把 PDFium 左下原点字符框转换为版面契约使用的左上原点坐标。""" + result: list[dict[str, Any]] = [] + for index in range(text_page.count_chars()): + text = text_page.get_text_range(index, 1) + if not text: + continue + left, bottom, right, top = text_page.get_charbox(index, loose=True) + if right <= left or top <= bottom: + continue + result.append({ + 'text': text, + 'bbox': {'x0': left, 'y0': page_height - top, 'x1': right, 'y1': page_height - bottom}, + }) + return result + + +def _candidate_tables(parse_candidate: Any, pdf: Any, *, image_scale: float) -> tuple[list[dict], list[dict]]: + """生成页面图片元数据和严格 cell 候选;候选不等同人工真值。""" + pages: list[dict[str, Any]] = [] + tables: list[dict[str, Any]] = [] + page_map = {item.page_no: item for item in parse_candidate.pages} + for page_no in range(1, len(pdf) + 1): + page = pdf[page_no - 1] + width, height = page.get_size() + pages.append({'page_no': page_no, 'width': width, 'height': height}) + candidate_page = page_map.get(page_no) + if candidate_page is None or not candidate_page.tables: + continue + bitmap = page.render(scale=image_scale) + image = np.asarray(bitmap.to_numpy()).copy() + text_page = page.get_textpage() + characters = _positioned_characters(text_page, page_height=height) + for table_index, table in enumerate(candidate_page.tables): + grid = parse_html_grid(table.html, table_id=table.candidate_id) + geometry = reconstruct_opencv_table_geometry( + image, + page_width=width, + page_height=height, + table_bbox=table.bbox, + grid=grid, + ) + cell_boxes: dict[str, dict[str, float]] = {} + candidate_source = 'none' + if geometry.ready: + def bounded_text_reader(box): + return text_page.get_text_bounded( + left=box.x0, + bottom=height - box.y1, + right=box.x1, + top=height - box.y0, + ) + + validation = validate_opencv_cell_text( + geometry, + grid=grid, + bounded_text_reader=bounded_text_reader, + ) + if validation.accepted: + cell_boxes = {item.cell_id: item.normalized_bbox.model_dump() for item in geometry.cells} + candidate_source = 'opencv_text_validated' + if not cell_boxes: + alignment = align_html_cells_from_positioned_text( + grid, + characters=characters, + table_bbox=table.bbox, + page_width=width, + page_height=height, + ) + cell_boxes = {item.cell_id: item.normalized_bbox.model_dump() for item in alignment.cells} + candidate_source = 'native_text_partial' if cell_boxes else 'none' + tables.append({ + 'annotation_id': f'table-p{page_no}-{table_index}', + 'page_no': page_no, + 'table_index': table_index, + 'normalized_bbox': table.normalized_bbox.model_dump(), + 'candidate_source': candidate_source, + 'cells': [{ + 'annotation_id': f'cell-p{page_no}-{table_index}-{index}', + 'page_no': page_no, + 'table_index': table_index, + 'row_index': cell.row_index, + 'column_index': cell.column_index, + 'normalized_bbox': cell_boxes.get(cell.cell_id), + 'normalized_text': cell.text, + 'role': 'header' if cell.is_header else 'data', + 'expected_field_code': None, + } for index, cell in enumerate(grid.cells)], + }) + return pages, tables + + +def _write_page_images(pdf: Any, sample_dir: Path, *, image_scale: float) -> None: + """渲染清晰页面图供人工框选;只写仓库外样本目录。""" + for page_index in range(len(pdf)): + image = pdf[page_index].render(scale=image_scale).to_pil().convert('RGB') + image.save(sample_dir / f'page-{page_index + 1}.png', optimize=True) + + +def _workbench_html(manifest: dict[str, Any]) -> str: + """生成无外部依赖的离线标注页面,导出结果符合 annotation.v1。""" + payload = json.dumps(manifest, ensure_ascii=False).replace(' + +Shipping Layout Truth Workbench
订单 PDF Cell 真值标注 - 样本 {html.escape(manifest['sample_id'])}
+
+
+
+''' + + +def build_workbench(args: argparse.Namespace) -> int: + """调用 MinerU 并为每个唯一 PDF 生成仓库外离线标注页面。""" + source = Path(args.eml_dir).expanduser().resolve() + output = _external_output_path(args.output_dir) + output.mkdir(parents=True, exist_ok=True) + index_rows: list[str] = [] + count = 0 + for digest, content in _iter_pdf_attachments(source): + if args.limit and count >= args.limit: + break + client = MinerUClient(MinerUClientConfig( + base_url=args.mineru_url, + backend='pipeline', + read_timeout_seconds=args.timeout, + poll_interval_seconds=1, + )) + candidate = parse_mineru_candidate(client.parse_file_async(filename='sample.pdf', content=content)) + pdf = pdfium.PdfDocument(content) + sample_id = f'pdf-{digest[:12]}' + sample_dir = output / sample_id + sample_dir.mkdir(parents=True, exist_ok=True) + _write_page_images(pdf, sample_dir, image_scale=args.image_scale) + pages, tables = _candidate_tables(candidate, pdf, image_scale=args.image_scale) + manifest = { + 'sample_id': sample_id, + 'content_hash': digest, + 'categories': ['native_pdf', 'eml_attachment'], + 'pages': pages, + 'tables': tables, + } + (sample_dir / 'workbench.html').write_text(_workbench_html(manifest), encoding='utf-8') + index_rows.append(f'
  • {sample_id} - {len(pages)} pages, {len(tables)} tables
  • ') + count += 1 + print(f'generated sample={sample_id} pages={len(pages)} tables={len(tables)}') + (output / 'index.html').write_text( + '

    Shipping Layout Truth Workbench

      ' + + ''.join(index_rows) + '
    ', + encoding='utf-8', + ) + print(f'generated_count={count} output={output}') + return 0 + + +def validate_annotations(args: argparse.Namespace) -> int: + """使用正式 annotation.v1 契约校验单个 JSON 或目录中的全部导出。""" + target = Path(args.path).expanduser().resolve() + files = [target] if target.is_file() else sorted(target.rglob('*.annotation.json')) + if not files: + print('no annotation files found', file=sys.stderr) + return 2 + failed = 0 + for path in files: + try: + annotation = LayoutAnnotation.model_validate_json(path.read_text(encoding='utf-8')) + print(f'valid sample={annotation.sample_id} tables={len(annotation.tables)} cells={sum(len(t.cells) for t in annotation.tables)}') + except Exception as exc: + failed += 1 + print(f'invalid file={path.name} error={type(exc).__name__}', file=sys.stderr) + return 1 if failed else 0 + + +def parse_args() -> argparse.Namespace: + """解析 build/validate 子命令,MinerU URL 只接受运行参数,不写项目配置。""" + parser = argparse.ArgumentParser(description='Build or validate shipping layout truth workbench') + subparsers = parser.add_subparsers(dest='command', required=True) + build = subparsers.add_parser('build') + build.add_argument('--eml-dir', required=True) + build.add_argument('--output-dir', required=True) + build.add_argument('--mineru-url', required=True) + build.add_argument('--timeout', type=int, default=300) + build.add_argument('--image-scale', type=float, default=2.0) + build.add_argument('--limit', type=int, default=0) + validate = subparsers.add_parser('validate') + validate.add_argument('path') + return parser.parse_args() + + +def main() -> int: + """执行离线工作台生成或人工真值契约校验。""" + args = parse_args() + return build_workbench(args) if args.command == 'build' else validate_annotations(args) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/backend/tests/test_admin_shipping_document_layouts.py b/backend/tests/test_admin_shipping_document_layouts.py new file mode 100644 index 00000000..217cf04b --- /dev/null +++ b/backend/tests/test_admin_shipping_document_layouts.py @@ -0,0 +1,59 @@ +""" +backend/tests/test_admin_shipping_document_layouts.py + +用途:验证布局版本管理员诊断、隐私字段最小化和显式重解析幂等 API。 +依赖:admin API、layout lifecycle、统一响应 envelope。 +逻辑:普通用户拒绝;管理员只见状态/checksum/计数,重复重解析复用活动版本。 +""" + +from __future__ import annotations + +from app import db +from app.models import User +from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot +from tests.conftest import parse_api_data +from tests.test_shipping_document_layout_lifecycle import _document, _snapshot + + +def test_layout_admin_api_is_private_and_reparse_is_idempotent(app): + """诊断不得泄露 payload/html/bbox;重解析重复点击只保留一个活动版本。""" + app.config['AUTH_JWT_REQUIRED'] = False + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + with app.app_context(): + document = _document() + document_id = document.id + record_inline_layout_snapshot(document, { + **_snapshot(), 'tables': [{'html': 'secret
    ', 'bbox': {'x0': 1}}], + }) + db.session.add(User( + username='layout-admin', email='layout-admin@example.com', role='admin', status='active', + )) + db.session.commit() + + client = app.test_client() + denied = client.get( + f'/api/admin/shipping-notice/documents/{document_id}/layout-versions', + headers={'X-Username': 'layout-owner', 'X-Role': 'user'}, + ) + assert denied.status_code == 403 + + headers = {'X-Username': 'layout-admin', 'X-Role': 'admin'} + listed = client.get( + f'/api/admin/shipping-notice/documents/{document_id}/layout-versions', headers=headers, + ) + assert listed.status_code == 200 + versions = parse_api_data(listed.get_json()) + assert versions[0]['table_count'] == 1 + assert 'payload_json' not in versions[0] + assert 'html' not in str(versions[0]).lower() + assert 'bbox' not in str(versions[0]).lower() + + first = client.post( + f'/api/admin/shipping-notice/documents/{document_id}/layout-reparse', headers=headers, + ) + second = client.post( + f'/api/admin/shipping-notice/documents/{document_id}/layout-reparse', headers=headers, + ) + assert first.status_code == 202 + assert second.status_code == 202 + assert parse_api_data(first.get_json())['id'] == parse_api_data(second.get_json())['id'] diff --git a/backend/tests/test_agent_runtime_bindings.py b/backend/tests/test_agent_runtime_bindings.py index 1ce76df9..96b429ef 100644 --- a/backend/tests/test_agent_runtime_bindings.py +++ b/backend/tests/test_agent_runtime_bindings.py @@ -31,10 +31,12 @@ from app.jobs.queue import claim_next_job, recover_stale_jobs from app.jobs.types import JobType from app.models import ( Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument, - ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderSchemaVersion, User, + ShippingOrderDocumentProfile, ShippingOrderExtraction, ShippingOrderExtractionRun, + ShippingOrderSchemaVersion, User, ) from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding from app.services.admin.agent_service import update_agent_permissions +from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot from app.services.admin.agent_service import list_agents from app.services.shipping_notice.order_extraction_workflow import ( build_order_extraction_workflow_inputs, execute_order_extraction_workflow, @@ -95,6 +97,50 @@ def test_binding_catalog_exposes_internal_executor_role_constraint(app): assert binding.provider_agent.exposure_mode == 'internal' +def test_binding_rejects_retired_workflow_contract_version(app): + """唯一协议不接受历史版本开关,防止运行时重新出现双格式分支。""" + with app.app_context(): + owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid') + provider = Agent( + name='Workflow Provider', agent_code='generic', runtime_provider='dify', + dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider', + dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, + ) + db.session.add_all([owner, provider]) + db.session.commit() + + with pytest.raises(ValidationError) as caught: + save_runtime_binding( + owner_agent_id=owner.id, capability_code='shipping.order_extraction', + provider_agent_id=provider.id, enabled=True, + config={'workflow_contract_version': 'latest'}, + ) + + assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID' + + +def test_binding_rejects_retired_workflow_contract_version_with_auto_create(app): + """自动建单也不得通过历史版本配置绕过唯一协议约束。""" + with app.app_context(): + owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid') + provider = Agent( + name='Workflow Provider', agent_code='generic', runtime_provider='dify', + dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider', + dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True, + ) + db.session.add_all([owner, provider]) + db.session.commit() + + with pytest.raises(ValidationError) as caught: + save_runtime_binding( + owner_agent_id=owner.id, capability_code='shipping.order_extraction', + provider_agent_id=provider.id, enabled=True, + config={'workflow_contract_version': 'legacy', 'auto_create_enabled': True}, + ) + + assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID' + + def test_internal_executor_cannot_receive_user_permissions(app): """内部执行器只能被运行时绑定,不能进入用户授权关系。""" with app.app_context(): @@ -182,14 +228,6 @@ def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_ assert saved.get_json()['data']['config'] == { 'timeout_seconds': 600, 'max_attempts': 2, - 'unit_concurrency': 2, - 'unit_max_attempts': 2, - 'unit_retry_backoff_ms': 500, - 'max_model_units': 20, - 'provider_max_concurrency': 4, - 'circuit_failure_threshold': 5, - 'circuit_cooldown_seconds': 60, - 'auto_create_enabled': False, } assert 'dify_api_key' not in saved.get_json()['data'] @@ -473,7 +511,9 @@ def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app): ) run_snapshot = { 'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1, + 'schema_version_id': 1, 'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {}, + 'provider_config_json': {}, } unit_snapshot = { 'id': 1, 'intake_id': 1, 'document_id': 1, @@ -500,8 +540,8 @@ def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app): record_failure.assert_not_called() -def test_workflow_inputs_use_frozen_extraction_contract_only(app): - """Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。""" +def test_workflow_inputs_use_unique_extraction_contract_only(app): + """唯一 Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。""" with app.app_context(): user, agent, session, intake, _document = _seed_run_input() run, _ = create_order_extraction_run( @@ -511,21 +551,19 @@ def test_workflow_inputs_use_frozen_extraction_contract_only(app): inputs = build_order_extraction_workflow_inputs(run, unit=unit) manifest = json.loads(inputs['execution_manifest']) schema = manifest['extraction_contract'] - documents = manifest['documents'] + document = manifest['document'] readonly_context = manifest['readonly_hints'] assert schema == run.input_snapshot_json['schema']['extraction_contract'] - assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2' + assert 'contract_version' not in manifest assert manifest['run']['run_no'] == run.run_no assert manifest['unit']['unit_id'] == unit.id assert manifest['unit']['document_id'] == unit.document_id assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash assert 'definition' not in schema assert schema['fields'][0]['field_id'] == 'qty-id' - assert len(documents) == 1 - assert set(documents[0]) == {'intake_id', 'intake_no', 'document'} - assert documents[0]['document']['document_id'] == unit.document_id - assert 'sales-' not in repr(documents).lower() + assert document['document_id'] == unit.document_id + assert 'sales-' not in repr(document).lower() assert readonly_context == [] assert set(inputs) == {'execution_manifest'} @@ -551,7 +589,7 @@ def test_workflow_execution_sends_only_versioned_manifest(app): inputs = mocked_run.call_args.kwargs['inputs'] manifest = json.loads(inputs['execution_manifest']) assert set(inputs) == {'execution_manifest'} - assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2' + assert 'contract_version' not in manifest assert manifest['run']['run_no'] == run.run_no assert manifest['unit']['unit_id'] == unit.id assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash @@ -559,8 +597,140 @@ def test_workflow_execution_sends_only_versioned_manifest(app): assert metadata['workflow_run_id'] == 'wf-manifest' -def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app): - """冻结 Schema 可完整解析的表格单元必须零模型调用,并缓存可恢复的局部订单。""" +def test_unique_manifest_sends_compact_layout_candidates_only(app): + """唯一 Manifest 只发送紧凑字段候选,禁止泄漏 bbox、HTML、token、cell_id 或 field_code。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='UNIT-V3') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + unit = run.extraction_plan.units[0] + frozen = run.input_snapshot_json['intakes'][0]['documents'][0] + frozen['layout_snapshot'] = {'html': 'RAW-HTML', 'bbox': [1, 2, 3, 4]} + frozen['layout_schema_candidates'] = [{ + 'page_no': 2, 'table_id': 'table-1', 'mapping_status': 'candidate', + 'issues': ['layout_table_not_accepted'], + 'rows': [{ + 'row_index': 3, 'role': 'data', 'issues': [], + 'fields': [{ + 'field_id': 'qty-id', 'field_code': 'qty', 'value': 30, + 'quote': 'Qty 30', 'column_index': 4, 'cell_id': 'secret-cell', + 'token_ids': ['secret-token'], 'evidence_ref': 'secret-ref', + }], + }], + }] + + manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest']) + + assert 'contract_version' not in manifest + assert manifest['structured_table_candidates'][0]['field_policy'] == 'suggested' + assert manifest['structured_table_candidates'][0]['rows'][0]['fields'] == [{ + 'column_index': 4, 'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30', + }] + assert 'documents' not in manifest + serialized = repr({ + 'document': manifest['document'], + 'structured_table_candidates': manifest['structured_table_candidates'], + }) + for forbidden in ('RAW-HTML', 'bbox', 'secret-cell', 'secret-token', 'secret-ref', 'field_code'): + assert forbidden not in serialized + + +def test_unique_manifest_prefers_mineru_pdf_text_and_table_grid(app): + """PDF 有 ready MinerU 快照时应向模型发送分页文本和 TSV 表格,替换旧拍平文本。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='MINERU-TEXT') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + unit = run.extraction_plan.units[0] + frozen = run.input_snapshot_json['intakes'][0]['documents'][0] + frozen['filename'] = 'order.pdf' + frozen['extracted_text'] = 'LEGACY-FLAT-TEXT' + frozen['layout_snapshot'] = { + 'status': 'ready', + 'text_blocks': [{ + 'page_no': 1, 'normalized_bbox': {'x0': 0.1, 'y0': 0.1}, + 'text': 'PO Number: 4518838154', + }], + 'tables': [{ + 'table_id': 'table-1', 'page_no': 1, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.3}, + 'html': '' + '
    ItemReservation ID
    0002012345
    ', + }], + } + + manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest']) + + document = manifest['document'] + assert document['text_source'] == 'mineru' + assert 'LEGACY-FLAT-TEXT' not in document['extracted_text'] + assert 'PO Number: 4518838154' in document['extracted_text'] + assert 'Item\tReservation ID' in document['extracted_text'] + assert '00020\t12345' in document['extracted_text'] + assert 'html' not in repr(document) + + +def test_unique_manifest_accepted_layout_fields_cannot_be_overridden(app): + """唯一 Manifest 模型可以补充候选,但 accepted 字段缺失或改值必须被后端拒绝。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='LOCKED-FIELD') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + unit = run.extraction_plan.units[0] + run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{ + 'mapping_status': 'accepted', 'rows': [{ + 'role': 'data', 'fields': [{'field_id': 'qty-id', 'value': 30}], + }], + }] + invalid = [{ + 'source_intake_no': intake.intake_no, 'primary_document_id': unit.document_id, + 'header_fields': [], 'lines': [{'fields': [{ + 'field_id': 'qty-id', 'observations': [{ + 'value': 31, 'document_id': unit.document_id, + }], + }]}], + }] + + with pytest.raises(ValidationError) as caught: + validate_unit_orders(run, unit=unit, orders=invalid) + + assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE' + + +def test_accepted_complete_layout_builds_order_without_provider(app): + """唯一 accepted 表格覆盖全部必填字段时必须直接生成订单,保持零 Provider 调用。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='LAYOUT-ZERO-PROVIDER') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + unit = run.extraction_plan.units[0] + run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{ + 'mapping_status': 'accepted', 'issues': [], + 'rows': [{ + 'role': 'data', 'fields': [{ + 'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30', + }], + }], + }] + from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders + + orders = build_deterministic_unit_orders(run, unit=unit) + + assert orders is not None + assert orders[0]['lines'][0]['fields'][0]['field_id'] == 'qty-id' + assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30 + + +def test_plain_text_complete_table_still_uses_provider(app): + """纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC') version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() @@ -590,6 +760,7 @@ def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app): with patch( 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', + return_value=([], {'workflow_run_id': 'wf-plain-text', 'execution_mode': 'dify'}), ) as execute, patch( 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', return_value={ @@ -602,11 +773,149 @@ def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app): db.session.expire_all() finished = db.session.get(ShippingOrderExtractionRun, run.id) unit = finished.extraction_plan.units[0] - assert execute.call_count == 0 - assert submit.call_args.kwargs['orders'][0]['lines'][0]['fields'] + assert execute.call_count == 1 + assert submit.call_args.kwargs['orders'] == [] assert unit.status == 'succeeded' - assert unit.result_json['workflow']['execution_mode'] == 'deterministic' - assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 1 + assert unit.result_json['workflow']['execution_mode'] == 'dify' + assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 0 + + +def test_profile_template_candidate_uses_provider_after_l7_cleanup(app): + """Profile 仍提供紧凑语义候选,但未获 accepted cell 前不能跳过 Provider。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-MAP') + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + version.definition_json = {'fields': [ + { + 'field_id': 'customer-id', 'field_code': 'customer_part_number', 'scope': 'line', + 'value_type': 'string', 'enabled': True, 'required': False, + 'normalizer_key': 'trim', 'validator_keys': [], + }, + { + 'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', + 'value_type': 'string', 'enabled': True, 'required': True, + 'normalizer_key': 'trim', 'validator_keys': [], + }, + { + 'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', + 'value_type': 'decimal', 'enabled': True, 'required': True, + 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], + }, + ]} + html = ( + '' + '' + '
    LNPart NumberVendor Item#Qty
    1CUSTOMER-1INTERNAL-13
    2CUSTOMER-ZINTERNAL-Z0
    ' + ) + from app.services.shipping_notice.document_layout.html_table import parse_html_grid + from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint + + fingerprint = order_profile_structure_fingerprint(parse_html_grid(html, table_id='fixture'), header_row_index=0) + profile = ShippingOrderDocumentProfile( + profile_code='PO_312207', display_name='PO template', version=1, status='published', + schema_version_id=version.id, structure_fingerprint=fingerprint, checksum='e' * 64, + definition_json={ + 'contract_version': 'shipping_order_document_profile.v1', + 'structure_fingerprint': fingerprint, 'header_row_index': 0, + 'data_start_row_index': 1, 'row_structure': 'preserved', 'drop_zero_qty': True, + 'column_rules': [ + {'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number'], + 'target_fields': [{'field_id': 'customer-id', 'field_code': 'customer_part_number'}]}, + {'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['part_number'], + 'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}]}, + {'column_index': 3, 'extractor_key': 'direct', 'target_field_codes': ['qty'], + 'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}]}, + ], + }, published_at=datetime.utcnow(), + ) + record_inline_layout_snapshot(document, { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [], + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}], + }) + db.session.add(profile) + db.session.commit() + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + db.session.commit() + job = claim_next_job( + domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], + worker_id='profile-worker', + ) + + with patch( + 'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow', + return_value=([], {'workflow_run_id': 'wf-profile', 'execution_mode': 'dify'}), + ) as execute, patch( + 'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result', + return_value={ + 'batch_no': None, 'created_count': 0, 'opened_existing_count': 0, + 'pending_count': 0, 'non_shipping_count': 0, + }, + ) as submit: + run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) + + execute.assert_called_once() + manifest = json.loads(execute.call_args.kwargs['run'].input_snapshot_json and build_order_extraction_workflow_inputs( + run, unit=run.extraction_plan.units[0], + )['execution_manifest']) + assert manifest['structured_table_candidates'] == [] + assert submit.call_args.kwargs['orders'] == [] + + +def test_profile_layout_html_is_not_sent_to_dify(app): + """Profile 不完整而回退 Dify 时,Manifest 只能携带紧凑候选,不能含坐标或原始 HTML。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-TOKEN') + record_inline_layout_snapshot(document, { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [], + 'tables': [{ + 'table_id': 'table-secret', 'page_no': 1, + 'bbox': {'x0': 1, 'y0': 2, 'x1': 3, 'y1': 4}, + 'html': '
    RAW-LAYOUT-SECRET
    ', + }], + }) + db.session.commit() + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + unit = run.extraction_plan.units[0] + + manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest']) + + assert 'layout_snapshot' not in manifest['document'] + assert 'layout_schema_candidates' not in manifest['document'] + # 表格文字可作为 TSV 上下文提供给 LLM;布局 HTML 与坐标/证据内部标识不得泄漏。 + assert 'RAW-LAYOUT-SECRET' in manifest['document']['extracted_text'] + assert ' dict: + """构造脱敏 PDF 订单行真值,覆盖删除归属和高风险字段的阶段门禁。""" + line = { + 'line_id': 'line-00020', + 'table_annotation_id': 'table-1', + 'line_cell_ids': ['cell-item-00020', 'cell-qty-00020'], + 'status': status, + 'fields': [{ + 'field_code': 'qty', 'value': 30, 'evidence_cell_ids': ['cell-qty-00020'], + }], + } + if status == 'deleted': + line['line_id'] = 'line-00010' + line['deletion_marker_cell_id'] = 'cell-item-deleted' + return { + 'schema_version': 'shipping_pdf_order_truth.v1', + 'sample_id': f'sample-{status}', + 'content_hash': 'c' * 64, + 'categories': categories, + 'lines': [line], + } + + +def test_pdf_order_quality_gate_passes_only_when_all_safety_rules_hold(): + """六类样本齐全且零误删、零高风险误放行、零漏复核时才允许进入下一阶段。""" + truth = [_pdf_order_truth(categories=[ + 'normal_multi_line', 'continued_row', 'deleted_line', 'cross_page_header', + 'scanned_ocr', 'unreadable_pdf', + ])] + gate = review_pdf_order_quality_gate(truth, PdfOrderQualityMetrics( + active_truth_lines=1, + deleted_truth_lines=1, + active_lines_auto_released=1, + active_lines_misdeleted=0, + high_risk_auto_released_fields=1, + incorrect_high_risk_auto_released_fields=0, + unreliable_truth_lines=1, + unreliable_lines_sent_to_review=1, + )) + + assert gate.passed is True + assert gate.reasons == [] + + +def test_pdf_order_quality_gate_blocks_missing_categories_and_unsafe_results(): + """缺样本、误删有效行、错误放行或漏转复核中任一项存在时必须阻断阶段推进。""" + gate = review_pdf_order_quality_gate( + [_pdf_order_truth(categories=['deleted_line'])], + { + 'active_truth_lines': 1, + 'deleted_truth_lines': 1, + 'active_lines_auto_released': 0, + 'active_lines_misdeleted': 1, + 'high_risk_auto_released_fields': 2, + 'incorrect_high_risk_auto_released_fields': 1, + 'unreliable_truth_lines': 2, + 'unreliable_lines_sent_to_review': 1, + }, + ) + + assert gate.passed is False + assert 'active_order_line_misdeleted' in gate.reasons + assert 'incorrect_high_risk_field_auto_released' in gate.reasons + assert 'unreliable_order_line_not_sent_to_review' in gate.reasons + assert any(reason.startswith('pdf_order_truth_categories_missing:') for reason in gate.reasons) + + +def test_pdf_order_truth_requires_a_marker_for_deleted_line_but_allows_review_truth(): + """删除归属缺证据必须拒绝;待复核行保留真值字段,供漏转复核评测使用。""" + deleted = _pdf_order_truth(categories=['deleted_line'], status='deleted') + deleted['lines'][0].pop('deletion_marker_cell_id') + with pytest.raises(ValidationError, match='deletion_marker_cell_id'): + review_pdf_order_quality_gate([deleted], { + 'active_truth_lines': 0, 'deleted_truth_lines': 1, + 'active_lines_auto_released': 0, 'active_lines_misdeleted': 0, + 'high_risk_auto_released_fields': 0, + 'incorrect_high_risk_auto_released_fields': 0, + 'unreliable_truth_lines': 0, 'unreliable_lines_sent_to_review': 0, + }) + + review = _pdf_order_truth(categories=['unreadable_pdf'], status='needs_review') + assert review_pdf_order_quality_gate([review], { + 'active_truth_lines': 0, 'deleted_truth_lines': 0, + 'active_lines_auto_released': 0, 'active_lines_misdeleted': 0, + 'high_risk_auto_released_fields': 0, + 'incorrect_high_risk_auto_released_fields': 0, + 'unreliable_truth_lines': 1, 'unreliable_lines_sent_to_review': 1, + }).passed is False diff --git a/backend/tests/test_shipping_document_layout_html_layout.py b/backend/tests/test_shipping_document_layout_html_layout.py new file mode 100644 index 00000000..216a46de --- /dev/null +++ b/backend/tests/test_shipping_document_layout_html_layout.py @@ -0,0 +1,69 @@ +""" +backend/tests/test_shipping_document_layout_html_layout.py + +用途:验证 EML HTML DOM 表格可安全转换为统一逻辑布局,且不携带主动内容。 +依赖:eml_parse HTML 清洗、html_layout、布局契约。 +逻辑:覆盖脚本/属性清理、rowspan/colspan、空 cell 和无有效表格候选。 +""" + +from __future__ import annotations + +from email import policy +from email.parser import BytesParser + +from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate +from app.services.shipping_notice.eml_parse import _extract_body_html_tables + + +def test_eml_html_tables_are_sanitized_before_layout(): + """正文表格只保留结构与跨度,脚本、样式、链接和图片均不得进入临时片段。""" + message = BytesParser(policy=policy.default).parsebytes( + b'MIME-Version: 1.0\r\nContent-Type: text/html; charset=utf-8\r\n\r\n' + b'' + b'' + b'' + b'
    PartQty
    2
    ' + ) + + tables = _extract_body_html_tables(message) + + assert len(tables) == 1 + assert 'rowspan="2"' in tables[0] + assert 'SECRET' not in tables[0] + assert 'onclick' not in tables[0] + assert 'href' not in tables[0] + assert 'PartQty' + '', + ], + ) + + table = layout.pages[0].tables[0] + assert layout.quality.status == 'needs_review' + assert table.rows[0].cells[0].row_span == 2 + assert table.rows[1].cells[0].text == '' + assert table.rows[1].cells[0].token_ids == [] + assert all(cell.source == 'html' for row in table.rows for cell in row.cells) + assert {item.code for item in layout.quality.issues} == {'html_logical_coordinates_only'} + + +def test_invalid_html_tables_return_valid_empty_needs_review_layout(): + """全部坏表仍须返回合法一页候选和问题码,不能因零页面尺寸抛契约异常。""" + layout = build_html_layout_candidate( + document_id=13, content_hash='f' * 64, tables=['
    not a table
    '], + ) + + assert layout.pages[0].width == 1 + assert layout.pages[0].height == 1 + assert layout.pages[0].tables == [] + assert {item.code for item in layout.quality.issues} == { + 'html_logical_coordinates_only', 'html_table_invalid', 'html_table_structure_missing', + } diff --git a/backend/tests/test_shipping_document_layout_html_table.py b/backend/tests/test_shipping_document_layout_html_table.py index 7a416d54..7ebc001b 100644 --- a/backend/tests/test_shipping_document_layout_html_table.py +++ b/backend/tests/test_shipping_document_layout_html_table.py @@ -127,6 +127,40 @@ def test_repeated_header_deleted_summary_and_empty_rows_are_not_data(): assert all(not row.fields for row in result.rows) +def test_exclusive_deleted_marker_marks_the_unique_previous_detail_line_deleted(): + """独占删除标记紧邻唯一明细时归属上一行,避免该行流入订单 Candidate。""" + result = _map( + '' + '' + '
    PartQty
    DELETED-PART3
    Item deleted
    ACTIVE-PART4
    ', + _field('part_number', ['Part']), + _field('qty', ['Qty'], value_type='integer'), + ) + + assert [row.role for row in result.rows] == ['deleted', 'deleted', 'data'] + assert result.rows[0].fields == [] + assert {field.field_code: field.value for field in result.rows[2].fields} == { + 'part_number': 'ACTIVE-PART', 'qty': 4, + } + + +def test_displaced_deleted_marker_never_deletes_the_following_positive_line(): + """零数量删除行与后置标记竞争时,正数量行必须保留并通过问题码进入人工复核。""" + result = _map( + '' + '' + '
    PartQty
    ITEM-00100
    ITEM-002030
    Item deleted
    ', + _field('part_number', ['Part']), + _field('qty', ['Qty'], value_type='integer'), + ) + + assert [row.role for row in result.rows] == ['deleted', 'data', 'deleted'] + assert {field.field_code: field.value for field in result.rows[1].fields} == { + 'part_number': 'ITEM-0020', 'qty': 30, + } + assert 'deletion_marker_target_ambiguous' in result.issues + + def test_explicit_zero_quantity_row_is_deleted_without_field_candidates(): """冻结 Qty 列明确为零的订单行必须删除,不能作为不完整 Candidate 流入后续。""" result = _map( @@ -298,6 +332,20 @@ def test_reservation_validator_rejects_line_number_shape(): assert [(field.field_code, field.value) for field in result.rows[0].fields] == [('qty', 1)] +@pytest.mark.parametrize('reservation_id', ['20004', '2000484577']) +def test_reservation_validator_keeps_valid_non_line_number_shapes(reservation_id): + """合法五位/十位预约号不能因项次防呆规则被误删。""" + result = _map( + f'
    Reservation IDQty
    {reservation_id}1
    ', + _field('reservation_id', ['Reservation ID'], normalizer_key='reservation_id'), + _field('qty', ['Qty'], value_type='integer'), + ) + + assert [(field.field_code, field.value) for field in result.rows[0].fields] == [ + ('reservation_id', reservation_id), ('qty', 1), + ] + + def test_nested_table_rows_do_not_pollute_parent_grid(): """主表单元格内的嵌套展示表格不得被重复解析成主表数据行。""" grid = parse_html_grid( diff --git a/backend/tests/test_shipping_document_layout_job.py b/backend/tests/test_shipping_document_layout_job.py new file mode 100644 index 00000000..57519d1e --- /dev/null +++ b/backend/tests/test_shipping_document_layout_job.py @@ -0,0 +1,106 @@ +""" +backend/tests/test_shipping_document_layout_job.py + +用途:验证独立布局 Job 从对象存储读取附件、按 lease 收口并在失败时同步版本状态。 +依赖:shipping_document_layout handler、lifecycle、通用 Job queue。 +逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease。 +""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest + +from app import db +from app.jobs.context import JobContext +from app.jobs.handlers.shipping_document_layout import LAYOUT_JOB_ERROR, run_shipping_document_layout +from app.models import Job +from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version +from tests.test_shipping_document_layout_lifecycle import _document, _snapshot + + +def _running_layout_job(app): + """创建布局版本并模拟通用队列已领取该 Job。""" + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + document = _document() + version = schedule_layout_version(document, force=True) + job = db.session.get(Job, version.job_id) + job.status = 'running' + job.attempts = 1 + job.max_attempts = 3 + db.session.commit() + return document, version, job + + +def test_layout_job_completes_version_and_updates_document_current(app): + """成功 Provider 结果必须冻结 checksum 并成为 Document 当前布局。""" + with app.app_context(): + document, version, job = _running_layout_job(app) + with patch( + 'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF', + ), patch( + 'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot', + return_value=_snapshot(marker='worker'), + ): + run_shipping_document_layout( + JobContext(config=dict(app.config), logger=None, extras={}), + {'job_id': job.id}, + ) + + db.session.refresh(version) + db.session.refresh(document) + db.session.refresh(job) + assert version.status == 'ready' + assert version.payload_checksum + assert version.lease_token is None + assert document.current_layout_version_id == version.id + assert job.status == 'success' + + +def test_layout_job_failure_requeues_version_and_clears_lease(app): + """可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。""" + with app.app_context(): + _document_row, version, job = _running_layout_job(app) + with patch( + 'app.jobs.handlers.shipping_document_layout.read_asset_bytes', + side_effect=RuntimeError('temporary storage failure'), + ): + with pytest.raises(RuntimeError, match='temporary storage failure'): + run_shipping_document_layout( + JobContext(config=dict(app.config), logger=None, extras={}), + {'job_id': job.id}, + ) + + db.session.refresh(version) + db.session.refresh(job) + assert job.status == 'queued' + assert version.status == 'queued' + assert version.lease_token is None + assert job.error_message == LAYOUT_JOB_ERROR + + +def test_layout_job_exhaustion_fails_version_without_leaking_provider_error(app): + """最后一次失败必须同步终结布局版本,Job 只保留稳定错误码而非内部异常。""" + with app.app_context(): + _document_row, version, job = _running_layout_job(app) + job.max_attempts = 1 + db.session.commit() + with patch( + 'app.jobs.handlers.shipping_document_layout.read_asset_bytes', + side_effect=RuntimeError('secret storage endpoint failed'), + ): + with pytest.raises(RuntimeError, match='secret storage endpoint failed'): + run_shipping_document_layout( + JobContext(config=dict(app.config), logger=None, extras={}), + {'job_id': job.id}, + ) + + db.session.refresh(version) + db.session.refresh(job) + assert job.status == 'failed' + assert job.error_message == LAYOUT_JOB_ERROR + assert 'secret storage endpoint' not in str(job.error_message) + assert version.status == 'failed' + assert version.lease_token is None + assert 'shipping_document_layout_job_exhausted' in version.issues_json diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py new file mode 100644 index 00000000..6914e52f --- /dev/null +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -0,0 +1,209 @@ +""" +backend/tests/test_shipping_document_layout_lifecycle.py + +用途:验证 L1 版面快照 checksum、版本幂等、容量门禁和当前成功版本保护。 +依赖:ShippingNoticeDocument/LayoutVersion、document_layout.lifecycle、Flask 测试库。 +逻辑:相同快照复用;新失败/超限版本保留审计但不覆盖旧成功引用。 +""" + +from __future__ import annotations + +from app import db +from app.models import Job, ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake, FileAsset, User +from app.services.shipping_notice.document_layout.lifecycle import ( + canonical_layout_payload, + claim_layout_version, + complete_layout_version, + current_layout_snapshot, + record_inline_layout_snapshot, + schedule_layout_version, + schedule_document_layouts, + sync_layout_after_job_recovery, +) + + +def _document() -> ShippingNoticeDocument: + """创建带稳定内容哈希的最小附件 Document。""" + user = User(username='layout-owner', email='layout-owner@example.com', role='user', status='active') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no='FA-LAYOUT-L1', owner_user_id=user.id, original_filename='sample.pdf', + storage_provider='minio', storage_bucket='test', storage_key='sample.pdf', + content_hash='a' * 64, file_size=10, mime_type='application/pdf', + upload_status='ready', lifecycle_status='referenced', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-LAYOUT-L1', asset_id=asset.id, user_id=user.id, + purpose='shipping_notice', parse_status='parsed', parser_version='v6', + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', + attachment_key='sample.pdf', filename='sample.pdf', content_hash='a' * 64, + classification='order_notice', parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + return document + + +def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict: + """构造不含正文的紧凑布局快照。""" + return { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'provider_version': '3.1.14', 'backend': 'pipeline', + 'status': status, 'tables': [], 'issues': [], 'marker': marker, + } + + +def test_layout_snapshot_checksum_and_idempotent_current_version(app): + """相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。""" + with app.app_context(): + document = _document() + checksum, size = canonical_layout_payload(_snapshot()) + first = record_inline_layout_snapshot(document, _snapshot()) + replay = record_inline_layout_snapshot(document, _snapshot()) + db.session.commit() + + assert first.id == replay.id + assert first.payload_checksum == checksum + assert first.payload_size_bytes == size + assert ShippingDocumentLayoutVersion.query.count() == 1 + assert document.current_layout_version_id == first.id + assert current_layout_snapshot(document)['marker'] == 'v1' + + +def test_failed_or_oversized_layout_does_not_replace_last_good_version(app): + """失败/超限版本必须可审计,但绝不能覆盖 Document 上一次成功布局。""" + app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 200 + with app.app_context(): + document = _document() + good = record_inline_layout_snapshot(document, _snapshot()) + failed = record_inline_layout_snapshot(document, _snapshot(status='failed', marker='failed')) + oversized = record_inline_layout_snapshot(document, { + **_snapshot(marker='large'), 'tables': [{'html': 'X' * 500}], + }) + db.session.commit() + + assert failed.status == 'failed' + assert oversized.status == 'failed' + assert oversized.payload_json is None + assert 'shipping_document_layout_snapshot_size_exceeded' in oversized.issues_json + assert document.current_layout_version_id == good.id + assert current_layout_snapshot(document)['marker'] == 'v1' + assert ShippingDocumentLayoutVersion.query.count() == 3 + + +def test_layout_schedule_is_idempotent_and_force_creates_next_version(app): + """同 parser 成功版本默认复用;显式重解析创建下一 queued 版本及独立 Job。""" + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + with app.app_context(): + document = _document() + ready = record_inline_layout_snapshot(document, _snapshot()) + reused = schedule_layout_version(document) + forced = schedule_layout_version(document, force=True) + db.session.commit() + + assert reused.id == ready.id + assert forced.id != ready.id + assert forced.version == 2 + assert forced.status == 'queued' + assert forced.job_id is not None + job = db.session.get(Job, forced.job_id) + assert job.job_type == 'shipping_document_layout' + assert job.payload_json == {'layout_version_id': forced.id} + + +def test_layout_parser_revision_change_creates_new_version_without_force(app): + """运维提升 parser revision 后不得复用旧 Provider/模型结果。""" + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + with app.app_context(): + document = _document() + old = record_inline_layout_snapshot( + document, _snapshot(), + parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:v1', + ) + app.config['SHIPPING_NOTICE_LAYOUT_PARSER_REVISION'] = 'v2' + new = schedule_layout_version(document) + db.session.commit() + + assert new.id != old.id + assert new.version == 2 + assert new.parser_key.endswith(':v2') + + +def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app): + """Job 回收后版本回 queued 并清 lease,旧 Worker 结果不得覆盖当前成功版本。""" + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + with app.app_context(): + document = _document() + ready = record_inline_layout_snapshot(document, _snapshot()) + pending = schedule_layout_version(document, force=True) + job = db.session.get(Job, pending.job_id) + job.status = 'running' + job.attempts = 1 + db.session.commit() + claimed = claim_layout_version(pending.id, job_id=job.id, owned_attempt=1) + assert claimed is not None + _version, old_lease = claimed + + job.status = 'queued' + sync_layout_after_job_recovery(job) + db.session.commit() + + assert pending.status == 'queued' + assert pending.lease_token is None + assert complete_layout_version( + pending.id, lease_token=old_lease, snapshot=_snapshot(marker='stale'), + ) is False + db.session.refresh(document) + assert document.current_layout_version_id == ready.id + + +def test_layout_document_budget_creates_unsupported_audit_versions(app): + """超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。""" + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 1 + with app.app_context(): + first = _document() + second = ShippingNoticeDocument( + intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment', + attachment_key='second.pdf', filename='second.pdf', content_hash='b' * 64, + classification='order_notice', parse_status='parsed', + ) + text = ShippingNoticeDocument( + intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment', + attachment_key='notes.txt', filename='notes.txt', content_hash='c' * 64, + classification='order_notice', parse_status='parsed', + ) + db.session.add_all([second, text]) + db.session.flush() + + versions = schedule_document_layouts([first, text, second]) + db.session.commit() + + assert len(versions) == 2 + assert versions[0].status == 'queued' + assert versions[1].status == 'unsupported' + assert versions[1].issues_json == ['mineru_intake_document_budget_exceeded'] + assert ShippingDocumentLayoutVersion.query.filter_by(document_id=text.id).count() == 0 + + +def test_deleting_document_cascades_layout_versions(app): + """Document 删除必须先解除 current 引用,并级联清理其全部布局版本。""" + with app.app_context(): + document = _document() + version = record_inline_layout_snapshot(document, _snapshot()) + document_id = document.id + version_id = version.id + db.session.commit() + + db.session.delete(document) + db.session.commit() + + assert db.session.get(ShippingNoticeDocument, document_id) is None + assert db.session.get(ShippingDocumentLayoutVersion, version_id) is None diff --git a/backend/tests/test_shipping_document_layout_lifecycle_migration.py b/backend/tests/test_shipping_document_layout_lifecycle_migration.py new file mode 100644 index 00000000..85c9c086 --- /dev/null +++ b/backend/tests/test_shipping_document_layout_lifecycle_migration.py @@ -0,0 +1,102 @@ +""" +backend/tests/test_shipping_document_layout_lifecycle_migration.py + +用途:验证 L1 布局生命周期迁移回填旧快照、建立版本/活动唯一约束并可完整降级。 +依赖:Alembic Operations、SQLite 内存库、a69f8091a2b5 迁移。 +逻辑:构造上一 revision 最小表,升级后校验 checksum/current FK,降级恢复原 JSON。 +""" + +from __future__ import annotations + +import importlib +import json + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_document_layout_lifecycle_migration_round_trip(monkeypatch): + """旧布局 JSON 必须无损迁入版本表,活动唯一索引和 downgrade 恢复均生效。""" + migration = importlib.import_module( + 'migrations.versions.a69f8091a2b5_add_document_layout_lifecycle', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'jobs', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('domain', sa.String(64)), sa.Column('job_type', sa.String(64)), + sa.Column('business_ref', sa.String(128)), sa.Column('status', sa.String(32)), + ) + documents = sa.Table( + 'shipping_notice_documents', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('content_hash', sa.String(64)), + sa.Column('layout_snapshot_json', sa.JSON()), + ) + metadata.create_all(engine) + + with engine.begin() as connection: + payload = { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'provider_version': '3.1.14', 'backend': 'pipeline', + 'status': 'ready', 'tables': [], 'issues': ['mineru_cell_coordinates_missing'], + } + connection.execute(documents.insert().values( + id=1, content_hash='a' * 64, layout_snapshot_json=payload, + )) + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + inspector = sa.inspect(connection) + assert 'shipping_document_layout_versions' in inspector.get_table_names() + assert 'uq_jobs_shipping_document_layout_active_ref' in { + item['name'] for item in inspector.get_indexes('jobs') + } + columns = {item['name'] for item in inspector.get_columns('shipping_notice_documents')} + assert 'current_layout_version_id' in columns + assert 'layout_snapshot_json' not in columns + versions = sa.Table( + 'shipping_document_layout_versions', sa.MetaData(), autoload_with=connection, + ) + version = connection.execute(sa.select(versions)).mappings().one() + assert version['status'] == 'ready' + assert version['parser_key'].endswith(':legacy') + assert version['payload_json'] == payload + assert len(version['payload_checksum']) == 64 + current_id = connection.execute(sa.text( + 'SELECT current_layout_version_id FROM shipping_notice_documents WHERE id = 1', + )).scalar_one() + assert current_id == version['id'] + + duplicate = connection.begin_nested() + with pytest.raises(sa.exc.IntegrityError): + connection.execute(versions.insert().values( + document_id=1, version=2, status='queued', source_content_hash='a' * 64, + parser_key='next', parser_name='mineru', contract_version='v1', issues_json=[], + payload_size_bytes=0, attempt_count=0, + created_at=sa.func.current_timestamp(), updated_at=sa.func.current_timestamp(), + )) + connection.execute(versions.insert().values( + document_id=1, version=3, status='running', source_content_hash='a' * 64, + parser_key='next-2', parser_name='mineru', contract_version='v1', issues_json=[], + payload_size_bytes=0, attempt_count=0, + created_at=sa.func.current_timestamp(), updated_at=sa.func.current_timestamp(), + )) + duplicate.rollback() + + migration.downgrade() + inspector = sa.inspect(connection) + assert 'shipping_document_layout_versions' not in inspector.get_table_names() + assert 'uq_jobs_shipping_document_layout_active_ref' not in { + item['name'] for item in inspector.get_indexes('jobs') + } + columns = {item['name'] for item in inspector.get_columns('shipping_notice_documents')} + assert 'layout_snapshot_json' in columns + restored = connection.execute(sa.text( + 'SELECT layout_snapshot_json FROM shipping_notice_documents WHERE id = 1', + )).scalar_one() + assert (json.loads(restored) if isinstance(restored, str) else restored) == payload diff --git a/backend/tests/test_shipping_document_layout_mineru.py b/backend/tests/test_shipping_document_layout_mineru.py index 24ca5200..128684f9 100644 --- a/backend/tests/test_shipping_document_layout_mineru.py +++ b/backend/tests/test_shipping_document_layout_mineru.py @@ -108,6 +108,26 @@ class _FakeSession: return self.response +class _AsyncSession: + """模拟 `/tasks` 提交、状态轮询和结果读取。""" + + def __init__(self, result: dict): + self.result = result + self.calls: list[str] = [] + + def post(self, url: str, **_kwargs): + """返回异步任务 ID。""" + self.calls.append(url) + return _FakeResponse({'task_id': 'task-async'}, status_code=202) + + def get(self, url: str, **_kwargs): + """第一次读取终态,结果接口返回完整 MinerU payload。""" + self.calls.append(url) + if url.endswith('/result'): + return _FakeResponse(self.result) + return _FakeResponse({'task_id': 'task-async', 'status': 'completed'}) + + def test_mineru_candidate_preserves_table_structure_but_blocks_cell_evidence(): """只有整表 bbox + HTML 时必须保留行列候选并阻止确定性单元格证据。""" candidate = parse_mineru_candidate(_mineru_payload()) @@ -188,6 +208,23 @@ def test_mineru_client_sends_bounded_single_file_request(): assert response.closed is True +def test_mineru_async_client_submits_polls_and_reads_result_without_long_post(): + """生产调用应使用 `/tasks` 短提交,再通过状态和结果接口获取 completed payload。""" + session = _AsyncSession(_mineru_payload()) + client = MinerUClient(MinerUClientConfig( + base_url='http://mineru.internal:8100', poll_interval_seconds=0.01, + ), session=session) + + payload = client.parse_file_async(filename='fixture.pdf', content=b'%PDF') + + assert payload['status'] == 'completed' + assert session.calls == [ + 'http://mineru.internal:8100/tasks', + 'http://mineru.internal:8100/tasks/task-async', + 'http://mineru.internal:8100/tasks/task-async/result', + ] + + def test_mineru_client_rejects_unsupported_empty_and_large_files_before_network(): """文件类型、空内容和上传上限必须在 HTTP 请求前拒绝。""" session = _FakeSession(_FakeResponse(_mineru_payload())) diff --git a/backend/tests/test_shipping_document_layout_native_pdf.py b/backend/tests/test_shipping_document_layout_native_pdf.py new file mode 100644 index 00000000..610b8864 --- /dev/null +++ b/backend/tests/test_shipping_document_layout_native_pdf.py @@ -0,0 +1,264 @@ +""" +backend/tests/test_shipping_document_layout_native_pdf.py + +用途:验证原生 PDF 字符证据与 MinerU HTML 组合为保守、可追溯的 layout.v1 候选。 +依赖:native_pdf、MinerU candidate、布局契约和 mock PDF 页面。 +逻辑:覆盖唯一文本成功、重复文本拒绝、扫描无文本和 runtime 内嵌候选;任何结果都不得自动 accepted。 +""" + +from __future__ import annotations + +from unittest.mock import patch +from io import BytesIO + +import numpy as np +from pypdf import PdfWriter + +from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.mineru import ( + MinerUCapabilityReport, + MinerUPageCandidate, + MinerUParseCandidate, + MinerUTableCandidate, +) +from app.services.shipping_notice.document_layout.native_pdf import ( + NativePdfPage, + build_native_pdf_layout_candidate, + extract_native_pdf_pages, +) +from app.services.shipping_notice.document_layout.ocr_pdf import ( + OcrCellEvidence, + OcrLine, + OcrTableEvidence, +) +from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot +from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter + + +def _candidate(html: str) -> MinerUParseCandidate: + """构造单页 MinerU HTML 表格候选,不提供 Provider 原生 cell bbox。""" + return MinerUParseCandidate( + provider_version='3.1.14', backend='pipeline', + pages=[MinerUPageCandidate( + page_no=1, width=200, height=100, + tables=[MinerUTableCandidate( + candidate_id='table-1', page_no=1, + bbox=LayoutBBox(x0=5, y0=5, x1=190, y1=80), + normalized_bbox=LayoutBBox(x0=.025, y0=.05, x1=.95, y1=.8), + html=html, row_count=1, cell_count=2, + has_rowspan=False, has_colspan=False, + )], + )], + capability=MinerUCapabilityReport( + provider_version='3.1.14', backend='pipeline', page_count=1, + page_size_count=1, bbox_object_count=1, html_table_count=1, + html_row_count=1, html_cell_count=2, text_block_count=0, + cell_bbox_count=0, has_page_coordinates=True, has_table_structure=True, + has_cell_coordinates=False, deterministic_cell_evidence_ready=False, + issues=['mineru_cell_coordinates_missing'], + ), + ) + + +def _page(text: str) -> NativePdfPage: + """为单行文本构造从左到右且位于表内的 PDF glyph 页面。""" + characters = [ + PositionedCharacter( + text=char, source_index=index, + bbox=LayoutBBox(x0=10 + index * 8, y0=20, x1=16 + index * 8, y1=30), + ) + for index, char in enumerate(text) + ] + return NativePdfPage( + page_no=1, width=200, height=100, rotation=0, + characters=characters, image=np.full((200, 400), 255, dtype=np.uint8), + ) + + +def test_native_pdf_unique_text_builds_traceable_needs_review_layout(): + """唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。""" + mineru = _candidate('
    PartQty
    ') + with patch( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + return_value=[_page('PartQty')], + ): + layout = build_native_pdf_layout_candidate( + document_id=7, content_hash='a' * 64, content=b'%PDF', mineru=mineru, + ) + + assert layout.quality.status == 'needs_review' + assert layout.pages[0].tables[0].status == 'needs_review' + assert len(layout.pages[0].tokens) == 7 + cells = layout.pages[0].tables[0].rows[0].cells + assert len(cells) == 2 + assert all(cell.token_ids for cell in cells) + assert {item.code for item in layout.quality.issues} >= { + 'document_cell_truth_deferred', 'native_pdf_cells_from_unique_text_candidate', + } + + +def test_native_pdf_repeated_text_does_not_create_cells(): + """重复表头不得按 HTML 顺序分配 glyph;候选保留阻断问题且没有表。""" + mineru = _candidate('
    QtyQty
    ') + with patch( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + return_value=[_page('QtyQty')], + ), patch( + 'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry', + ) as opencv: + opencv.return_value.ready = False + opencv.return_value.issues = ['opencv_table_grid_not_detected'] + opencv.return_value.cells = [] + layout = build_native_pdf_layout_candidate( + document_id=8, content_hash='b' * 64, content=b'%PDF', mineru=mineru, + ) + + assert layout.pages[0].tables == [] + codes = {item.code for item in layout.quality.issues} + assert 'text_cell_alignment_text_not_unique' in codes + assert 'native_pdf_no_resolved_tables' in codes + + +def test_runtime_embeds_layout_candidate_without_changing_ready_snapshot(app): + """PDF Job 可保存 layout.v1 候选,同时维持现有 Profile 使用的 ready 表格快照。""" + app.config.update( + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + ) + mineru = _candidate('
    PartQty
    ') + with app.app_context(), patch( + 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', + return_value={'status': 'completed'}, + ), patch( + 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', + return_value=mineru, + ), patch( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + return_value=[_page('PartQty')], + ): + snapshot = build_mineru_table_snapshot( + filename='order.pdf', content=b'%PDF', document_id=9, content_hash='c' * 64, + ) + + assert snapshot['status'] == 'ready' + assert snapshot['layout_candidate']['schema_version'] == 'shipping_document_layout.v1' + assert snapshot['layout_candidate']['quality']['status'] == 'needs_review' + assert 'PRIVATE' not in repr(snapshot) + + +def test_runtime_native_pdf_failure_keeps_mineru_table_snapshot(app): + """PDFium 候选失败只记录问题码,不得丢弃已成功取得的 MinerU HTML 表格。""" + app.config.update( + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + ) + mineru = _candidate('
    PartQty
    ') + with app.app_context(), patch( + 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', + return_value={'status': 'completed'}, + ), patch( + 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', + return_value=mineru, + ), patch( + 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate', + side_effect=RuntimeError('broken pdf'), + ): + snapshot = build_mineru_table_snapshot( + filename='order.pdf', content=b'%PDF', document_id=9, content_hash='c' * 64, + ) + + assert snapshot['status'] == 'ready' + assert len(snapshot['tables']) == 1 + assert 'layout_candidate' not in snapshot + assert 'native_pdf_layout_candidate_invalid' in snapshot['issues'] + + +def test_blank_pdf_has_page_geometry_without_fake_text_or_cells(): + """真实无文本 PDF 只能提供页面尺寸,禁止生成虚构 token 或表格单元格。""" + output = BytesIO() + writer = PdfWriter() + writer.add_blank_page(width=200, height=100) + writer.write(output) + + pages = extract_native_pdf_pages(output.getvalue(), render_scale=1) + + assert len(pages) == 1 + assert pages[0].width == 200 + assert pages[0].height == 100 + assert pages[0].characters == [] + + +def test_bad_table_is_isolated_from_other_native_pdf_tables(): + """一张越界坏表不得抹除同页另一张可追溯表,问题应定位到坏表。""" + mineru = _candidate('
    PartQty
    ') + good = mineru.pages[0].tables[0] + bad = good.model_copy(update={ + 'candidate_id': 'table-bad', + 'bbox': LayoutBBox(x0=5, y0=5, x1=250, y1=80), + }) + mineru.pages[0].tables = [good, bad] + with patch( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + return_value=[_page('PartQty')], + ): + layout = build_native_pdf_layout_candidate( + document_id=10, content_hash='d' * 64, content=b'%PDF', mineru=mineru, + ) + + assert len(layout.pages[0].tables) == 1 + assert any( + item.code == 'native_pdf_table_candidate_invalid' and item.table_id == 'table-bad' + for item in layout.quality.issues + ) + + +def test_scanned_pdf_uses_ocr_tokens_only_after_grid_evidence(): + """无原生字符页只有在 OCR+网格门禁 ready 时才能生成 source=ocr 的 token/cell。""" + mineru = _candidate('
    PartQty
    ') + page = NativePdfPage( + page_no=1, width=200, height=100, rotation=0, characters=[], + image=np.full((200, 400), 255, dtype=np.uint8), + ) + grid_cell_ids = ['table-1:r0:c0', 'table-1:r0:c1'] + evidence = OcrTableEvidence( + ready=True, + lines=[ + OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=60, y1=30), confidence=.99), + OcrLine(text='Qty', bbox=LayoutBBox(x0=110, y0=10, x1=150, y1=30), confidence=.98), + ], + cells=[ + OcrCellEvidence( + cell_id=grid_cell_ids[0], bbox=LayoutBBox(x0=5, y0=5, x1=100, y1=40), + line_indices=[0], + ), + OcrCellEvidence( + cell_id=grid_cell_ids[1], bbox=LayoutBBox(x0=100, y0=5, x1=190, y1=40), + line_indices=[1], + ), + ], + ) + with patch( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + return_value=[page], + ), patch( + 'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry', + ) as geometry, patch( + 'app.services.shipping_notice.document_layout.native_pdf.validate_opencv_cell_text', + ) as validation, patch( + 'app.services.shipping_notice.document_layout.native_pdf.build_ocr_table_evidence', + return_value=evidence, + ): + geometry.return_value.ready = False + geometry.return_value.issues = ['opencv_table_grid_not_detected'] + geometry.return_value.cells = [] + validation.return_value.accepted = False + validation.return_value.issues = ['opencv_table_geometry_not_ready'] + layout = build_native_pdf_layout_candidate( + document_id=14, content_hash='1' * 64, content=b'%PDF', mineru=mineru, + ) + + cells = layout.pages[0].tables[0].rows[0].cells + assert all(cell.source == 'ocr' for cell in cells) + assert all(cell.token_ids for cell in cells) + assert all(token.source == 'ocr' for token in layout.pages[0].tokens) + assert 'ocr_pdf_cells_from_grid_candidate' in {item.code for item in layout.quality.issues} diff --git a/backend/tests/test_shipping_document_layout_ocr_pdf.py b/backend/tests/test_shipping_document_layout_ocr_pdf.py new file mode 100644 index 00000000..49adda23 --- /dev/null +++ b/backend/tests/test_shipping_document_layout_ocr_pdf.py @@ -0,0 +1,99 @@ +""" +backend/tests/test_shipping_document_layout_ocr_pdf.py + +用途:验证 RapidOCR 多边形坐标适配和扫描表三重门禁。 +依赖:ocr_pdf、OpenCV 几何结果、HTML 网格。 +逻辑:覆盖坐标缩放、低置信过滤、引擎不可用与完整 cell 文本验收。 +""" + +from __future__ import annotations + +from unittest.mock import patch + +import numpy as np + +from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.document_layout.ocr_pdf import ( + OcrLine, + build_ocr_table_evidence, + extract_ocr_lines, +) +from app.services.shipping_notice.document_layout.opencv_table import ( + OpenCVCellGeometry, + OpenCVTableGeometryResult, +) + + +def test_rapidocr_polygon_is_scaled_to_pdf_page_and_filters_low_confidence(): + """OCR 像素框必须按渲染图与 PDF 页面比例转换,低置信结果不得保留。""" + image = np.zeros((200, 400, 3), dtype=np.uint8) + response = [ + [[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95], + [[[200, 20], [240, 20], [240, 60], [200, 60]], 'bad', 0.4], + ] + with patch('app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine') as engine: + engine.return_value.return_value = (response, 0.1) + lines = extract_ocr_lines(image, page_width=200, page_height=100) + + assert len(lines) == 1 + assert lines[0].text == 'Part' + assert lines[0].bbox.model_dump() == {'x0': 20.0, 'y0': 10.0, 'x1': 60.0, 'y1': 30.0} + + +def test_ocr_table_requires_geometry_and_all_cell_text(): + """扫描表仅在网格 ready 且全部非空 cell OCR 文本一致时输出 cell evidence。""" + grid = parse_html_grid( + '
    PartQty
    ', table_id='ocr', + ) + geometry = OpenCVTableGeometryResult( + ready=True, consensus_count=2, row_count=1, column_count=2, + cells=[ + OpenCVCellGeometry( + cell_id=grid.cells[0].cell_id, row_index=0, column_index=0, + row_span=1, column_span=1, + bbox=LayoutBBox(x0=0, y0=0, x1=100, y1=50), + normalized_bbox=LayoutBBox(x0=0, y0=0, x1=.5, y1=.5), + ), + OpenCVCellGeometry( + cell_id=grid.cells[1].cell_id, row_index=0, column_index=1, + row_span=1, column_span=1, + bbox=LayoutBBox(x0=100, y0=0, x1=200, y1=50), + normalized_bbox=LayoutBBox(x0=.5, y0=0, x1=1, y1=.5), + ), + ], + ) + lines = [ + OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=50, y1=30), confidence=.99), + OcrLine(text='Qty', bbox=LayoutBBox(x0=120, y0=10, x1=150, y1=30), confidence=.98), + ] + with patch( + 'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', return_value=lines, + ), patch( + 'app.services.shipping_notice.document_layout.ocr_pdf.reconstruct_opencv_table_geometry', + return_value=geometry, + ): + result = build_ocr_table_evidence( + image=np.zeros((100, 200), dtype=np.uint8), page_width=200, page_height=100, + table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=50), grid=grid, + ) + + assert result.ready is True + assert [item.line_indices for item in result.cells] == [[0], [1]] + + +def test_ocr_engine_failure_is_safe_unsupported_candidate(): + """OCR 引擎缺失或异常必须返回机器问题码,不得抛出或生成 cell。""" + grid = parse_html_grid('
    A
    ', table_id='fail') + with patch( + 'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', + side_effect=RuntimeError('model missing'), + ): + result = build_ocr_table_evidence( + image=np.zeros((100, 100), dtype=np.uint8), page_width=100, page_height=100, + table_bbox=LayoutBBox(x0=0, y0=0, x1=100, y1=100), grid=grid, + ) + + assert result.ready is False + assert result.cells == [] + assert result.issues == ['ocr_engine_unavailable'] diff --git a/backend/tests/test_shipping_document_layout_runtime.py b/backend/tests/test_shipping_document_layout_runtime.py new file mode 100644 index 00000000..9e66e2b9 --- /dev/null +++ b/backend/tests/test_shipping_document_layout_runtime.py @@ -0,0 +1,152 @@ +""" +backend/tests/test_shipping_document_layout_runtime.py + +用途:验证 Intake 阶段 MinerU 紧凑文本/表格快照、降级行为和容量门禁。 +依赖:document_layout.runtime/mineru 构造候选、Flask 测试配置。 +逻辑:Mock 客户端避免真实网络;只允许受预算文本块、表格 HTML 和能力摘要进入快照,原响应不得持久化。 +""" + +from __future__ import annotations + +from unittest.mock import patch + +from app.core.errors import ServiceUnavailableError +from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.mineru import ( + MinerUCapabilityReport, + MinerUPageCandidate, + MinerUParseCandidate, + MinerUTableCandidate, + MinerUTextCandidate, +) +from app.services.shipping_notice.document_layout.runtime import ( + attach_mineru_layout_snapshots, + build_mineru_table_snapshot, +) + + +def _candidate() -> MinerUParseCandidate: + """构造包含文本与表格的 MinerU 候选,验证紧凑快照内容。""" + return MinerUParseCandidate( + task_id='task-private', + provider_version='3.1.14', + backend='pipeline', + pages=[MinerUPageCandidate( + page_no=1, + width=100, + height=200, + text_blocks=[MinerUTextCandidate( + candidate_id='text-1', page_no=1, + bbox=LayoutBBox(x0=1, y0=1, x1=10, y1=10), + normalized_bbox=LayoutBBox(x0=.01, y0=.01, x1=.1, y1=.05), + text='PRIVATE-NON-TABLE-TEXT', content_type='text', + )], + tables=[MinerUTableCandidate( + candidate_id='table-1', page_no=1, + bbox=LayoutBBox(x0=1, y0=20, x1=90, y1=100), + normalized_bbox=LayoutBBox(x0=.01, y0=.1, x1=.9, y1=.5), + html='
    Part
    A
    ', + row_count=2, cell_count=2, has_rowspan=False, has_colspan=False, + )], + )], + capability=MinerUCapabilityReport( + provider_version='3.1.14', backend='pipeline', page_count=1, + page_size_count=1, bbox_object_count=2, html_table_count=1, + html_row_count=2, html_cell_count=2, text_block_count=1, + cell_bbox_count=0, has_page_coordinates=True, has_table_structure=True, + has_cell_coordinates=False, deterministic_cell_evidence_ready=False, + issues=['mineru_cell_coordinates_missing'], + ), + ) + + +def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(app): + """快照保存受控文本和表格,但不得保存 task_id 或 Provider 原始响应。""" + app.config.update( + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + ) + with app.app_context(), patch( + 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', + return_value={'status': 'completed'}, + ), patch( + 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', + return_value=_candidate(), + ): + snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF') + + assert snapshot['status'] == 'ready' + assert snapshot['text_blocks'][0]['text'] == 'PRIVATE-NON-TABLE-TEXT' + assert snapshot['tables'][0]['html'].startswith('') + assert 'task-private' not in repr(snapshot) + assert snapshot['issues'] == ['mineru_cell_coordinates_missing'] + + +def test_runtime_limits_persisted_mineru_text(app): + """MinerU 文本超过既有通知字符预算时应丢弃超额块并记录问题码。""" + app.config.update( + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=10, + ) + with app.app_context(), patch( + 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', + return_value={'status': 'completed'}, + ), patch( + 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', + return_value=_candidate(), + ): + snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF') + + assert snapshot['text_blocks'] == [] + assert 'mineru_text_budget_exceeded' in snapshot['issues'] + + +def test_runtime_provider_failure_is_safe_fallback(app): + """MinerU 失败只记录错误码并返回空表,不能抛出导致 Intake 文本解析失败。""" + app.config.update( + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + ) + with app.app_context(), patch( + 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', + side_effect=ServiceUnavailableError('failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'), + ): + snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF') + + assert snapshot == { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'backend': 'pipeline', 'status': 'failed', + 'tables': [], 'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'], + } + + +def test_runtime_attachment_budget_preserves_order_and_marks_overflow(app): + """EML 多附件只并发处理预算内文档,超量附件显式降级且原顺序不变。""" + app.config.update( + SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, + SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', + SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=2, + SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2, + ) + result = type('Result', (), {'meta': {'attachments': [ + {'filename': 'first.pdf', '_payload_bytes': b'1'}, + {'filename': 'second.pdf', '_payload_bytes': b'2'}, + {'filename': 'third.pdf', '_payload_bytes': b'3'}, + ]}})() + + with app.app_context(), patch( + 'app.services.shipping_notice.document_layout.runtime.build_mineru_table_snapshot', + side_effect=lambda *, filename, content, **_kwargs: { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', + 'tables': [], 'issues': [], 'marker': filename, + }, + ) as parse: + attach_mineru_layout_snapshots(result) + + rows = result.meta['attachments'] + assert parse.call_count == 2 + assert rows[0]['layout_snapshot']['marker'] == 'first.pdf' + assert rows[1]['layout_snapshot']['marker'] == 'second.pdf' + assert rows[2]['layout_snapshot']['status'] == 'skipped_budget' diff --git a/backend/tests/test_shipping_document_layout_schema_mapping.py b/backend/tests/test_shipping_document_layout_schema_mapping.py new file mode 100644 index 00000000..3c46b3cb --- /dev/null +++ b/backend/tests/test_shipping_document_layout_schema_mapping.py @@ -0,0 +1,169 @@ +""" +backend/tests/test_shipping_document_layout_schema_mapping.py + +用途:验证 layout.v1 真实 cell/token 证据按 Run 冻结 Schema 映射,不回退 HTML 私有 ID 或猜测跨页。 +依赖:schema_mapping、布局契约、TableHeaderContract。 +逻辑:覆盖后置表头、重复列、零 Qty、needs_review、token 引用和显式 continuation。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.document_layout.contracts import ( + LayoutBBox, + LayoutCell, + LayoutDocument, + LayoutIssue, + LayoutPage, + LayoutParserInfo, + LayoutQuality, + LayoutRow, + LayoutTable, + LayoutToken, +) +from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema +from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract + + +def _cell( + cell_id: str, row: int, column: int, text: str, *, token_id: str, role: str, +) -> LayoutCell: + """构造一格具有稳定 token 引用的布局证据。""" + bbox = LayoutBBox(x0=column * 100, y0=row * 30, x1=(column + 1) * 100, y1=(row + 1) * 30) + return LayoutCell( + cell_id=cell_id, row_index=row, column_index=column, + text=text, normalized_text=text.casefold(), bbox=bbox, + normalized_bbox=LayoutBBox( + x0=column / 3, y0=row / 4, x1=(column + 1) / 3, y1=(row + 1) / 4, + ), + token_ids=[token_id], source='native_text', confidence=1, role=role, + ) + + +def _layout(*, duplicate_part: bool = False, continuation: bool = False) -> LayoutDocument: + """构造标题行后置、两条数据行(第二条 Qty=0)的 layout.v1。""" + rows_data = [ + [('title', 'Purchase Order', 'header')], + [ + ('h-part', 'Part Number', 'header'), + ('h-qty', 'Qty', 'header'), + ('h-extra', 'Part Number' if duplicate_part else 'Reservation ID', 'header'), + ], + [('v-part', 'A-1', 'data'), ('v-qty', '2', 'data'), ('v-rsv', '2000484577', 'data')], + [('z-part', 'A-2', 'data'), ('z-qty', '0', 'data'), ('z-rsv', '2000484578', 'data')], + ] + rows = [] + tokens = [] + for row_index, values in enumerate(rows_data): + cells = [] + for column_index, (cell_id, text, role) in enumerate(values): + token_id = f't-{cell_id}' + cell = _cell( + cell_id, row_index, column_index, text, token_id=token_id, role=role, + ) + cells.append(cell) + tokens.append(LayoutToken( + token_id=token_id, text=text, normalized_text=text.casefold(), + bbox=cell.bbox, normalized_bbox=cell.normalized_bbox, + source='native_text', confidence=1, + )) + rows.append(LayoutRow( + row_id=f'row-{row_index}', row_index=row_index, cells=cells, + role='header' if row_index <= 1 else 'data', + )) + table = LayoutTable( + table_id='table-main', bbox=LayoutBBox(x0=0, y0=0, x1=300, y1=120), + normalized_bbox=LayoutBBox(x0=0, y0=0, x1=1, y1=1), rows=rows, + header_row_indices=[0, 1], continuation_of='table-parent' if continuation else None, + confidence=0, status='needs_review', + ) + pages = [LayoutPage(page_no=1, width=300, height=120, tokens=tokens, tables=[table])] + if continuation: + parent = LayoutTable( + table_id='table-parent', bbox=LayoutBBox(x0=0, y0=0, x1=300, y1=30), + normalized_bbox=LayoutBBox(x0=0, y0=0, x1=1, y1=.25), + rows=[LayoutRow( + row_id='parent-row', row_index=0, + cells=[_cell('parent-cell', 0, 0, 'Part Number', token_id='parent-token', role='header')], + role='header', + )], + header_row_indices=[0], confidence=0, status='needs_review', + ) + pages = [ + LayoutPage( + page_no=1, width=300, height=120, + tokens=[LayoutToken( + token_id='parent-token', text='Part Number', normalized_text='part number', + bbox=parent.rows[0].cells[0].bbox, + normalized_bbox=parent.rows[0].cells[0].normalized_bbox, + source='native_text', confidence=1, + )], tables=[parent], + ), + LayoutPage(page_no=2, width=300, height=120, tokens=tokens, tables=[table]), + ] + return LayoutDocument( + document_id=21, content_hash='a' * 64, + parser=LayoutParserInfo(name='test', version='v1'), pages=pages, + quality=LayoutQuality( + status='needs_review', confidence=0, + issues=[LayoutIssue(code='truth_deferred', severity='blocking')], + ), + ) + + +def _contract(): + """构造包含客户料号、数量和 Reservation 的冻结 Schema。""" + return compile_table_header_contract({'fields': [ + { + 'field_id': 'part-id', 'field_code': 'customer_part_number', + 'scope': 'line', 'value_type': 'string', 'enabled': True, + 'aliases': ['Part Number'], 'normalizer_key': 'trim', 'validator_keys': [], + }, + { + 'field_id': 'qty-id', 'field_code': 'qty', + 'scope': 'line', 'value_type': 'decimal', 'enabled': True, + 'aliases': ['Qty'], 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], + }, + { + 'field_id': 'rsv-id', 'field_code': 'reservation_id', + 'scope': 'line', 'value_type': 'string', 'enabled': True, + 'aliases': ['Reservation ID'], 'normalizer_key': 'trim', 'validator_keys': [], + }, + ]}) + + +def test_layout_mapping_preserves_real_cell_and_token_evidence_and_zero_qty(): + """后置表头应精确映射,字段引用真实 layout cell/token,显式 Qty=0 行删除。""" + mapped = map_layout_document_to_schema(_layout(), contract=_contract())[0] + + assert mapped['header_row_index'] == 1 + assert mapped['mapping_status'] == 'candidate' + assert 'layout_table_not_accepted' in mapped['issues'] + data = next(row for row in mapped['rows'] if row['row_index'] == 2) + assert {field['field_id'] for field in data['fields']} == {'part-id', 'qty-id', 'rsv-id'} + part = next(field for field in data['fields'] if field['field_id'] == 'part-id') + assert part['cell_id'] == 'v-part' + assert part['token_ids'] == ['t-v-part'] + assert part['evidence_ref'] == 'layout:21:p1:table-main:v-part' + deleted = next(row for row in mapped['rows'] if row['row_index'] == 3) + assert deleted['role'] == 'deleted' + assert deleted['fields'] == [] + + +def test_layout_mapping_blocks_duplicate_target_columns(): + """同一字段命中两列时两列均 ambiguous,禁止选择左/右列。""" + mapped = map_layout_document_to_schema(_layout(duplicate_part=True), contract=_contract())[0] + + assert 'html_table_duplicate_field_columns' in mapped['issues'] + part_columns = [item for item in mapped['columns'] if 'customer_part_number' in item['candidates']] + assert len(part_columns) == 2 + assert all(item['status'] == 'ambiguous' for item in part_columns) + + +def test_layout_mapping_keeps_only_explicit_cross_page_continuation(): + """跨页关系只透传契约中的 continuation_of,不按重复表头自动猜父表。""" + mapped = map_layout_document_to_schema(_layout(continuation=True), contract=_contract()) + + child = next(item for item in mapped if item['table_id'] == 'table-main') + parent = next(item for item in mapped if item['table_id'] == 'table-parent') + assert child['continuation_of'] == 'table-parent' + assert parent['continuation_of'] is None diff --git a/backend/tests/test_shipping_document_layout_text_cell_alignment.py b/backend/tests/test_shipping_document_layout_text_cell_alignment.py new file mode 100644 index 00000000..146caf49 --- /dev/null +++ b/backend/tests/test_shipping_document_layout_text_cell_alignment.py @@ -0,0 +1,153 @@ +""" +backend/tests/test_shipping_document_layout_text_cell_alignment.py + +用途:验证 PDF 原生字符坐标只在唯一、非重叠文本匹配时形成 cell bbox 候选。 +依赖:text_cell_alignment、html_table、LayoutBBox。 +逻辑:覆盖完整匹配、重复 Qty、空 cell、找不到文本和重叠子串,禁止任何猜框行为。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.html_table import parse_html_grid +from app.services.shipping_notice.document_layout.text_cell_alignment import ( + align_html_cells_from_positioned_text, +) + + +def _characters(text: str) -> list[dict]: + """为无空格字符串生成从左到右的构造字符坐标。""" + return [ + {'text': char, 'bbox': {'x0': 10 + index * 5, 'y0': 20, 'x1': 14 + index * 5, 'y1': 30}} + for index, char in enumerate(text) + ] + + +def _align(html: str, text: str): + """使用固定页面和整表范围执行文本对齐。""" + return align_html_cells_from_positioned_text( + parse_html_grid(html, table_id='t'), + characters=_characters(text), + table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100), + page_width=200, + page_height=100, + ) + + +def test_unique_text_alignment_returns_normalized_cell_boxes(): + """每个 cell 文本唯一时应返回对应字符并集及标准化坐标。""" + result = _align( + '
    PartQty
    A120
    ', + 'PartQtyA120', + ) + + # 断言完整候选只来自唯一文本,不按列宽均分。 + assert result.complete is True + assert result.matched_cell_count == 4 + assert result.cells[0].bbox.model_dump() == {'x0': 10.0, 'y0': 20.0, 'x1': 29.0, 'y1': 30.0} + assert result.cells[0].normalized_bbox.x0 == 0.05 + assert result.cells[0].glyph_indices == [0, 1, 2, 3] + + +def test_repeated_text_is_rejected_instead_of_selected_by_position(): + """重复 Qty/值不得按首次出现或 HTML 顺序分配给 cell。""" + result = _align( + '
    QtyQty
    ', + 'QtyQty', + ) + + assert result.complete is False + assert result.cells == [] + assert result.issues == ['text_cell_alignment_text_not_unique'] + + +def test_empty_and_missing_cells_remain_unmatched(): + """空 cell 或文本层缺失不得生成零面积框或借用相邻字符。""" + result = _align( + '
    A1Missing
    ', + 'A1', + ) + + assert result.complete is False + assert result.matched_cell_count == 1 + assert result.issues == [ + 'text_cell_alignment_empty_cell', + 'text_cell_alignment_text_not_found', + ] + + +def test_overlapping_unique_substrings_do_not_share_glyphs(): + """一个长 cell 与其唯一子串不能共享同一组 PDF 字符。""" + result = _align( + '
    ABCBC
    ', + 'ABC', + ) + + assert result.complete is False + assert result.matched_cell_count == 1 + assert result.issues == ['text_cell_alignment_glyph_overlap'] + + +def test_invalid_page_glyph_is_dropped_without_adjusting_coordinates(): + """页面外 glyph 应被丢弃并记录问题,不能裁剪坐标后参与 cell 候选。""" + characters = _characters('A1') + characters.append({'text': 'X', 'bbox': {'x0': 20, 'y0': -2, 'x1': 24, 'y1': 5}}) + + result = align_html_cells_from_positioned_text( + parse_html_grid('
    A1
    ', table_id='invalid-glyph'), + characters=characters, + table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100), + page_width=200, + page_height=100, + ) + + assert result.complete is True + assert result.matched_cell_count == 1 + assert result.issues == ['text_cell_alignment_invalid_character_bbox'] + + +def test_page_overflow_glyph_and_table_are_never_normalized(): + """超出实际页面宽高的 glyph 被丢弃,整表 bbox 越界则直接拒绝。""" + characters = _characters('A1') + characters.append({'text': 'X', 'bbox': {'x0': 198, 'y0': 20, 'x1': 205, 'y1': 30}}) + grid = parse_html_grid('
    A1
    ', table_id='page-overflow') + + result = align_html_cells_from_positioned_text( + grid, + characters=characters, + table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100), + page_width=200, + page_height=100, + ) + assert result.complete is True + assert result.cells[0].normalized_bbox.x1 <= 1 + assert result.issues == ['text_cell_alignment_invalid_character_bbox'] + + with pytest.raises(ValueError, match='table bbox'): + align_html_cells_from_positioned_text( + grid, + characters=_characters('A1'), + table_bbox=LayoutBBox(x0=0, y0=0, x1=201, y1=100), + page_width=200, + page_height=100, + ) + + +def test_unique_string_split_across_visual_rows_is_rejected(): + """文本流中唯一但视觉上跨行的字符串不能被合并成一个大 cell bbox。""" + characters = _characters('AB') + characters[1]['bbox'] = {'x0': 10, 'y0': 60, 'x1': 14, 'y1': 70} + + result = align_html_cells_from_positioned_text( + parse_html_grid('
    AB
    ', table_id='cross-row'), + characters=characters, + table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100), + page_width=200, + page_height=100, + ) + + assert result.complete is False + assert result.cells == [] + assert result.issues == ['text_cell_alignment_geometry_discontinuous'] diff --git a/backend/tests/test_shipping_layout_truth_workbench.py b/backend/tests/test_shipping_layout_truth_workbench.py new file mode 100644 index 00000000..878baefe --- /dev/null +++ b/backend/tests/test_shipping_layout_truth_workbench.py @@ -0,0 +1,79 @@ +""" +backend/tests/test_shipping_layout_truth_workbench.py + +用途:验证人工真值工作台的仓库外输出门禁、离线页面和 annotation 契约校验入口。 +依赖:脚本模块、临时目录、正式 LayoutAnnotation。 +逻辑:不调用 MinerU;仅测试隐私路径和生成/校验纯函数,避免真实样本进入测试输出。 +""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +import pytest + + +def _module(): + """按脚本路径加载工作台模块,不依赖 scripts 包结构。""" + path = Path(__file__).resolve().parents[1] / 'scripts' / 'build_shipping_layout_truth_workbench.py' + spec = importlib.util.spec_from_file_location('shipping_layout_truth_workbench', path) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(module) + return module + + +def _manifest() -> dict: + """构造不含业务原文的最小离线工作台清单。""" + return { + 'sample_id': 'pdf-aaaaaaaaaaaa', + 'content_hash': 'a' * 64, + 'categories': ['native_pdf'], + 'pages': [{'page_no': 1, 'width': 100, 'height': 200}], + 'tables': [], + } + + +def test_workbench_rejects_repository_output_and_builds_offline_html(tmp_path, monkeypatch): + """真实样本输出不得落仓库;离线页面不得依赖 CDN 或网络脚本。""" + module = _module() + repository = tmp_path / 'repository' + repository.mkdir() + monkeypatch.setattr(module, 'REPOSITORY_ROOT', repository) + with pytest.raises(ValueError, match='outside'): + module._external_output_path(repository / 'tmp' / 'truth') + + external = tmp_path / 'external' + assert module._external_output_path(external) == external.resolve() + page = module._workbench_html(_manifest()) + assert 'shipping_document_layout_annotation.v1' in page + assert 'http://' not in page and 'https://' not in page + assert '导出 annotation.json' in page + + +def test_layout_annotation_contract_accepts_workbench_export_shape(): + """工作台导出字段必须能直接通过正式 annotation.v1 契约。""" + module = _module() + payload = { + 'schema_version': 'shipping_document_layout_annotation.v1', + 'layout_schema_version': 'shipping_document_layout.v1', + 'sample_id': 'pdf-aaaaaaaaaaaa', + 'content_hash': 'a' * 64, + 'categories': ['native_pdf'], + 'tables': [{ + 'annotation_id': 'table-p1-0', 'page_no': 1, 'table_index': 0, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.9, 'y1': 0.9}, + 'continuation_of': None, + 'cells': [{ + 'annotation_id': 'cell-p1-0-0', 'page_no': 1, 'table_index': 0, + 'row_index': 0, 'column_index': 0, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.5, 'y1': 0.2}, + 'normalized_text': 'Part', 'role': 'header', 'expected_field_code': 'part_number', + }], + }], + } + + annotation = module.LayoutAnnotation.model_validate_json(json.dumps(payload)) + assert annotation.tables[0].cells[0].expected_field_code == 'part_number' diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index 6f5295e8..5a3c3814 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -1319,9 +1319,9 @@ def test_flattened_text_does_not_guess_external_reservation_id(): assert issues[0]["severity"] == "blocking" -def test_adjudication_supports_non_numeric_reservation_templates(): - """不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。""" - raw_text = "Part Number\tReservation Order\tQty\nA001\tAWS-311\t2" +def test_adjudication_supports_five_digit_reservation_templates(): + """不同来源模板可使用 5 位数字 Reservation ID,并保留明确列证据。""" + raw_text = "Part Number\tReservation Order\tQty\nA001\t12345\t2" lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}] adjudicated, issues, status = adjudicate_notice_lines( @@ -1329,7 +1329,7 @@ def test_adjudication_supports_non_numeric_reservation_templates(): ) assert status == "ready" - assert adjudicated[0]["reservation_id"] == "AWS-311" + assert adjudicated[0]["reservation_id"] == "12345" assert issues[0]["reason"] == "value_corrected" @@ -1368,6 +1368,15 @@ Part Number\tReservation ID\tQty\tUnit Price\tAmount assert lines[0]["reservation_id"] == "1000140351" +def test_extract_notice_supports_five_digit_reservation_free_text(): + """自由文本回退路径应识别 5 位 Reservation ID、内部料号和数量。""" + parsed, _confidence, _warnings = _heuristic_extract("12345 10-40594-001 2") + + assert parsed["lines"] == [{ + "reservation_id": "12345", "part_number": "10-40594-001", "qty": 2.0, + }] + + def test_does_not_infer_reservation_id_without_configured_header(): headers = ["Part Number", "Ref", "Qty"] rows = [["10-40594-001", 1000140351, 2]] diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py index f5e24ab4..cad4d868 100644 --- a/backend/tests/test_shipping_notice_intakes.py +++ b/backend/tests/test_shipping_notice_intakes.py @@ -112,7 +112,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): structured_result_json={ 'business_summary': { 'po_number': '7001', - 'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 1}], + 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}], }, }, validation_status='needs_review', @@ -134,7 +134,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): 'selected': False, 'business_summary': { 'po_number': '7001', - 'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 2}], + 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}], }, }, headers=owner_headers, @@ -3333,8 +3333,13 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid ) eml_bytes = msg.as_bytes() + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 4 with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): + with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'), patch( + 'app.services.shipping_notice.document_layout.runtime.build_mineru_table_snapshot', + side_effect=AssertionError('Intake parse must not call MinerU inline'), + ): asset_data = upload_file_asset( user_id=shipping_user.id, upload=FileStorage( @@ -3408,6 +3413,12 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid assert len(cands) == 0 assert len(children) == 3 assert len({c.content_hash for c in children}) == 3 + from app.models import Job, ShippingDocumentLayoutVersion + + assert ShippingDocumentLayoutVersion.query.filter( + ShippingDocumentLayoutVersion.document_id.in_([item.id for item in pdf_docs]), + ).count() == 3 + assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3 detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True) assert detail['document_count'] == 4 @@ -3431,6 +3442,8 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid ) assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4 assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0 + assert ShippingDocumentLayoutVersion.query.count() == 3 + assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3 assert ( db.session.query(FileAsset) .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None)) @@ -3439,6 +3452,66 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid ) +def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak( + app, shipping_user, monkeypatch, +): + """HTML 正文表格应生成独立布局版本,临时 HTML 不得进入 Intake 摘要或 Dify 文档正文。""" + from email.message import EmailMessage + from io import BytesIO + + from werkzeug.datastructures import FileStorage + + from app.models import ShippingDocumentLayoutVersion + from app.services.file_assets.service import upload_file_asset + from app.services.shipping_notice.intake_parse_workflow import run_intake_parse + + msg = EmailMessage() + msg['Subject'] = 'HTML table order' + msg.set_content('PO 12345') + msg.add_alternative( + '' + '' + '
    PartQty
    A-12
    ', + subtype='html', + ) + eml_bytes = msg.as_bytes() + with app.app_context(), patch( + 'app.services.file_assets.service.file_asset_storage.upload_bytes', + ): + asset_data = upload_file_asset( + user_id=shipping_user.id, + upload=FileStorage( + stream=BytesIO(eml_bytes), filename='html-order.eml', content_type='message/rfc822', + ), + ) + parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() + intake = ShippingNoticeIntake( + intake_no='SNI-HTML-LAYOUT', asset_id=parent.id, user_id=shipping_user.id, + purpose='shipping_notice', parse_status='parsing', parser_version='v6', + ) + db.session.add(intake) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', + lambda _asset: eml_bytes, + ) + + result = run_intake_parse(intake, parent) + db.session.expire_all() + body = ShippingNoticeDocument.query.filter_by( + intake_id=intake.id, document_type='email_body', + ).one() + version = ShippingDocumentLayoutVersion.query.filter_by(document_id=body.id).one() + structured = db.session.get(ShippingNoticeIntake, intake.id).structured_result_json + + assert result['status'] == 'parsed' + assert version.status == 'needs_review' + assert version.payload_json['layout_candidate']['parser']['name'] == 'eml-html-dom' + assert 'SECRET' not in repr(version.payload_json) + assert 'body_html_tables' not in repr(structured) + assert ' tuple[User, ChatSession, ShippingNoticeIntake, S classification='order_notice', parse_status='parsed', extracted_text=( - 'PO 4510000001 SKU SKU-A QTY 10 RSV R-100 SOURCE AWS Dublin HUB DUB\n' + 'PO 4510000001 SKU SKU-A QTY 10 RSV 1000140351 SOURCE AWS Dublin HUB DUB\n' 'PO 4510000002 SKU SKU-B QTY 20\n' 'SKU SKU-STATE SKU SKU-STALE SKU SKU-UI-STATE SKU SKU-OPEN-EXISTING\n' 'SKU P123456 SKU IGNORED-SKU QTY 1 QTY 2 QTY 3 QTY 5 QTY 24' @@ -260,6 +260,7 @@ def _persist_test_orders(payload: dict) -> dict: run_id=None, schema_version_id=int(schema.id), extraction_source='test_workflow', + frozen_layout_candidates_by_document=payload.get('layout_candidates_by_document'), auto_create_enabled=True, ) @@ -282,6 +283,36 @@ def _persist_shadow_orders(payload: dict) -> dict: auto_create_enabled=False, ) + +def test_plain_text_table_issue_reaches_candidate_as_machine_readable_conflict(app): + """无 cell 证据的纯文本表格必须在 Candidate 保留原因码,供现有任务 UI 解释。""" + with app.app_context(): + _user, _session, intake, document, _runtime = _seed_extraction_input() + document.extracted_text = 'part_number\tqty\nPART-PLAIN\t3' + db.session.commit() + fields = _ensure_order_schema() + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + order = { + 'schema_version_id': version.id, 'schema_checksum': version.checksum, + 'classification': 'shipping_request', 'classification_confidence': 0.99, + 'source_intake_no': intake.intake_no, 'primary_document_id': document.id, + 'header_fields': [], 'lines': [{'fields': [{ + 'field_id': fields['qty'], 'observations': [{ + 'value': 3, 'document_id': document.id, + 'quote': 'qty\nPART-PLAIN\t3', 'confidence': 0.9, + }], + }]}], 'conflicts': [], + } + + _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [order]}) + + candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one() + assert candidate.validation_status == 'needs_review' + assert any( + item.get('reason') == 'plain_text_table_has_no_cell_evidence' + for item in candidate.conflicts_json + ) + def _order( *, intake_no: str, @@ -308,7 +339,7 @@ def _order( if include_process_fields: line_fields.extend([ {'field_id': fields['reservation_id'], 'observations': [ - {'value': 'R-100', 'quote': 'R-100', 'document_id': document_id, 'confidence': confidence}, + {'value': '1000140351', 'quote': '1000140351', 'document_id': document_id, 'confidence': confidence}, ]}, {'field_id': fields['inventory_source_hint'], 'observations': [ {'value': 'AWS Dublin', 'quote': 'AWS Dublin', 'document_id': document_id, 'confidence': confidence}, @@ -413,8 +444,8 @@ def _attach_existing_task_dynamic_order(task: ShippingTask) -> None: db.session.flush() -def test_order_field_display_uses_locked_schema_sequence(app): - """对话字段顺序必须来自任务锁定 Schema,且通用上下文不能混入订单信息。""" +def test_order_field_display_uses_current_catalog_sequence(app): + """对话字段顺序使用当前字段目录,锁定 Schema 仍负责字段定义和分类。""" with app.app_context(): _ensure_order_schema() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() @@ -436,7 +467,7 @@ def test_order_field_display_uses_locked_schema_sequence(app): assert [item['field_code'] for item in display['header_fields']] == ['po_number'] assert [item['field_code'] for item in display['line_fields']][:3] == [ - 'qty', 'part_number', 'reservation_id', + 'part_number', 'qty', 'reservation_id', ] @@ -484,7 +515,7 @@ def _add_extraction_intake( content_hash=f'order-extraction-document-{suffix.lower()}', classification='order_notice', parse_status='parsed', - extracted_text=f'SKU SKU-{normalized} QTY 1 RSV R-100', + extracted_text=f'SKU SKU-{normalized} QTY 1 RSV 1000140351', ) db.session.add(document) db.session.commit() @@ -574,7 +605,7 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes 'task_id': task.task_no, 'line_index': 0, 'patch': { - 'reservation_id': 'R-100', + 'reservation_id': '1000140351', }, 'comment': '用户通过自然对话补齐流程字段', }) @@ -910,13 +941,13 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide def test_order_extraction_backend_blocks_reservation_source_conflict(app): - """即使 LLM 未声明冲突,后端也必须用明确表格列证据阻断不一致的 Reservation。""" + """即使 LLM 未声明冲突,accepted cell 证据也必须阻断不一致的 Reservation。""" with app.app_context(): user, _session, intake, document, runtime_context = _seed_extraction_input() document.extracted_text = ( "Part Number\tReservation ID\tQty\n" - "SKU-A\tR-200\t10\n" - "LLM candidate quote R-100" + "SKU-A\t1000140352\t10\n" + "LLM candidate quote 1000140351" ) db.session.commit() context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) @@ -932,6 +963,24 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): result = _persist_test_orders({ 'agent_runtime_context': runtime_context, 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'layout_candidates_by_document': {int(document.id): [{ + 'page_no': 1, 'table_id': 'reservation-table', + 'mapping_status': 'accepted', 'issues': [], + 'rows': [{'row_index': 1, 'role': 'data', 'fields': [ + { + 'field_id': _ensure_order_schema()['part_number'], + 'value': 'SKU-A', 'quote': 'SKU-A', 'column_index': 0, + 'cell_id': 'part-cell', + 'evidence_ref': f'layout:{document.id}:p1:reservation-table:part-cell', + }, + { + 'field_id': _ensure_order_schema()['reservation_id'], + 'value': '1000140352', 'quote': '1000140352', 'column_index': 1, + 'cell_id': 'reservation-cell', + 'evidence_ref': f'layout:{document.id}:p1:reservation-table:reservation-cell', + }, + ]}], + }]}, 'orders': [order], }) @@ -945,7 +994,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): item for item in adjudication['observations'] if item['field_id'] == _ensure_order_schema()['reservation_id'] ] - assert {item['source_type'] for item in reservation_observations} == {'backend_table', 'attachment_text'} + assert {item['source_type'] for item in reservation_observations} == {'attachment_table', 'attachment_text'} assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 @@ -1178,7 +1227,7 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app) qty=10, include_process_fields=True, ) - _set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351') + _set_dynamic_line_field(order, 'reservation_id', '1000140352', quote='1000140352') result = _persist_test_orders({ 'agent_runtime_context': runtime_context, diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index 18d698c4..e90f2f72 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -25,14 +25,16 @@ def test_normalize_reservation_id_string(): assert normalize_reservation_id("1000140351") == "1000140351" -def test_reservation_contract_rejects_internal_hex_but_keeps_business_ids(): - """硬契约应拒绝内部 hex 主键,同时兼容已有字母型业务 Reservation ID。""" +def test_reservation_contract_only_accepts_five_or_ten_digits(): + """硬契约只接受 5 位或 10 位纯数字 Reservation ID。""" assert not is_valid_reservation_id("1f1a682dfdc446a393415dee93eb36ce") assert validated_reservation_id("1f1a682dfdc446a393415dee93eb36ce") == "" + assert is_valid_reservation_id("12345") assert is_valid_reservation_id("3000092917") - assert is_valid_reservation_id("AWS-311") - assert is_valid_reservation_id("R-1") - assert not is_valid_reservation_id("AWS-311", numeric_only=True) + assert not is_valid_reservation_id("123456") + assert not is_valid_reservation_id("AWS-311") + assert not is_valid_reservation_id("R-1") + assert not is_valid_reservation_id("12345678901", numeric_only=True) def test_reservation_gate_blocks_empty_and_malformed_order_lines(): diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index b6e2abde..5cd999db 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -488,11 +488,11 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1) + _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) task.process_status = "inventory_ready" task.review_status = None task.pending_human_reason = "inv_unavail" - task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "R-1", "available_qty": 3}] + task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}] task.match_status = "fulfillable" task.shortage_json = {"lines": []} task.line_results_json = [{"part_number": "OLD", "status": "ok"}] @@ -570,7 +570,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1) + _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) task.process_status = "waiting_inventory" task.pending_human_reason = PH_RPA_PENDING task.step_payload_json = { @@ -634,7 +634,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1) + _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) task.process_status = "waiting_inventory" task.pending_human_reason = PH_RPA_EXHAUSTED task.step_payload_json = { @@ -718,7 +718,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1) + _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) task.process_status = "waiting_inventory" task.pending_human_reason = PH_RPA_PENDING task.step_payload_json = { diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py new file mode 100644 index 00000000..05fd3dde --- /dev/null +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -0,0 +1,316 @@ +""" +backend/tests/test_shipping_order_document_profile_service.py + +用途:验证订单文档 Profile 的 Schema 字段绑定、发布生命周期、并发锁和管理 API 权限。 +依赖:全局 Flask 测试库、订单 Schema/Profile 模型与服务。 +逻辑:构造不可变 Schema 后保存模板级特例;发布新版本退役旧版,非法字段和并发覆盖必须阻断。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.models import ( + ShippingOrderDocumentProfile, + ShippingNoticeDocument, + ShippingNoticeIntake, + FileAsset, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + User, +) +from app.services.shipping_notice import order_document_profile_service as service +from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot +from tests.conftest import parse_api_data, parse_api_error + + +def _schema_version() -> ShippingOrderSchemaVersion: + """创建含模板所需客户料号、内部料号和数量字段的发布 Schema。""" + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add(schema) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + checksum='a' * 64, + published_at=datetime.utcnow(), + definition_json={'fields': [ + { + 'field_id': 'customer-field', 'field_code': 'customer_part_number', + 'scope': 'line', 'value_type': 'string', 'enabled': True, + 'normalizer_key': 'trim', 'validator_keys': [], + }, + { + 'field_id': 'part-field', 'field_code': 'part_number', + 'scope': 'line', 'value_type': 'string', 'enabled': True, + 'normalizer_key': 'trim', 'validator_keys': [], + }, + { + 'field_id': 'qty-field', 'field_code': 'qty', + 'scope': 'line', 'value_type': 'decimal', 'enabled': True, + 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'], + }, + ]}, + ) + db.session.add(version) + db.session.commit() + return version + + +def _data(schema_id: int, *, fingerprint: str = 'b' * 64) -> dict: + """构造已确认模板 `Part Number/Vendor Item#` 的 Profile 请求。""" + return { + 'profile_code': 'PO_312207', + 'display_name': 'PO 312207 template', + 'schema_version_id': schema_id, + 'definition': { + 'structure_fingerprint': fingerprint, + 'header_row_index': 0, + 'data_start_row_index': 1, + 'drop_zero_qty': True, + 'column_rules': [ + { + 'column_index': 1, + 'extractor_key': 'direct', + 'target_field_codes': ['customer_part_number'], + }, + { + 'column_index': 2, + 'extractor_key': 'direct', + 'target_field_codes': ['part_number'], + }, + { + 'column_index': 3, + 'extractor_key': 'direct', + 'target_field_codes': ['qty'], + }, + ], + }, + } + + +def test_profile_publish_freezes_field_ids_and_retires_previous_version(app): + """模板级语义必须冻结稳定字段 ID;新发布版本原子退役旧发布版本。""" + with app.app_context(): + schema = _schema_version() + first = service.save_draft(_data(schema.id), actor_id=None) + published = service.publish( + first['id'], actor_id=None, expected_lock_version=first['lock_version'], + ) + + rules = published['definition']['column_rules'] + assert rules[0]['target_fields'] == [{ + 'field_id': 'customer-field', 'field_code': 'customer_part_number', + }] + assert rules[1]['target_fields'] == [{ + 'field_id': 'part-field', 'field_code': 'part_number', + }] + assert len(published['checksum']) == 64 + + draft = service.clone_draft(published['id'], actor_id=None) + update = _data(schema.id, fingerprint='c' * 64) + update['expected_lock_version'] = draft['lock_version'] + saved = service.save_draft(update, actor_id=None, profile_id=draft['id']) + replacement = service.publish( + draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], + ) + + assert replacement['version'] == 2 + assert db.session.get(ShippingOrderDocumentProfile, published['id']).status == 'retired' + assert ShippingOrderDocumentProfile.query.filter_by( + profile_code='PO_312207', status='published', + ).one().id == replacement['id'] + + +def test_profile_rejects_unknown_field_and_stale_lock(app): + """Profile 不得引用未绑定 Schema 字段,草稿并发更新不得后写覆盖。""" + with app.app_context(): + schema = _schema_version() + invalid = _data(schema.id) + invalid['definition']['column_rules'][0]['target_field_codes'] = ['unknown_field'] + with pytest.raises(Exception) as caught: + service.save_draft(invalid, actor_id=None) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID' + + draft = service.save_draft(_data(schema.id), actor_id=None) + stale = _data(schema.id, fingerprint='d' * 64) + stale['expected_lock_version'] = draft['lock_version'] + 1 + with pytest.raises(Exception) as caught: + service.save_draft(stale, actor_id=None, profile_id=draft['id']) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT' + + duplicate = _data(schema.id) + duplicate['profile_code'] = 'PO_DUPLICATE_TARGET' + duplicate['definition']['column_rules'][1]['target_field_codes'] = ['customer_part_number'] + with pytest.raises(Exception) as caught: + service.save_draft(duplicate, actor_id=None) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' + + +def test_profile_admin_api_requires_admin_and_uses_standard_errors(app): + """普通用户不能维护 Profile;管理员错误使用统一业务 envelope。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + schema = _schema_version() + schema_id = schema.id + db.session.add_all([ + User(username='profile-admin', email='profile-admin@example.com', role='admin', status='active'), + User(username='profile-user', email='profile-user@example.com', role='user', status='active'), + ]) + db.session.commit() + + client = app.test_client() + denied = client.post( + '/api/admin/shipping-notice/order-document-profiles', + json=_data(schema_id), + headers={'X-Username': 'profile-user', 'X-Role': 'user'}, + ) + assert denied.status_code == 403 + + created = client.post( + '/api/admin/shipping-notice/order-document-profiles', + json=_data(schema_id), + headers={'X-Username': 'profile-admin', 'X-Role': 'admin'}, + ) + assert created.status_code == 201 + payload = parse_api_data(created.get_json()) + assert payload['profile_code'] == 'PO_312207' + + conflict = client.put( + f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}", + json={**_data(schema_id), 'expected_lock_version': payload['lock_version'] + 1}, + headers={'X-Username': 'profile-admin', 'X-Role': 'admin'}, + ) + assert conflict.status_code == 409 + assert parse_api_error(conflict.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT' + + +def test_profile_sample_api_supports_secure_preview_create_and_version_update(app): + """样本 API 必须鉴权、隐藏 HTML、服务端计算指纹,并支持新版本按乐观锁重配。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + schema = _schema_version() + user = User(username='sample-owner', email='sample-owner@example.com', role='admin', status='active') + regular_user = User( + username='sample-user', email='sample-user@example.com', role='user', status='active', + ) + db.session.add_all([user, regular_user]) + db.session.flush() + asset = FileAsset( + asset_no='FA-PROFILE-SAMPLE', owner_user_id=user.id, original_filename='sample.pdf', + storage_provider='minio', storage_bucket='test', storage_key='sample.pdf', + content_hash='c' * 64, file_size=100, mime_type='application/pdf', + upload_status='ready', lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-PROFILE-SAMPLE', asset_id=asset.id, user_id=user.id, + purpose='shipping_notice', parse_status='parsed', parser_version='v6', + ) + db.session.add(intake) + db.session.flush() + html = ( + '' + '
    Part NumberVendor Item#Qty
    CUSTOMER-1INTERNAL-13
    ' + ) + document = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', + attachment_key='sample.pdf', filename='sample.pdf', content_hash='c' * 64, + classification='order_notice', parse_status='parsed', extracted_text='sample', + ) + db.session.add(document) + db.session.flush() + record_inline_layout_snapshot(document, { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'mineru', 'provider_version': '3.1.14', 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}], + }) + db.session.commit() + document_id = document.id + schema_id = schema.id + + client = app.test_client() + user_headers = {'X-Username': 'sample-user', 'X-Role': 'user'} + admin_headers = {'X-Username': 'sample-owner', 'X-Role': 'admin'} + denied = client.get( + '/api/admin/shipping-notice/order-document-profile-samples', headers=user_headers, + ) + assert denied.status_code == 403 + + samples_response = client.get( + '/api/admin/shipping-notice/order-document-profile-samples', headers=admin_headers, + ) + assert samples_response.status_code == 200 + samples = parse_api_data(samples_response.get_json()) + assert samples[0]['document_id'] == document_id + + preview_response = client.get( + f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/tables', + headers=admin_headers, + ) + assert preview_response.status_code == 200 + preview = parse_api_data(preview_response.get_json()) + assert preview['tables'][0]['rows'][0] == ['Part Number', 'Vendor Item#', 'Qty'] + assert 'html' not in preview['tables'][0] + assert 'bbox' not in preview['tables'][0] + + sample_payload = { + 'profile_code': 'SAMPLE_TEMPLATE', 'display_name': 'Sample template', + 'schema_version_id': schema_id, 'document_id': document_id, 'table_id': 'table-1', + 'header_row_index': 0, 'data_start_row_index': 1, 'drop_zero_qty': True, + 'column_rules': [ + {'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']}, + {'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']}, + {'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']}, + ], + 'structure_fingerprint': 'browser-forged-value', + } + created = client.post( + '/api/admin/shipping-notice/order-document-profiles/from-sample', + json=sample_payload, headers=admin_headers, + ) + assert created.status_code == 201 + draft = parse_api_data(created.get_json()) + assert draft['structure_fingerprint'] != 'browser-forged-value' + assert draft['definition']['structure_fingerprint'] == draft['structure_fingerprint'] + + published_response = client.post( + f"/api/admin/shipping-notice/order-document-profiles/{draft['id']}/publish", + json={'expected_lock_version': draft['lock_version']}, headers=admin_headers, + ) + published = parse_api_data(published_response.get_json()) + clone_response = client.post( + f"/api/admin/shipping-notice/order-document-profiles/{published['id']}/clone", + headers=admin_headers, + ) + clone = parse_api_data(clone_response.get_json()) + + stale = client.put( + f"/api/admin/shipping-notice/order-document-profiles/{clone['id']}/from-sample", + json={**sample_payload, 'expected_lock_version': clone['lock_version'] + 1}, + headers=admin_headers, + ) + assert stale.status_code == 409 + assert parse_api_error(stale.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT' + + updated_response = client.put( + f"/api/admin/shipping-notice/order-document-profiles/{clone['id']}/from-sample", + json={ + **sample_payload, + 'display_name': 'Sample template v2', + 'change_note': 'Reconfirmed against MinerU sample', + 'expected_lock_version': clone['lock_version'], + }, + headers=admin_headers, + ) + assert updated_response.status_code == 200 + updated = parse_api_data(updated_response.get_json()) + assert updated['id'] == clone['id'] + assert updated['display_name'] == 'Sample template v2' + assert updated['change_note'] == 'Reconfirmed against MinerU sample' + assert updated['lock_version'] == clone['lock_version'] + 1 diff --git a/backend/tests/test_shipping_order_extraction_dify_guide.py b/backend/tests/test_shipping_order_extraction_dify_guide.py new file mode 100644 index 00000000..f87c343e --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_dify_guide.py @@ -0,0 +1,120 @@ +""" +backend/tests/test_shipping_order_extraction_dify_guide.py + +用途:验证订单抽取 Dify 配置指南中的校验 Code 节点可执行且保持业务错误契约。 +依赖:订单抽取 Workflow 指南、标准 json/pathlib。 +逻辑:直接加载指南中的 Python 节点脚本,确保单文档字段错位被丢弃而非阻断跨文档聚合。 +""" + +from __future__ import annotations + +import json +from pathlib import Path + + +def _validation_main(): + """ + 从 Dify 配置指南提取并编译订单校验节点的 main 函数。 + + Returns: + callable: 与 Dify `VALIDATE_AND_NORMALIZE_ORDERS` 节点一致的入口函数。 + """ + guide = Path(__file__).parents[2] / 'docs' / 'features' / 'shipping-notice' / 'order-extraction-workflow-dify-guide.md' + source = guide.read_text(encoding='utf-8') + marker = 'def _field_map(schema):' + marker_index = source.index(marker) + block_start = source.rfind('```python', 0, marker_index) + len('```python\n') + block_end = source.index('\n```', marker_index) + namespace: dict[str, object] = {} + exec(source[block_start:block_end], namespace) + return namespace['main'] + + +def _contract() -> dict: + """构造包含可选单价和必填需求数量的最小冻结 Schema 契约。""" + return { + 'schema_version_id': 1, + 'checksum': 'checksum', + 'fields': [ + { + 'field_id': 'po-id', 'field_code': 'po_number', 'display_name': '采购订单号', + 'scope': 'header', 'value_type': 'string', 'collection_mode': 'llm_extraction', + 'required': True, 'validator_keys': ['non_empty'], + }, + { + 'field_id': 'unit-price-id', 'field_code': 'unit_price', 'display_name': '单价', + 'scope': 'line', 'value_type': 'decimal', 'collection_mode': 'llm_extraction', + 'required': False, 'validator_keys': [], + }, + { + 'field_id': 'qty-id', 'field_code': 'qty', 'display_name': '需求数量', + 'scope': 'line', 'value_type': 'decimal', 'collection_mode': 'llm_extraction', + 'required': True, 'validator_keys': ['positive_decimal'], + }, + ], + } + + +def _order(fields: list[dict]) -> dict: + """构造只含一条订单行的最小模型输出。""" + return { + 'orders': [{ + 'schema_version_id': 1, 'schema_checksum': 'checksum', + 'classification': 'shipping_request', 'classification_confidence': 0.98, + 'source_intake_no': 'SNI-TEST', 'primary_document_id': 1, + 'header_fields': [], 'lines': [{'fields': fields}], 'conflicts': [], + }], + } + + +def _observation(field_id: str, value: object) -> dict: + """构造带当前 Document 逐字证据的字段 Observation。""" + return { + 'field_id': field_id, + 'observations': [{'value': value, 'document_id': 1, 'quote': str(value), 'confidence': 0.98}], + } + + +def test_dify_validation_drops_optional_numeric_field_type_mismatch(): + """可选单价错填料号时应忽略该字段,保留必填需求数量并通过校验。""" + main = _validation_main() + result = main( + json.dumps(_order([ + _observation('unit-price-id', 'D4-A08AR12000002'), + _observation('qty-id', 30), + ])), + json.dumps(_contract()), 'SNI-TEST', 1, + ) + + assert result['validation_ok'] is True + fields = json.loads(result['orders'])[0]['lines'][0]['fields'] + assert [item['field_id'] for item in fields] == ['qty-id'] + + +def test_dify_validation_drops_required_field_type_mismatch_for_partial_unit(): + """单文档的必填 Qty 类型错误只丢弃该字段,完整性由 HXOPS 跨文档判断。""" + main = _validation_main() + result = main( + json.dumps(_order([_observation('qty-id', 'thirty')])), + json.dumps(_contract()), 'SNI-TEST', 1, + ) + + assert result['validation_ok'] is True + normalized = json.loads(result['orders']) + assert normalized[0]['lines'] == [] + assert result['validation_error'] == '' + + +def test_dify_validation_accepts_email_header_fragment_without_order_lines(): + """EML 只提供 PO 等 Header 证据时必须成功,等待 PDF Unit 补充订单行。""" + main = _validation_main() + payload = _order([]) + payload['orders'][0]['header_fields'] = [_observation('po-id', '4518738152')] + payload['orders'][0]['lines'] = [] + + result = main(json.dumps(payload), json.dumps(_contract()), 'SNI-TEST', 1) + + assert result['validation_ok'] is True + normalized = json.loads(result['orders'])[0] + assert normalized['lines'] == [] + assert normalized['header_fields'][0]['field_id'] == 'po-id' diff --git a/backend/tests/test_shipping_order_extraction_quality_gate.py b/backend/tests/test_shipping_order_extraction_quality_gate.py new file mode 100644 index 00000000..c239606b --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_quality_gate.py @@ -0,0 +1,315 @@ +""" +backend/tests/test_shipping_order_extraction_quality_gate.py + +用途:验证 L7 订单抽取双人影子标签、指标、双角色批准和 Runtime Binding 自动建单门禁。 +依赖:质量服务、Agent Runtime Binding、订单抽取 Run 测试夹具。 +逻辑:构造 100 个匿名一致样本达标批次,并覆盖分歧、权限边界和批准引用。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.core.errors import ConflictError, ValidationError +from app.jobs.context import JobContext +from app.jobs.handlers.shipping_order_extraction import run_shipping_order_extraction +from app.jobs.queue import claim_next_job +from app.jobs.types import JobType +from app.models import ( + Agent, + ShippingOrderExtractionQualityBatch, + ShippingOrderExtractionQualityLabel, + ShippingOrderExtractionRun, + User, +) +from app.services.agent_runtime_binding_service import save_runtime_binding +from app.services.shipping_notice.order_extraction_quality_service import ( + approve_quality_batch, + list_approved_quality_batches, + quality_metrics, + require_approved_quality_batch, + save_quality_label, +) +from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run +from tests.test_shipping_order_extraction_runs import _seed_run_input +from tests.conftest import parse_api_data + + +def _quality_batch(owner: Agent, schema_version_id: int, creator: User) -> ShippingOrderExtractionQualityBatch: + """建立 collecting 批次,供服务级测试批量注入匿名标签。""" + batch = ShippingOrderExtractionQualityBatch( + batch_no=f'SOQ-TEST-{owner.id}', owner_agent_id=owner.id, + schema_version_id=schema_version_id, + threshold_version='l7.v1', status='collecting', created_by_id=creator.id, + ) + db.session.add(batch) + db.session.flush() + return batch + + +def _add_agreed_samples( + batch: ShippingOrderExtractionQualityBatch, runs: list[ShippingOrderExtractionRun], + first: User, second: User, +) -> None: + """为每个 Run 写入两份完全一致且无错误的匿名标签。""" + for run in runs: + for reviewer in (first, second): + db.session.add(ShippingOrderExtractionQualityLabel( + batch_id=batch.id, run_id=run.id, reviewer_id=reviewer.id, + core_expected_count=4, core_extracted_count=4, core_correct_count=4, + wrong_merge=False, wrong_split=False, wrong_auto_create=False, + )) + db.session.flush() + + +def test_quality_metrics_require_two_matching_reviews(app): + """单人和分歧标签不计样本;100 个一致样本才通过固定阈值。""" + with app.app_context(): + user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS') + second = User(username='quality-second', email='quality-second@example.com', role='admin', password_hash='x') + db.session.add(second) + db.session.flush() + batch = _quality_batch(owner, 1, user) + runs = [] + for index in range(100): + run = ShippingOrderExtractionRun( + run_no=f'SNER-QUALITY-{index:03d}', user_id=user.id, owner_agent_id=owner.id, + conversation_id=f'quality-{index}', schema_version_id=batch.schema_version_id, + input_snapshot_hash=f'{index:064x}'[-64:], input_snapshot_json={}, + idempotency_key=f'{index + 1000:064x}'[-64:], status='completed', phase='completed', + provider_config_json={'auto_create_enabled': False}, + ) + db.session.add(run) + runs.append(run) + db.session.flush() + _add_agreed_samples(batch, runs, user, second) + + metrics = quality_metrics(batch) + + assert metrics['eligible'] is True + assert metrics['agreed_sample_count'] == 100 + assert metrics['precision'] == 1.0 + assert metrics['recall'] == 1.0 + + +def test_quality_label_rejects_wrong_owner_or_auto_create_run(app): + """标签只能引用同 Owner/Schema 的终态 unit.v3 影子 Run,不能标生产自动建单结果。""" + with app.app_context(): + user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-LABEL') + user.role = 'admin' + batch = _quality_batch(owner, 1, user) + run = ShippingOrderExtractionRun( + run_no='SNER-QUALITY-INVALID', user_id=user.id, owner_agent_id=owner.id, + conversation_id=session.session_id, schema_version_id=batch.schema_version_id, + input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64, + status='completed', phase='completed', + provider_config_json={'auto_create_enabled': True}, + ) + db.session.add(run) + db.session.flush() + + with pytest.raises(ValidationError) as caught: + save_quality_label( + batch_id=batch.id, run_no=run.run_no, actor_id=user.id, + payload={'core_expected_count': 4, 'core_extracted_count': 4, 'core_correct_count': 4}, + ) + + assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID' + + +def test_approved_quality_batch_is_required_for_auto_create_binding(app): + """unit.v3 自动建单必须引用同 Owner、当前阈值、双人批准且仍达标的批次。""" + with app.app_context(): + user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-BINDING') + business = User(username='quality-business', email='quality-business@example.com', role='admin', password_hash='x') + technical = User(username='quality-technical', email='quality-technical@example.com', role='admin', password_hash='x') + db.session.add_all([business, technical]) + db.session.flush() + batch = _quality_batch(owner, 1, user) + runs = [] + for index in range(100): + run = ShippingOrderExtractionRun( + run_no=f'SNER-APPROVE-{index:03d}', user_id=user.id, owner_agent_id=owner.id, + conversation_id=f'approve-{index}', schema_version_id=batch.schema_version_id, + input_snapshot_hash=f'{index + 2000:064x}'[-64:], input_snapshot_json={}, + idempotency_key=f'{index + 3000:064x}'[-64:], status='completed', phase='completed', + provider_config_json={'auto_create_enabled': False}, + ) + db.session.add(run) + runs.append(run) + db.session.flush() + _add_agreed_samples(batch, runs, business, technical) + batch.status = 'ready' + db.session.flush() + approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id) + approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id) + provider = Agent.query.filter_by(exposure_mode='internal').first() + + approved = require_approved_quality_batch( + batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id, + ) + binding = save_runtime_binding( + owner_agent_id=owner.id, capability_code='shipping.order_extraction', + provider_agent_id=provider.id, enabled=True, quality_batch_id=batch.id, + config={'auto_create_enabled': True}, + ) + + assert approved.status == 'approved' + assert binding.quality_batch_id == batch.id + + +def test_same_admin_cannot_approve_both_roles(app): + """业务和技术批准必须由不同管理员完成。""" + with app.app_context(): + user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-APPROVERS') + user.role = 'admin' + batch = _quality_batch(owner, 1, user) + batch.status = 'ready' + batch.business_approved_by_id = user.id + batch.business_approved_at = datetime.utcnow() + db.session.flush() + + with pytest.raises(ConflictError): + require_approved_quality_batch( + batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id, + ) + with pytest.raises(ConflictError): + approve_quality_batch(batch_id=batch.id, role='technical', actor_id=user.id) + + +def test_first_approval_freezes_labels_and_schema_mismatch_blocks_release(app): + """任一角色批准后标签不可变化,且旧 Schema 批次不能给新 Schema 的执行放行。""" + with app.app_context(): + user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-FREEZE') + user.role = 'admin' + second = User(username='quality-freeze-second', email='quality-freeze-second@example.com', role='admin', password_hash='x') + db.session.add(second) + db.session.flush() + batch = _quality_batch(owner, 1, user) + runs = [] + for index in range(100): + run = ShippingOrderExtractionRun( + run_no=f'SNER-FREEZE-{index:03d}', user_id=user.id, owner_agent_id=owner.id, + conversation_id=f'freeze-{index}', schema_version_id=batch.schema_version_id, + input_snapshot_hash=f'{index + 4000:064x}'[-64:], input_snapshot_json={}, + idempotency_key=f'{index + 5000:064x}'[-64:], status='completed', phase='completed', + provider_config_json={'auto_create_enabled': False}, + ) + db.session.add(run) + runs.append(run) + db.session.flush() + _add_agreed_samples(batch, runs, user, second) + batch.status = 'ready' + db.session.flush() + approve_quality_batch(batch_id=batch.id, role='business', actor_id=user.id) + + with pytest.raises(ConflictError) as frozen: + save_quality_label( + batch_id=batch.id, run_no=runs[0].run_no, actor_id=second.id, + payload={'core_expected_count': 5, 'core_extracted_count': 5, 'core_correct_count': 5}, + ) + with pytest.raises(ConflictError): + require_approved_quality_batch( + batch_id=batch.id, owner_agent_id=owner.id, + schema_version_id=batch.schema_version_id + 1, + ) + + assert frozen.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE' + + +def test_approved_batch_is_listed_and_frozen_on_run(app): + """管理端候选只含当前 Schema 已批准批次,启用后 Run 必须冻结相同批次。""" + with app.app_context(): + user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-RUN') + business = User(username='quality-run-business', email='quality-run-business@example.com', role='admin', password_hash='x') + technical = User(username='quality-run-technical', email='quality-run-technical@example.com', role='admin', password_hash='x') + db.session.add_all([business, technical]) + db.session.flush() + batch = _quality_batch(owner, 1, user) + runs = [] + for index in range(100): + run = ShippingOrderExtractionRun( + run_no=f'SNER-RUN-GATE-{index:03d}', user_id=user.id, owner_agent_id=owner.id, + conversation_id=f'run-gate-{index}', schema_version_id=batch.schema_version_id, + input_snapshot_hash=f'{index + 6000:064x}'[-64:], input_snapshot_json={}, + idempotency_key=f'{index + 7000:064x}'[-64:], status='completed', phase='completed', + provider_config_json={'auto_create_enabled': False}, + ) + db.session.add(run) + runs.append(run) + db.session.flush() + _add_agreed_samples(batch, runs, business, technical) + batch.status = 'ready' + db.session.flush() + approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id) + approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id) + binding = Agent.query.filter_by(exposure_mode='internal').first() + save_runtime_binding( + owner_agent_id=owner.id, capability_code='shipping.order_extraction', + provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id, + config={'auto_create_enabled': True}, + ) + + listed = list_approved_quality_batches(owner_agent_id=owner.id) + run, reused = create_order_extraction_run( + user=user, agent_id=owner.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + + assert reused is False + assert [item['id'] for item in listed] == [batch.id] + assert run.quality_batch_id == batch.id + assert run.provider_config_json['auto_create_enabled'] is True + + db.session.commit() + batch.threshold_version = 'obsolete-threshold' + db.session.commit() + job = claim_next_job( + domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], + worker_id='quality-gate-worker', + ) + run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id}) + + db.session.refresh(run) + assert run.status == 'failed' + assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED' + + +def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client): + """质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。""" + with app.app_context(): + user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-API') + user.role = 'admin' + db.session.flush() + token = issue_local_access_token(user) + db.session.commit() + owner_id = owner.id + admin_username = user.username + + forbidden = client.get( + f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}', + headers={'X-Username': 'missing-quality-user', 'X-Role': 'user'}, + ) + auth = {'Authorization': f'Bearer {token}'} + created = client.post( + '/api/admin/shipping-notice/order-extraction-quality-batches', + json={'owner_agent_id': owner_id, 'schema_version_id': 1}, + headers=auth, + ) + listed = client.get( + f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}', + headers=auth, + ) + + assert forbidden.status_code in {401, 403} + assert created.status_code == 201 + created_data = parse_api_data(created.get_json()) + assert created_data['status'] == 'collecting' + assert listed.status_code == 200 + assert parse_api_data(listed.get_json()) == [] + serialized = str(created.get_json()).lower() + assert all(key not in serialized for key in ('document', 'quote', 'orders', 'evidence_ref', 'cell_id', 'labels')) diff --git a/backend/tests/test_shipping_order_extraction_quality_migration.py b/backend/tests/test_shipping_order_extraction_quality_migration.py new file mode 100644 index 00000000..66ee0631 --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_quality_migration.py @@ -0,0 +1,51 @@ +""" +backend/tests/test_shipping_order_extraction_quality_migration.py + +用途:验证 L7 质量批次/标签和 Runtime Binding 引用迁移可完整往返。 +依赖:Alembic Operations、SQLite 内存数据库、a71f8091a2b7 迁移。 +逻辑:构造最小父表,升级检查表/列/索引,降级确认完全移除。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_order_extraction_quality_migration_round_trip(monkeypatch): + """质量表和 Binding 外键必须可独立升级、写入并完整降级。""" + migration = importlib.import_module( + 'migrations.versions.a71f8091a2b7_add_order_extraction_quality_gate', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'): + sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'agent_runtime_bindings', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('owner_agent_id', sa.Integer()), + ) + metadata.create_all(engine) + with engine.begin() as connection: + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + inspector = sa.inspect(connection) + assert 'shipping_order_extraction_quality_batches' in inspector.get_table_names() + assert 'shipping_order_extraction_quality_labels' in inspector.get_table_names() + assert 'quality_batch_id' in { + item['name'] for item in inspector.get_columns('agent_runtime_bindings') + } + + migration.downgrade() + inspector = sa.inspect(connection) + assert 'shipping_order_extraction_quality_batches' not in inspector.get_table_names() + assert 'shipping_order_extraction_quality_labels' not in inspector.get_table_names() + assert 'quality_batch_id' not in { + item['name'] for item in inspector.get_columns('agent_runtime_bindings') + } diff --git a/backend/tests/test_shipping_order_extraction_run_quality_migration.py b/backend/tests/test_shipping_order_extraction_run_quality_migration.py new file mode 100644 index 00000000..ec2e4722 --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_run_quality_migration.py @@ -0,0 +1,87 @@ +""" +backend/tests/test_shipping_order_extraction_run_quality_migration.py + +用途:验证订单抽取 Run 冻结质量批次引用的迁移可完整往返。 +依赖:Alembic Operations、SQLite 内存数据库、a72f8091a2b8 迁移。 +逻辑:构造最小父表,升级检查外键列与索引,降级确认引用被移除。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_order_extraction_run_quality_migration_round_trip(monkeypatch): + """Run 质量批次外键必须可独立升级、写入并完整降级。""" + migration = importlib.import_module( + 'migrations.versions.a72f8091a2b8_freeze_quality_batch_on_order_extraction_run', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'shipping_order_extraction_quality_batches', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + sa.Table( + 'shipping_order_extraction_runs', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + metadata.create_all(engine) + with engine.begin() as connection: + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + inspector = sa.inspect(connection) + assert 'quality_batch_id' in { + item['name'] for item in inspector.get_columns('shipping_order_extraction_runs') + } + assert 'ix_shipping_order_extraction_runs_quality_batch' in { + item['name'] for item in inspector.get_indexes('shipping_order_extraction_runs') + } + + migration.downgrade() + inspector = sa.inspect(connection) + assert 'quality_batch_id' not in { + item['name'] for item in inspector.get_columns('shipping_order_extraction_runs') + } + + +def test_quality_binding_migration_round_trip(monkeypatch): + """Binding 与 Run 的质量批次引用必须一起升级和完整降级。""" + migration = importlib.import_module( + 'migrations.versions.a77f8091a2c3_add_order_extraction_quality_binding', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'shipping_order_extraction_quality_batches', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + ) + for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): + sa.Table(table_name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) + metadata.create_all(engine) + with engine.begin() as connection: + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + inspector = sa.inspect(connection) + for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): + assert 'quality_batch_id' in { + item['name'] for item in inspector.get_columns(table_name) + } + assert f'ix_{table_name}_quality_batch_id' in { + item['name'] for item in inspector.get_indexes(table_name) + } + + migration.downgrade() + inspector = sa.inspect(connection) + for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'): + assert 'quality_batch_id' not in { + item['name'] for item in inspector.get_columns(table_name) + } diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index c9075ad5..a590b876 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -24,12 +24,15 @@ from app.models import ( FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingNoticeCandidate, Job, ShippingOrderExtraction, + ShippingOrderFieldObservation, ShippingOrderExtractionDiagnosticAudit, ShippingOrderExtractionPlan, ShippingOrderExtractionRun, ShippingOrderExtractionUnit, + ShippingOrderDocumentProfile, ShippingOrderSchema, ShippingOrderSchemaVersion, User, @@ -37,7 +40,9 @@ from app.models import ( from app.services.shipping_notice.order_extraction_run_service import ( create_order_extraction_run, mark_order_extraction_run_seen, + reparse_order_extraction_run, retry_order_extraction_run, + serialize_order_extraction_message_state, serialize_order_extraction_run, transition_order_extraction_run, ) @@ -166,6 +171,7 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app): assert intake.order_extraction_status == 'extracting' assert run.input_snapshot_json['schema']['checksum'] == 'a' * 64 assert run.input_snapshot_json['schema']['extraction_contract']['fields'][0]['field_id'] == 'qty-id' + assert run.input_snapshot_json['snapshot_version'] == 3 assert run.input_snapshot_json['intakes'][0]['documents'][0]['document_id'] == document.id assert run.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'] == 'PO 451883815A QTY 30 EA' # 确定性上下文保留在HXOPS冻结快照;Workflow编译时才从documents强制剔除。 @@ -175,6 +181,7 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app): plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one() assert plan.plan_version == 'shipping_order_extraction.plan.v1' assert len(plan.plan_version) == 33 + assert plan.input_snapshot_hash == run.input_snapshot_hash assert plan.status == 'planned' assert plan.unit_count == 1 @@ -199,6 +206,102 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app): assert ShippingOrderExtractionUnit.query.count() == 1 +def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app): + """Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。""" + from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate + from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot + from app.services.shipping_notice.order_extraction_workflow import build_order_extraction_workflow_inputs + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='B') + document.content_hash = 'b' * 64 + schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + schema.definition_json = {'fields': [{ + 'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', + 'value_type': 'decimal', 'enabled': True, 'required': True, + 'aliases': ['Qty'], 'normalizer_key': 'decimal', + 'validator_keys': ['positive_decimal'], + }]} + layout = build_html_layout_candidate( + document_id=document.id, content_hash=document.content_hash, + tables=['
    Qty
    30
    '], + ) + record_inline_layout_snapshot(document, { + 'snapshot_version': 'shipping_document_table_snapshot.v1', + 'provider': 'eml-html-dom', 'backend': 'html', 'status': 'needs_review', + 'tables': [], 'layout_candidate': layout.model_dump(mode='json'), 'issues': [], + }) + db.session.commit() + + run, _reused = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + frozen_document = run.input_snapshot_json['intakes'][0]['documents'][0] + candidates = frozen_document['layout_schema_candidates'] + assert run.input_snapshot_json['snapshot_version'] == 3 + assert candidates[0]['mapping_status'] == 'candidate' + assert candidates[0]['rows'][0]['fields'][0]['cell_id'] + assert 'layout_table_not_accepted' in candidates[0]['issues'] + + manifest = build_order_extraction_workflow_inputs( + run, unit=run.extraction_plan.units[0], + )['execution_manifest'] + assert 'layout_schema_candidates' not in manifest + assert 'layout_candidate' not in manifest + + +def test_create_run_freezes_published_order_document_profile_definition(app): + """Run 必须复制完整 published Profile;创建后修改数据库行不得污染已排队快照。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='PROFILE') + schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + profile = ShippingOrderDocumentProfile( + profile_code='PO_312207', + display_name='PO template', + version=1, + status='published', + schema_version_id=schema.id, + structure_fingerprint='b' * 64, + definition_json={ + 'contract_version': 'shipping_order_document_profile.v1', + 'structure_fingerprint': 'b' * 64, + 'header_row_index': 0, + 'data_start_row_index': 1, + 'row_structure': 'preserved', + 'drop_zero_qty': True, + 'column_rules': [], + }, + checksum='c' * 64, + published_at=datetime.utcnow(), + ) + db.session.add(profile) + db.session.commit() + + run, reused = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + db.session.commit() + + assert reused is False + frozen = run.input_snapshot_json['order_document_profiles'] + assert frozen == [{ + 'profile_id': profile.id, + 'profile_code': 'PO_312207', + 'version': 1, + 'checksum': 'c' * 64, + 'schema_version_id': schema.id, + 'structure_fingerprint': 'b' * 64, + 'definition': profile.definition_json, + }] + profile.definition_json = {**profile.definition_json, 'drop_zero_qty': False} + db.session.commit() + assert run.input_snapshot_json['order_document_profiles'][0]['definition']['drop_zero_qty'] is True + + def test_run_plan_creates_email_relation_and_attachment_units_in_frozen_order(app): """邮件正文和附件必须成为彼此隔离、顺序稳定的计划单元。""" with app.app_context(): @@ -580,6 +683,30 @@ def test_run_progress_health_is_computed_server_side(app): assert serialize_order_extraction_run(run)['progress']['health'] == 'normal' +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(): + user, agent, session, intake, _document = _seed_run_input(suffix='USER-ERROR-REDACTION') + 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='running') + transition_order_extraction_run( + run, + target_status='failed', + error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED', + error_message='Provider stack trace contains a confidential document fragment', + ) + + payload = serialize_order_extraction_run(run) + assert payload['error'] == {'code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED'} + assert 'confidential document fragment' not in str(payload) + + message_state = serialize_order_extraction_message_state(run) + assert message_state['message'] == '' + assert 'confidential document fragment' not in str(message_state) + + def test_terminal_run_attention_is_new_only_seen_idempotently_and_resets_on_retry(app): """终态才生成提醒;确认幂等,失败重试清除旧周期并为下一次终态重新生成提醒。""" with app.app_context(): @@ -813,7 +940,8 @@ def test_terminal_transition_updates_persisted_chat_state(app): db.session.refresh(log) assert log.payload['shipping_order_extraction_state']['status'] == 'failed' assert log.payload['shipping_order_extraction_state']['terminal'] is True - assert log.payload['shipping_order_extraction_state']['message'] == 'failed once' + # The persisted card is user-visible on history replay, so it must not retain worker text. + assert log.payload['shipping_order_extraction_state']['message'] == '' def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client): @@ -858,7 +986,8 @@ def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, clie state = response.get_json()[-1]['payload']['shipping_order_extraction_state'] assert state['status'] == 'failed' assert state['terminal'] is True - assert state['message'] == 'failed before card persisted' + assert state['message'] == '' + assert 'failed before card persisted' not in str(response.get_json()) def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(app, client): @@ -947,6 +1076,70 @@ def test_failed_run_retry_api_returns_queued_run(app, client): assert payload['run']['phase'] == 'manual_retry_queued' +def test_terminal_run_reparse_api_creates_versioned_run_and_hides_cross_user(app, client): + """工作台重新识别 API 只能创建本人终态 Run 的新版本,重复请求复用活跃版本。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-API') + source, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(source, target_status='running') + transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + other = User(username='reparse-api-other', email='reparse-api-other@example.com', password_hash='x') + db.session.add(other) + db.session.commit() + token = issue_local_access_token(user) + other_token = issue_local_access_token(other) + run_no = source.run_no + + response = client.post( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse', + json={'reason': 'field_mapping_error', 'comment': 'column shifted'}, + headers={'Authorization': f'Bearer {token}'}, + ) + assert response.status_code == 202 + payload = response.get_json()['data'] + assert payload['reused'] is False + assert payload['run']['reparse']['source_run_no'] == run_no + replay = client.post( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse', + json={'reason': 'field_mapping_error'}, headers={'Authorization': f'Bearer {token}'}, + ) + assert replay.status_code == 202 + assert replay.get_json()['data']['reused'] is True + hidden = client.post( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse', + json={'reason': 'other'}, headers={'Authorization': f'Bearer {other_token}'}, + ) + assert hidden.status_code == 404 + + +def test_reparse_api_requires_valid_reason_and_json_object(app, client): + """API 不接收自由原因或非对象请求体,避免审计分类失真。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-API-INVALID') + 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='running') + transition_order_extraction_run(run, target_status='failed', error_message='failed') + db.session.commit() + token = issue_local_access_token(user) + run_no = run.run_no + invalid = client.post( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse', + json={'reason': 'free text'}, headers={'Authorization': f'Bearer {token}'}, + ) + assert invalid.status_code == 400 + assert invalid.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID' + malformed = client.post( + f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse', + json=[], headers={'Authorization': f'Bearer {token}'}, + ) + assert malformed.status_code == 400 + + def test_run_api_rejects_non_object_json(app, client): """请求体为 JSON 数组时应返回标准 400,而不是调用 `.get` 产生 500。""" with app.app_context(): @@ -1090,6 +1283,146 @@ def test_terminal_run_releases_intake_occupancy(app): assert replacement.id != run.id +def test_reparse_creates_new_run_with_lineage_and_current_snapshot(app): + """重新识别必须创建新 Run、冻结当前发布配置,并保存来源谱系和原因。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE') + source, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(source, target_status='running') + transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + db.session.commit() + + replacement, reused = reparse_order_extraction_run( + user_id=user.id, run_no=source.run_no, reason='field_mapping_error', comment='column shifted', + ) + db.session.commit() + + assert reused is False + assert replacement.id != source.id + assert replacement.reparse_of_run_id == source.id + assert replacement.reparse_reason == 'field_mapping_error' + assert replacement.reparse_comment == 'column shifted' + assert source.superseded_by_run_id == replacement.id + assert source.superseded_at is not None + assert replacement.provider_result_json is None + serialized = serialize_order_extraction_run(replacement) + assert serialized['reparse']['difference_summary'] == { + 'schema_changed': False, 'profile_changed': False, 'layout_changed': False, + } + assert 'root text' not in str(serialized).lower() + replay, replayed = reparse_order_extraction_run( + user_id=user.id, run_no=source.run_no, reason='field_mapping_error', + ) + assert replayed is True + assert replay.id == replacement.id + + +def test_reparse_freezes_current_document_schema_and_layout_without_reprocessing_layout(app, monkeypatch): + """重新识别重新冻结当前规则/布局快照,但不得在用户链路直接启动 MinerU/OpenCV。""" + from app.services.shipping_notice.document_layout import lifecycle + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='REPARSE-SNAPSHOT') + source, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(source, target_status='running') + transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + document.extracted_text = 'PO 451883815 SNAPSHOT QTY 42 EA' + schema.definition_json = {**schema.definition_json, 'reparse_marker': 'current-published-rule'} + db.session.commit() + monkeypatch.setattr( + lifecycle, 'schedule_document_layouts', + lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError('user reparse must not schedule layout')), + ) + + replacement, _ = reparse_order_extraction_run( + user_id=user.id, run_no=source.run_no, reason='rule_updated', + ) + + assert replacement.input_snapshot_hash != source.input_snapshot_hash + assert replacement.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'].endswith('42 EA') + assert replacement.input_snapshot_json['schema']['definition']['reparse_marker'] == 'current-published-rule' + assert replacement.provider_result_json is None + + +def test_reparse_rejects_non_terminal_run_and_invalid_reason(app): + """运行中 Run 与未受控原因不得创建新版本,避免并发耗费和审计失真。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-INVALID') + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + with pytest.raises(ConflictError) as active: + reparse_order_extraction_run(user_id=user.id, run_no=run.run_no, reason='other') + assert active.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE' + transition_order_extraction_run(run, target_status='running') + transition_order_extraction_run(run, target_status='failed', error_message='failed') + with pytest.raises(ValidationError) as reason: + reparse_order_extraction_run(user_id=user.id, run_no=run.run_no, reason='free text') + assert reason.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID' + + +def test_failed_reparse_restores_source_candidate_version(app): + """新版运行期间旧候选必须只读;新版失败后只恢复来源版本的可审核资格。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='REPARSE-RESTORE') + source, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], + ) + transition_order_extraction_run(source, target_status='running') + transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1}) + transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1}) + candidate = ShippingNoticeCandidate( + candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id, + candidate_key='restore-version', order_extraction_run_id=source.id, + selected=True, is_current_version=True, validation_status='ready', + ) + db.session.add(candidate) + db.session.commit() + + replacement, _ = reparse_order_extraction_run( + user_id=user.id, run_no=source.run_no, reason='rule_updated', + ) + db.session.flush() + assert candidate.is_current_version is False + assert candidate.selected is False + assert candidate.selected_before_superseded is True + transition_order_extraction_run(replacement, target_status='running') + transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable') + db.session.flush() + + assert candidate.is_current_version is True + assert candidate.selected is True + assert candidate.selected_before_superseded is None + assert source.superseded_by_run_id is None + + +def test_only_current_version_candidate_can_be_consumed(app): + """旧版本 Candidate 即使被直接提交,也必须被建单入口拒绝。""" + from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates + + with app.app_context(): + user, _agent, _session, intake, document = _seed_run_input(suffix='SUPERSEDED') + candidate = ShippingNoticeCandidate( + candidate_no='SNC-SUPERSEDED', intake_id=intake.id, primary_document_id=document.id, + candidate_key='old-version', selected=True, is_current_version=False, validation_status='ready', + ) + db.session.add(candidate) + db.session.commit() + with pytest.raises(ValidationError) as caught: + create_shipping_batch_from_candidates( + user_id=user.id, intake_nos=[intake.intake_no], candidate_nos=[candidate.candidate_no], + create_idempotency_key='test-current-version-gate', conversation_id=None, + ) + assert caught.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_FOUND' + + def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app): """管理员健康汇总应识别积压/失败并只返回安全运行元数据。""" from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health @@ -1181,6 +1514,34 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap job = db.session.get(Job, run.current_job_id) job.error_message = 'secret job error' job.payload_json = {'documents': 'secret document body'} + extraction = ShippingOrderExtraction( + run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id, + input_snapshot_hash='d' * 64, status='needs_review', + validation_result_json={ + 'blocked_fields': ['qty'], + 'deterministic_table_issues': [{ + 'reason': 'layout_table_needs_review', 'document_id': _document.id, + 'field_codes': ['qty'], 'cell_id': 'must-not-leak-cell', + }], + }, + ) + db.session.add(extraction) + db.session.flush() + db.session.add_all([ + ShippingOrderFieldObservation( + extraction_id=extraction.id, field_id='qty-id', source_type='attachment_table', + extractor='layout_schema_mapping', raw_value_json=30, normalized_value_json=30, + evidence_quote='must-not-leak-quote', evidence_ref='layout:secret-cell', + evidence_metadata_json={'kind': 'layout_cell', 'cell_id': 'must-not-leak-cell'}, + confidence='1.0000', evidence_verified=True, + ), + ShippingOrderFieldObservation( + extraction_id=extraction.id, field_id='qty-id', source_type='attachment_text', + extractor='dify_dynamic_schema', raw_value_json=30, normalized_value_json=30, + evidence_quote='must-not-leak-text', evidence_ref=None, + confidence='0.9000', evidence_verified=True, + ), + ]) job_id = job.id admin = User(username='diagnostic-admin', email='diagnostic-admin@example.com', role='admin', password_hash='x') normal = User(username='diagnostic-normal', email='diagnostic-normal@example.com', role='user', password_hash='x') @@ -1206,6 +1567,12 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap payload = detail.get_json()['data'] assert payload['run']['error_code'] == 'UPSTREAM.TIMEOUT' assert payload['job_attempts'][0]['job_id'] == job_id + assert payload['evidence_gate'] == { + 'accepted_observation_count': 2, + 'traceable_observation_count': 1, + 'traceable_rate': 0.5, + 'issue_counts': {'layout_table_needs_review': 1}, + } assert str(payload).lower().count('secret') == 0 with app.app_context(): assert ShippingOrderExtractionDiagnosticAudit.query.filter_by(admin_user_id=admin.id).count() == 2 diff --git a/backend/tests/test_shipping_order_layout_evidence_migration.py b/backend/tests/test_shipping_order_layout_evidence_migration.py new file mode 100644 index 00000000..cbb74b42 --- /dev/null +++ b/backend/tests/test_shipping_order_layout_evidence_migration.py @@ -0,0 +1,54 @@ +""" +backend/tests/test_shipping_order_layout_evidence_migration.py + +用途:验证 L6 Observation 版面证据迁移可独立升级和降级。 +依赖:Alembic Operations、SQLite 内存库、a70f8091a2b6 迁移。 +逻辑:构造上一 revision 最小 Observation 表,检查新增列及无损降级。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def test_order_layout_evidence_migration_round_trip(monkeypatch): + """新增列必须可写结构化证据,降级后旧 Observation 数据仍保留。""" + migration = importlib.import_module( + 'migrations.versions.a70f8091a2b6_add_order_observation_layout_evidence', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + observations = sa.Table( + 'shipping_order_field_observations', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('field_id', sa.String(36), nullable=False), + sa.Column('normalized_value_json', sa.JSON()), + ) + metadata.create_all(engine) + + with engine.begin() as connection: + connection.execute(observations.insert().values( + id=1, field_id='qty-id', normalized_value_json=30, + )) + operations = Operations(MigrationContext.configure(connection)) + monkeypatch.setattr(migration, 'op', operations) + + migration.upgrade() + columns = {item['name'] for item in sa.inspect(connection).get_columns(observations.name)} + assert {'evidence_ref', 'evidence_metadata_json'} <= columns + connection.execute(sa.text( + "UPDATE shipping_order_field_observations " + "SET evidence_ref = :ref, evidence_metadata_json = :metadata WHERE id = 1", + ), {'ref': 'layout:1:p1:t1:c1', 'metadata': '{"page_no": 1}'}) + + migration.downgrade() + columns = {item['name'] for item in sa.inspect(connection).get_columns(observations.name)} + assert 'evidence_ref' not in columns + assert 'evidence_metadata_json' not in columns + assert connection.execute(sa.text( + 'SELECT field_id FROM shipping_order_field_observations WHERE id = 1', + )).scalar_one() == 'qty-id' diff --git a/backend/tests/test_shipping_order_schema_policy_repair_migration.py b/backend/tests/test_shipping_order_schema_policy_repair_migration.py new file mode 100644 index 00000000..f200c874 --- /dev/null +++ b/backend/tests/test_shipping_order_schema_policy_repair_migration.py @@ -0,0 +1,93 @@ +""" +backend/tests/test_shipping_order_schema_policy_repair_migration.py + +用途:验证订单 Schema 自动建单策略列的结构漂移修复迁移。 +依赖:Alembic Operations、SQLite 内存数据库、a76f8091a2c2 迁移。 +逻辑:覆盖缺列升级、已有列幂等升级和降级,确保不同环境均能安全推进。 +""" + +from __future__ import annotations + +import importlib + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _columns(connection) -> set[str]: + """ + 返回测试库订单 Schema 表的列集合。 + + Args: + connection: 当前 SQLite 迁移连接。 + + Returns: + set[str]: 表中实际存在的列名。 + """ + return { + item['name'] for item in sa.inspect(connection).get_columns('shipping_order_schemas') + } + + +def test_order_schema_policy_repair_migration_round_trip(monkeypatch): + """缺列环境升级后应补列,重复升级不报错,降级后应移除。""" + migration = importlib.import_module( + 'migrations.versions.a76f8091a2c2_repair_order_schema_auto_creation_policy', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'shipping_order_schemas', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_code', sa.String(64), nullable=False), + ) + metadata.create_all(engine) + + with engine.begin() as connection: + monkeypatch.setattr( + migration, 'op', Operations(MigrationContext.configure(connection)), + ) + + migration.upgrade() + migration.upgrade() + assert 'auto_creation_policy_json' in _columns(connection) + + connection.execute(sa.text( + "INSERT INTO shipping_order_schemas (id, schema_code) VALUES (1, 'SHIPPING_ORDER')", + )) + stored = connection.execute(sa.text( + 'SELECT auto_creation_policy_json FROM shipping_order_schemas WHERE id = 1', + )).scalar_one() + assert stored in ({}, '{}') + + migration.downgrade() + migration.downgrade() + assert 'auto_creation_policy_json' not in _columns(connection) + + +def test_order_schema_policy_repair_accepts_existing_column(monkeypatch): + """已正确包含目标列的环境执行升级时不得重复添加或改变现有数据。""" + migration = importlib.import_module( + 'migrations.versions.a76f8091a2c2_repair_order_schema_auto_creation_policy', + ) + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + table = sa.Table( + 'shipping_order_schemas', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('auto_creation_policy_json', sa.JSON(), nullable=False), + ) + metadata.create_all(engine) + + with engine.begin() as connection: + connection.execute(table.insert().values(id=1, auto_creation_policy_json={'enabled': True})) + monkeypatch.setattr( + migration, 'op', Operations(MigrationContext.configure(connection)), + ) + + migration.upgrade() + + assert connection.execute(sa.select(table.c.auto_creation_policy_json)).scalar_one() == { + 'enabled': True, + } diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py index 02cbbd58..f2aaba94 100644 --- a/backend/tests/test_shipping_order_schema_runtime.py +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -63,13 +63,36 @@ def _config(field_id: str, name: str, *, value_type: str) -> dict: def _save_and_publish(draft: dict, fields: list[dict]) -> dict: """按乐观锁契约保存并发布运行时测试使用的 Schema。""" saved = service.save_draft(draft['id'], { - 'fields': fields, 'expected_lock_version': draft['lock_version'], + 'fields': fields, + 'expected_lock_version': draft['lock_version'], }) return service.publish( draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], ) +def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): + """自动建单开关独立于版本;每个关键字段只保存自身的最低置信度。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + part_config = _config(part['id'], '内部料号', value_type='string') + part_config.update({'auto_create_key_field': True, 'minimum_confidence': 0.95}) + qty_config = _config(qty['id'], '数量', value_type='decimal') + qty_config.update({'auto_create_key_field': True, 'minimum_confidence': 0.90}) + + saved = service.save_draft(draft['id'], { + 'fields': [part_config, qty_config], 'expected_lock_version': draft['lock_version'], + }) + by_code = {item['field_code']: item for item in saved['definition']['fields']} + assert by_code['part_number']['minimum_confidence'] == 0.95 + assert by_code['qty']['minimum_confidence'] == 0.90 + assert service.get_auto_creation_policy() == {'enabled': False} + assert service.save_auto_creation_policy({'enabled': True}, actor_id=None) == {'enabled': True} + + def test_schema_save_rejects_normalized_table_alias_collision(app): """草稿保存阶段即应拒绝不同字段占用同一标准化表头,避免歧义进入发布版本。""" with app.app_context(): @@ -92,7 +115,7 @@ def test_schema_save_rejects_normalized_table_alias_collision(app): def test_retired_run_schema_keeps_its_frozen_table_aliases(app): - """新版本改动别名后,锁定旧版本的 Run 仍必须按旧 definition 解析后端表格。""" + """旧别名仍可识别表格语义,但没有冻结 cell 证据时不得自动补字段。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) @@ -137,9 +160,13 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app): actor_id=actor_id, schema_version_id=first['id'], ) - assert result['lines'][0]['part_number'] == 'PART-FROZEN' assert result['lines'][0]['qty'] == '4' - assert result['blocked_fields'] == [] + assert 'part_number' in result['blocked_fields'] + assert result['extraction'].validation_result_json['deterministic_table_issues'] == [{ + 'document_id': int(documents[1].id), + 'reason': 'plain_text_table_has_no_cell_evidence', + 'field_codes': ['part_number', 'qty'], + }] def test_duplicate_table_columns_force_dynamic_run_review(app): @@ -178,11 +205,107 @@ def test_duplicate_table_columns_force_dynamic_run_review(app): assert result['extraction'].status == 'needs_review' assert result['extraction'].validation_result_json['deterministic_table_issues'][0] == { 'document_id': int(documents[1].id), - 'reason': 'ambiguous_table_headers', + 'reason': 'plain_text_table_has_no_cell_evidence', 'field_codes': ['part_number'], } +def test_accepted_layout_cell_persists_traceable_backend_observation(app): + """accepted L4 cell 可补模型缺失字段,且 Observation 必须保存完整稳定证据引用。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [ + _config(part['id'], '内部料号', value_type='string'), + _config(qty['id'], '数量', value_type='decimal'), + ]) + intake_id, documents, actor_id = _seed_documents() + pdf = documents[1] + candidates = {int(pdf.id): [{ + 'page_no': 2, 'table_id': 'table-main', 'mapping_status': 'accepted', 'issues': [], + 'rows': [{'row_index': 3, 'role': 'data', 'fields': [ + { + 'field_id': part['id'], 'value': 'PART-LAYOUT', 'quote': 'PART-LAYOUT', + 'column_index': 1, 'cell_id': 'cell-part', + 'evidence_ref': f'layout:{pdf.id}:p2:table-main:cell-part', + }, + { + 'field_id': qty['id'], 'value': 4, 'quote': '4', + 'column_index': 2, 'cell_id': 'cell-qty', + 'evidence_ref': f'layout:{pdf.id}:p2:table-main:cell-qty', + }, + ]}], + }]} + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], 'lines': [{'fields': [{ + 'field_id': part['id'], 'observations': [{ + 'value': 'PART-LAYOUT', 'document_id': pdf.id, + 'quote': 'Part Number PART-100', 'confidence': 0.9, + }], + }]}], + }, + intake_id=intake_id, snapshot_hash='1' * 64, documents=documents, actor_id=actor_id, + layout_candidates_by_document=candidates, + ) + + assert result['blocked_fields'] == [] + assert result['lines'] == [{'part_number': 'PART-LAYOUT', 'qty': '4'}] + observation = next( + item for item in result['extraction'].observations + if item.field_id == qty['id'] and item.extractor == 'layout_schema_mapping' + ) + assert observation.evidence_verified is True + assert observation.evidence_ref == f'layout:{pdf.id}:p2:table-main:cell-qty' + assert observation.evidence_metadata_json == { + 'kind': 'layout_cell', 'page_no': 2, 'table_id': 'table-main', + 'row_index': 3, 'column_index': 2, 'cell_id': 'cell-qty', + } + + +def test_layout_row_cannot_be_associated_by_qty_across_documents(app): + """相同 Qty 不是业务身份,另一附件的 accepted 行不得据此补入当前订单。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [ + _config(part['id'], '内部料号', value_type='string'), + _config(qty['id'], '数量', value_type='decimal'), + ]) + intake_id, documents, actor_id = _seed_documents() + body, pdf = documents + candidates = {int(pdf.id): [{ + 'page_no': 1, 'table_id': 'other-table', 'mapping_status': 'accepted', 'issues': [], + 'rows': [{'row_index': 1, 'role': 'data', 'fields': [ + {'field_id': part['id'], 'value': 'WRONG-PART', 'quote': 'WRONG-PART', 'column_index': 0, + 'cell_id': 'wrong-part', 'evidence_ref': f'layout:{pdf.id}:p1:other-table:wrong-part'}, + {'field_id': qty['id'], 'value': 10, 'quote': '10', 'column_index': 1, + 'cell_id': 'wrong-qty', 'evidence_ref': f'layout:{pdf.id}:p1:other-table:wrong-qty'}, + ]}], + }]} + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], 'lines': [{'fields': [{ + 'field_id': qty['id'], 'observations': [{ + 'value': 10, 'document_id': body.id, 'quote': 'quantity 10', 'confidence': 0.9, + }], + }]}], + }, + intake_id=intake_id, snapshot_hash='2' * 64, documents=documents, actor_id=actor_id, + layout_candidates_by_document=candidates, + ) + + assert 'part_number' not in result['lines'][0] + assert 'part_number' in result['blocked_fields'] + assert not any(item.extractor == 'layout_schema_mapping' for item in result['extraction'].observations) + + def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]: """创建同一 Intake 下的邮件正文和 PDF Document,供跨文档证据验证。""" user = User(username='dynamic-runtime', email='dynamic-runtime@example.com', password_hash='x') @@ -615,3 +738,69 @@ def test_dynamic_schema_accepts_equivalent_number_and_date_evidence_formats(app) # 断言格式化差异不会阻断三类字段,但每条证据仍必须引用当前文档中的原文片段。 assert result['blocked_fields'] == [] assert result['lines'] == [{'qty': '30', 'amount': '28252.8', 'required_date': '2026-06-29'}] + + +def test_dynamic_schema_verifies_dify_quote_against_frozen_mineru_text(app): + """Dify 使用冻结 MinerU 文本时,旧 PDF 文本不含 quote 也必须接受同源料号和数量证据。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [ + _config(part['id'], '内部料号', value_type='string'), + _config(qty['id'], '数量', value_type='decimal'), + ]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'legacy PDF text without the MinerU table' + mineru_text = 'Vendor Item#\tB3-A08AR11000001\nQuantity\t7' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [ + {'field_id': part['id'], 'observations': [{ + 'value': 'B3-A08AR11000001', 'document_id': document.id, + 'quote': 'Vendor Item#\tB3-A08AR11000001', 'confidence': 0.95, + }]}, + {'field_id': qty['id'], 'observations': [{ + 'value': 7, 'document_id': document.id, 'quote': 'Quantity\t7', 'confidence': 0.99, + }]}, + ]}], + }, + intake_id=intake_id, snapshot_hash='m' * 64, documents=documents, actor_id=actor_id, + frozen_evidence_text_by_document={int(document.id): mineru_text}, + ) + + assert result['blocked_fields'] == [] + assert result['lines'] == [{'part_number': 'B3-A08AR11000001', 'qty': '7'}] + + +def test_dynamic_schema_rejects_quote_absent_from_frozen_and_legacy_text(app): + """冻结 MinerU 文本不是宽松白名单;quote 未出现时仍必须拒绝 Observation。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(part['id'], '内部料号', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'legacy PDF text' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [{'field_id': part['id'], 'observations': [{ + 'value': 'B3-A08AR11000001', 'document_id': document.id, + 'quote': 'Vendor Item#\tB3-A08AR11000001', 'confidence': 0.95, + }]}]}], + }, + intake_id=intake_id, snapshot_hash='n' * 64, documents=documents, actor_id=actor_id, + frozen_evidence_text_by_document={int(document.id): 'different MinerU text'}, + ) + + assert result['blocked_fields'] == ['part_number'] + assert result['lines'] == [{}] diff --git a/backend/tests/test_shipping_task_parsed_projection.py b/backend/tests/test_shipping_task_parsed_projection.py index 336d86b7..b5a3b00c 100644 --- a/backend/tests/test_shipping_task_parsed_projection.py +++ b/backend/tests/test_shipping_task_parsed_projection.py @@ -9,7 +9,18 @@ backend/tests/test_shipping_task_parsed_projection.py from __future__ import annotations from app import db -from app.models import ShippingNoticeCandidate, ShippingTask +from app.models import ( + ShippingNoticeCandidate, + ShippingOrderExtraction, + ShippingOrderField, + ShippingOrderFieldDecision, + ShippingOrderFieldValue, + ShippingOrderLine, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingTask, + User, +) from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief from app.services.shipping_notice.query_service import serialize_task_detail @@ -17,6 +28,27 @@ from app.services.shipping_notice.query_service import serialize_task_detail def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): """Task Detail 必须稳定顶层返回 lines 门禁与来源 Candidate 证据投影。""" with app.app_context(): + user = User(username='parsed-projection-user', email='parsed-projection@example.com', password_hash='x') + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Parsed projection') + db.session.add_all([user, schema]) + db.session.flush() + fields = {} + for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'), ('inventory_source_hint', 'string')): + field = ShippingOrderField(schema_id=schema.id, field_code=code, scope='line', value_type=value_type) + fields[code] = field + db.session.add(field) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + definition_json={'fields': [ + {'field_id': field.id, 'field_code': code, 'scope': 'line'} + for code, field in fields.items() + ]}, + ) + db.session.add(version) + db.session.flush() candidate = ShippingNoticeCandidate( candidate_no='SNC-PARSED-PROJECTION-001', intake_id=1, @@ -38,6 +70,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): task = ShippingTask( task_no='SN-PARSED-PROJECTION-001', + user_id=user.id, source_type='manual', process_status='pending_review', po_number='4510038672', @@ -61,6 +94,28 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): }, ) db.session.add(task) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=task.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + line = ShippingOrderLine(extraction_id=extraction.id, position=0) + db.session.add(line) + db.session.flush() + for code, value in task.lines_json[0].items(): + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id, + decision_status='accepted', resolved_value_json=value, + ) + db.session.add(decision) + db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id, + decision_id=decision.id, value_text=str(value) if code != 'qty' else None, + value_decimal=value if code == 'qty' else None, value_json=value, + )) + task.current_order_extraction_id = extraction.id db.session.commit() detail = serialize_task_detail(task) @@ -236,3 +291,8 @@ def test_candidate_update_persists_inventory_source_hint_round_trip(app): db.session.refresh(candidate) persisted = candidate.structured_result_json['business_summary']['lines'][0] assert persisted['inventory_source_hint'] == 'DBS DUB' + history = candidate.structured_result_json['manual_review_history'] + assert history[-1]['action'] == 'business_summary_edited' + assert history[-1]['actor_user_id'] == int(user.id) + assert history[-1]['before_validation_status'] == 'needs_review' + assert history[-1]['after_summary']['lines'][0]['reservation_id'] == '1000140351' diff --git a/docs/demand.md b/docs/demand.md index 046681c4..ec1f6515 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -113,6 +113,14 @@ - 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。 - 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。 - 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;Run 冻结用户、入口 Agent、会话、Intake/Document 正文和 published Schema,幂等键由服务端快照计算,不依赖浏览器 request ID。 +- 订单附件结构化必须支持版本化订单文档 Profile。Profile 绑定一个不可变订单 Schema 版本,以表头网格精确结构指纹选择固定列规则,并把目标字段冻结为稳定 `field_id + field_code`。已发布 Profile 不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile 与 MinerU 紧凑表格快照,不能只保存当前 Profile ID。 +- 业务管理员必须通过 MinerU 样本表格的结构化页面维护订单文档 Profile:只选择表格、表头/数据行、行结构、Schema 字段和注册解析器,不得编辑 HTML、bbox、JSON、正则、脚本或结构指纹。结构指纹由后端基于持久化样本计算;草稿更新使用乐观锁,同一目标字段不得跨列重复映射;不可变版本可复制为新草稿或退役。 +- MinerU 按显式环境开关固定使用 `pipeline`,由独立布局 Job 在 Intake 持久化 Document 后异步调用,不得阻塞 Intake 预解析。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Intake 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时回退现有 Dify/人工复核,不得伪造确定性字段。 +- 人工单元格真值当前允许延期,不阻塞布局版本/任务生命周期建设;但在真值评测完成前,不得宣称 95% 准确率、把 MinerU/OpenCV/文本对齐候选自动标记为 `accepted`,也不得据此开启错误自动建单风险。 +- 原生 PDF 可使用 PDFium 字符坐标与 MinerU HTML 生成 `shipping_document_layout.v1` 候选;只允许唯一连续文本或“OpenCV 多参数有框网格 + 原生文本全量一致”两条保守路径。候选必须保持 `needs_review`,扫描 PDF 不得由本阶段伪造 OCR 结果。 +- 扫描 PDF 的布局 OCR 必须保留 RapidOCR 原始多边形坐标和置信度,并且只有与严格有框网格及全部非空 cell 文本一致时才能生成 OCR cell 候选。EML HTML table 必须经主动内容/属性白名单清理后按 DOM 行列和跨度生成逻辑布局;原始 HTML 不得进入 Intake 摘要、Dify 或日志。两类结果在人工真值完成前均保持 `needs_review`。 +- 冻结 Schema 映射必须直接消费 layout.v1 的真实 `cell_id/token_ids`,不得从 HTML 再生成第二套证据 ID。表头后置、重复列、零 Qty、类型与安全校验复用同一规则;跨页只接受显式 continuation。needs_review 映射只能冻结为内部 candidate,禁止进入 Dify、自动接受或跳过 Provider。 +- 精确 Profile 命中后,模板语义优先于全局 Schema 别名。例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法映射。只有唯一命中表且每个保留行都具备可信 `part_number + qty` 时,后端才可跳过该附件的 LLM;显式 Qty=0 行删除。Reservation 可由邮件或其他附件补充,最终缺失仍须阻断库存匹配和发货 Excel。 - 阶段 2 创建 Run 时同步创建 `shipping_order_extraction` Job;Worker 按 Run 冻结快照调用 `shipping.order_extraction` 能力绑定的内部 Provider,并把 Dify 成功结果先于 HXOPS 订单落库独立提交,重试不得重复调用 Dify。 - 应用管理必须显式创建 `exposure_mode=internal` 的 Dify Workflow Provider,再由货代 Agent 绑定 `shipping.order_extraction`。业务代码只识别能力编码和数据库外键,禁止写死 App ID、按名称匹配或从环境变量静默回退;Dify 画布由管理员手工配置。 - Run 冻结 Provider App ID、Base URL 与执行参数;二者变更后旧 Run 必须失败并重新发起。API Key 不进入快照,允许在不重建 Run 的情况下安全轮换。 @@ -121,6 +129,7 @@ - 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。 - 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。 - 订单抽取进度由 HXOPS 服务端消费专用 Workflow 的 Dify SSE 节点事件并自动按节点类型归并;用户默认查看当前脱敏阶段、真实运行时长和最近活动,可展开时间线。无需手工修改 Dify Workflow;不展示模型思考、节点输入输出、伪百分比或内部运行标识。浏览器继续使用自适应短轮询,不建立订单抽取浏览器长 SSE。 +- 用户状态卡、Run 查询和历史聊天回放只可显示稳定错误码与通用可操作提示;Worker、Provider 或上游异常正文不得进入用户 API、ChatLog 或前端状态。 - 新上线 Run 的完成、待确认和失败状态应在用户离开会话后形成会话级待查看提示;进入对应会话且终态卡片成功加载后才清除。管理员在货代管理域只读诊断 Run、Job Attempt 和脱敏节点时间线;不提供管理端强制操作。 - Run 失败或取消时 Intake 恢复为可重试失败态;切换会话后的迟到轮询响应不得更新当前页面或重启旧 Run 计时器。 - 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态/阶段/错误码分布、失败率、重试数、积压 Run,以及排队、Provider、HXOPS 落库和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。 @@ -172,7 +181,7 @@ - 库存主匹配键固定为 `(part_number, reservation_id)`;库存 `Supplier Sku` 映射为 `part_number`,`AWS Sku` 仅映射为可选 `aws_part_number`,不得作为默认主匹配料号。 - 本次为无生产数据的破坏性字段升级,不保留旧字段兼容层:规范订单行使用 `shipping-task-line-v2`,内容指纹使用 `shipping-content-v4`;后端、Dify 画布、静态 OpenAPI 与前端必须同批切换。 - Reservation ID 不绑定单一邮件模板:允许 `Reservation ID / COM ID / Reservation Order / PR Number / External reservation ID` 等业务来源;禁止把 `Allocation ID / Parent allocation ID / Commodity group ID` 当作 Reservation ID。 -- 32 位十六进制内部主键和 UUID 不得进入库存匹配;数字型及 `AWS-311 / ORD-3002 / R-1` 等字母型业务编号按通用契约兼容,后续可按客户或来源 profile 收紧。 +- Reservation ID 统一为 5 位或 10 位纯数字;字母型编号、其他长度数字、32 位十六进制内部主键和 UUID 均不得进入订单关联或库存匹配。 - 自动纠错必须具备表头列关系和唯一 SKU/APN/MPN 关联证据;拍平文本或多义匹配不得猜测,必须进入人工复核。 - 后端必须保留原始候选、修正值、原因与证据;任何 blocking 问题不得被 LLM 高置信度或人工“确认”动作绕过。 - 订单持久化:Task 通过 `current_order_extraction_id` 锁定 `ShippingOrderExtraction/Line/Decision/FieldValue` 唯一真相;不保留固定订单表、JSON 快照或兼容回滚。Candidate→既有 Task 仅允许空 FieldValue 安全补齐,双方非空且不同时落字段冲突并阻断库存/匹配/导出;人工改单须带 `expected_order_data_version`。 @@ -545,3 +554,11 @@ - 聚合/非聚合由 `agents.is_aggregate` 显式配置,切回非聚合时清空成员关系。 - 目录 Agent 本身仍配置一套聚合 Dify Chatflow;HXOPS 在发起聊天时向 Dify inputs 注入成员 Agent 元数据。 - 本期不在 HXOPS 后端并行调用多个子 Agent,不合并多个 Dify 回答;多路召回与答案融合由聚合 Chatflow 承担。 +## 2026-07-22 订单抽取唯一 Manifest 与自动建单策略 + +- 订单抽取只保留唯一、可冻结的 `execution_manifest`,不提供输入格式切换或回退。 +- Manifest 仅向模型提供压缩后的结构化字段候选,不传递版面坐标、HTML、token 或内部映射代码;确定性 accepted 字段不可被模型覆盖。 +- 人工真值暂缓期间,版面候选保持 `needs_review`,质量验收与 95% 准确率目标延期,不得自动 accepted、自动建单或对外宣称达标。 +- L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。 +- 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。 +- 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index e72ac231..91f453be 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -347,10 +347,10 @@ WYC26071501 | 操作 | 含义 | |------|------| | **确认** | 解析正确,进入库存环节 | -| **重新解析** | 原文有误或解析不对,请助手重新解析 | +| **按当前规则重新识别** | 原文件不变但字段规则、映射或识别结果有误;系统创建新版结果,旧结果保留查看 | | **驳回** | 本单不再处理,任务结束 | -聊天页下方会出现对应按钮;也可输入「确认」「重新解析」「驳回」等文字。 +聊天页下方会出现对应按钮;也可输入「确认」「重新解析」「驳回」等文字。重新识别期间旧结果不能确认建单;新版失败时系统恢复旧结果。若任务无法追溯原始识别 Run,系统会提示重新上传。 --- @@ -447,7 +447,7 @@ WYC26071501 **Reservation ID 格式说明:** -- 常见为 **8~12 位纯数字**,例如 `1000140351`,也可能是 `AWS-311` 等来源系统业务编号。 +- 必须为 **5 位或 10 位纯数字**,例如 `12345` 或 `1000140351`。 - Excel 中的数字型编号可能被存成浮点格式,系统会自动规范为同一字符串再比对,避免「1000140351」与「1000140351.0」对不上。 - 32 位十六进制内部主键和 UUID 会被拒绝,不参与订单关联、指纹或库存匹配。 @@ -624,7 +624,7 @@ A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是 3. 若原件里不存在:请向客户/上游确认 Reservation ID 的提供规则,在补齐并通过门禁前,系统不会执行库存匹配,避免同一内部料号对应多个预留号时误匹配。 **Q:Reservation ID 必须是数字吗?** -A:不一定。很多来源使用 8~12 位纯数字(如 `1000140351`),也有来源使用 `AWS-311`、`ORD-3002` 等字母型业务编号。系统兼容多模板,但会拒绝 32 位十六进制内部主键、UUID 等明显不是业务预留号的值。 +A:必须。当前业务契约只接受 5 位或 10 位纯数字,例如 `12345` 或 `1000140351`;字母型编号、其他长度数字、32 位十六进制内部主键和 UUID 均会被拒绝。 **Q:单价、金额错了会影响能不能发货吗?** A:不会。库存匹配只看内部料号、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。 diff --git a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md index ee388b47..5e4905ca 100644 --- a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md +++ b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md @@ -2,6 +2,55 @@ > 适用范围:HXOPS 货代订单抽取内部 Workflow。本文是当前唯一有效的 Dify 画布契约。 +## 唯一 Manifest 配置(2026-07-22,优先执行) + +> HXOPS 只发送一种 `execution_manifest`。Dify 必须只接受本手册定义的唯一结构。 + +1. Start 节点继续只保留一个 **String** 输入 `execution_manifest`。 +2. `parse_and_prepare_input` 直接读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`;不得读取其他文档集合、确定性表格内部载荷或任何输入格式分支。 +3. Code 节点不得期待或生成 HTML、bbox、token、cell_id、evidence_ref、field_code。结构化候选字段仅为 `column_index/field_id/value/quote`;表/行同时带 `status/issues`,候选顶层带 `field_policy`。 +4. LLM 对 `field_policy=locked` 的字段必须原样保留稳定 `field_id/value/quote`,只能补充缺失字段;对 `suggested` 候选可结合当前文档短文本判断,但不得把自然语言表头改写为其他 field_id。 +5. `unit.intake_no` 必须写入每个订单 `source_intake_no`;`unit.document_id` 必须写入 `primary_document_id` 及每条 Observation 的 `document_id`。End 仍只输出 String 类型 `orders`,内容必须是 JSON 数组,不得附加 think/XML/Markdown 标签。 +6. 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。 + +人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。不得在 Code 节点自行把候选提升为 accepted,不得据此开启自动建单,也不得宣称达到 95% 准确率。 + +### 单文档证据与跨文档订单的边界(必须遵守) + +一个 Unit 只代表 EML 正文或一份附件,不代表完整订单。EML 通常提供 PO、收货/账款信息、Reservation 或沟通上下文;PDF 通常提供订单行、料号和数量。Dify 必须分别返回当前 Document 能逐字证明的字段,**不得**要求 EML 或任一 PDF 单独具有 PO、所有必填 Header、完整订单行、Reservation 或完整订单才能通过校验。 + +`VALIDATE_AND_NORMALIZE_ORDERS` 的职责仅为 JSON 结构、Schema、当前 Unit 来源、字段类型和明显错位防护;它不做订单完整性、必填字段、跨文档关联、冲突裁决、库存门禁或自动建单判断。HXOPS 在收齐同一 Intake 的全部 Unit 后,才按 PO 或强行身份保守合并、比较所有 Observation,并将无法安全归属或缺少必填信息的结果置为 `needs_review`。因此: + +- 某个字段未找到、类型不正确或语义明显错位时,Code 节点应丢弃该字段的 Observation,保留同一 Unit 的其他有效证据;不得让整份 EML/PDF 失败。 +- 单文档完全没有可证明字段时,LLM 返回 `{"orders":[]}`,属于成功空结果,不是校验失败。 +- 只有 JSON 无法解析、订单/字段结构损坏、Schema/Intake/Document 不一致、Observation 指向其他 Document 等协议或来源越界,才进入失败分支。 +- Dify 不可把没有锚点的 EML 证据猜测性并入某份 PDF;是否能合并、是否能创建订单只能由 HXOPS 后端决定。 + +Reservation 的最终裁决也在 HXOPS:PDF 缺少 `reservation_id` 时,Dify 必须照常返回其可证明的 PO、料号、数量、项次等字段;EML 若有明确 Reservation 也只返回该 Document 自己的 Observation。后端仅在同 Intake、同 PO 下,且邮件/PDF 行可通过**唯一且一致**的 `part_number` 或 `line_no` 关联时,才把合法 Reservation 合并到最终行。重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点时都不得自动补入,必须保留证据并进入 `needs_review`。 + +自动建单策略不是 Dify 变量。它在“货代配置 → 订单字段模板”中维护:一个总开关,以及每个字段自己的关键字段标记和最低置信度;Run 会冻结开关和字段快照。Dify 不得自行创建订单或绕过 HXOPS 的证据、冲突、重复和 Reservation 门禁。 + +## 重新识别的 Dify 配置说明 + +HXOPS 的“按当前规则重新识别”不会调用新的 Dify 节点,也不需要在画布添加循环、重试或版本判断。它创建新的 HXOPS Run,并把当前已发布的 Schema 契约和单文档 manifest 重新发送到已发布 Workflow。管理员只需在修改本手册规定的 Start/Code/LLM/End 节点后发布 Workflow;然后业务用户重新识别即可使用新画布。失败 Run 的“重试”仍复用旧 Run 的冻结 Provider 执行上下文,不能用于验证新 Prompt 或新 Schema。 + +订单识别异步状态卡也无需 Dify 配置:HXOPS 根据既有 Workflow SSE 事件投影用户阶段、运行时长和健康状态。画布不得为状态卡新增节点、变量、错误正文或浏览器 SSE;Provider 的异常正文只保留在 HXOPS 服务端诊断边界,用户卡片仅显示通用提示。 + +### L6 证据门禁补充 + +- Dify 不返回 `evidence_ref`、`cell_id`、bbox 或 token;这些只由 HXOPS 冻结布局和后端裁决生成。 +- `field_policy=locked` 仅表示后端已判定字段不可覆盖,不授权 Code/LLM 将 `suggested` 提升为 locked。 +- 模型 Observation 仍必须提供逐字 `quote`;confidence 只是弱辅助,不能替代 quote 或 layout cell 证据。 +- 纯文本中看似整齐的列不得由 Dify 标记为确定性表格。HXOPS 会以 `plain_text_table_has_no_cell_evidence` 转复核。 + +## L7 正式切换检查表 + +- [ ] 人工单元格真值和真实质量/性能指标全部达到 `technical.md` 阈值。 +- [ ] Dify 已发布本手册定义的唯一画布,Start 仍只有 String `execution_manifest`。 +- [ ] 保持 `auto_create_enabled=false` 完成至少 20 个测试环境真实 Run。 +- [ ] 管理员诊断中证据追溯率、issue code 和失败单元均可解释;无错误合并、错误拆分或错误 Task。 +- [ ] 业务负责人和技术负责人书面批准后才开启自动建单。 + ## 1. 边界与运行模型 HXOPS Worker 每次调用 Workflow 时,只传入一个冻结的抽取单元(Unit):一个 Intake 下的一份邮件正文或一份附件。Dify 只读取该 Unit、按冻结 Schema 提取字段并返回 `orders`;不负责合并附件、创建 Candidate/Task、判重、库存、RPA、Excel 或重试。 @@ -44,7 +93,6 @@ End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错 ```json { - "contract_version": "shipping_order_extraction.unit.v2", "run": {"run_no": "SNER-..."}, "unit": { "unit_id": 123, @@ -55,19 +103,29 @@ End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错 "document_type": "attachment" }, "integrity": {"input_snapshot_hash": "..."}, - "extraction_contract": {"schema_version_id": 14, "checksum": "...", "fields": []}, - "documents": [ + "extraction_contract": {"schema_version_id": 15, "checksum": "...", "fields": []}, + "document": { + "document_id": 789, + "filename": "order.pdf", + "document_type": "attachment", + "extracted_text": "..." + }, + "structured_table_candidates": [ { - "intake_id": 456, - "intake_no": "SNI-...", - "document": {"document_id": 789, "extracted_text": "..."} + "candidate_id": "p1:table-1", + "page_no": 1, + "table_id": "table-1", + "status": "candidate", + "field_policy": "suggested", + "rows": [{"row_index": 2, "role": "data", "fields": [], "issues": []}], + "issues": ["layout_table_not_accepted"] } ], "readonly_hints": [] } ``` -`documents` 必须恰好有一项,实际文档位于 `documents[0].document`。同次调用不存在其他附件或兄弟 Document。 +`document` 是当前 Unit 的唯一文档;`structured_table_candidates` 是可选的紧凑字段候选。两者都不包含兄弟附件、HTML、bbox、token、cell ID、证据内部 ID 或完整布局载荷。 ## 4. Code 节点:parse_and_prepare_input @@ -84,6 +142,7 @@ End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错 | `primary_document_id` | Number | | `schema_contract_json` | String | | `document_json` | String | +| `table_candidates_json` | String | | `readonly_context_json` | String | | `header_field_ids_json` | String | | `line_field_ids_json` | String | @@ -127,39 +186,47 @@ def _as_int(value, name): def main(execution_manifest: str): manifest = _object(_parse_json(execution_manifest, "execution_manifest"), "execution_manifest") - if manifest.get("contract_version") != "shipping_order_extraction.unit.v2": - raise ValueError("unsupported execution_manifest.contract_version") - run = _object(manifest.get("run"), "execution_manifest.run") unit = _object(manifest.get("unit"), "execution_manifest.unit") integrity = _object(manifest.get("integrity"), "execution_manifest.integrity") schema = _object(manifest.get("extraction_contract"), "execution_manifest.extraction_contract") - wrappers = _array(manifest.get("documents"), "execution_manifest.documents") + document = _object(manifest.get("document"), "execution_manifest.document") + table_candidates = _array( + manifest.get("structured_table_candidates", []), + "execution_manifest.structured_table_candidates", + ) readonly_hints = _array(manifest.get("readonly_hints"), "execution_manifest.readonly_hints") - if len(wrappers) != 1: - raise ValueError("unit.v2 requires exactly one document wrapper") - wrapper = _object(wrappers[0], "execution_manifest.documents[0]") - document = _object(wrapper.get("document"), "execution_manifest.documents[0].document") - run_no = str(run.get("run_no") or "").strip() unit_id = _as_int(unit.get("unit_id"), "unit.unit_id") intake_no = str(unit.get("intake_no") or "").strip().upper() document_id = _as_int(unit.get("document_id"), "unit.document_id") - wrapper_intake_no = str(wrapper.get("intake_no") or "").strip().upper() - wrapped_document_id = _as_int(document.get("document_id"), "document.document_id") + manifest_document_id = _as_int(document.get("document_id"), "document.document_id") checksum = str(schema.get("checksum") or "").strip() fields = schema.get("fields") if not run_no or not intake_no or not checksum or not isinstance(fields, list): raise ValueError("manifest is missing required run, unit, or schema values") - if wrapper_intake_no != intake_no: - raise ValueError("documents[0].intake_no must equal unit.intake_no") - if wrapped_document_id != document_id: - raise ValueError("documents[0].document.document_id must equal unit.document_id") + if manifest_document_id != document_id: + raise ValueError("document.document_id must equal unit.document_id") if not str(integrity.get("input_snapshot_hash") or "").strip(): raise ValueError("integrity.input_snapshot_hash is required") + allowed_candidate_keys = { + "candidate_id", "page_no", "table_id", "continuation_of", "status", + "field_policy", "rows", "issues", + } + forbidden_keys = {"html", "bbox", "token", "token_ids", "cell_id", "evidence_ref", "field_code"} + for index, candidate in enumerate(table_candidates): + candidate = _object(candidate, f"structured_table_candidates[{index}]") + if set(candidate) - allowed_candidate_keys: + raise ValueError(f"structured_table_candidates[{index}] has unsupported keys") + if candidate.get("field_policy") not in {"locked", "suggested"}: + raise ValueError(f"structured_table_candidates[{index}].field_policy is invalid") + serialized = json.dumps(candidate, ensure_ascii=False).lower() + if any(f'"{key}"' in serialized for key in forbidden_keys): + raise ValueError(f"structured_table_candidates[{index}] contains forbidden layout data") + header_ids = [] line_ids = [] for index, field in enumerate(fields): @@ -190,7 +257,6 @@ def main(execution_manifest: str): "intake_no": intake_no, "filename": str(document.get("filename") or ""), "document_type": str(document.get("document_type") or unit.get("document_type") or ""), - "classification": str(document.get("classification") or ""), "extracted_text": str(document.get("extracted_text") or ""), } return { @@ -201,6 +267,9 @@ def main(execution_manifest: str): "primary_document_id": document_id, "schema_contract_json": json.dumps(model_schema, ensure_ascii=False, separators=(",", ":")), "document_json": json.dumps(model_document, ensure_ascii=False, separators=(",", ":")), + "table_candidates_json": json.dumps( + table_candidates, ensure_ascii=False, separators=(",", ":") + ), "readonly_context_json": json.dumps(readonly_hints, ensure_ascii=False, separators=(",", ":")), "header_field_ids_json": json.dumps(sorted(set(header_ids)), ensure_ascii=False, separators=(",", ":")), "line_field_ids_json": json.dumps(sorted(set(line_ids)), ensure_ascii=False, separators=(",", ":")), @@ -211,7 +280,7 @@ def main(execution_manifest: str): 建议参数:Temperature `0`,Top P `0.1`,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。 -输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。 +输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`table_candidates_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。 ### System Prompt @@ -222,19 +291,57 @@ def main(execution_manifest: str): 你只能读取当前 document_json。不得假设存在邮件正文、其他附件、兄弟 Document 或外部数据;不得跨文档合并、补全、判重、建单、调用工具、查询数据库或读取外部文件。 +classification 必须根据当前 document_json.extracted_text 独立判断。document_json 不提供、也不得继承任何上游文档分类;不得根据文件名或既有任务状态回填分类。 + 固定来源约束:每一条订单的 source_intake_no 必须逐字等于输入 source_intake_no;primary_document_id 必须逐字等于输入 primary_document_id;每个 Observation.document_id 也必须逐字等于输入 primary_document_id。违反任一约束即为无效输出。 仅可使用 schema_contract_json.fields[] 中 collection_mode=llm_extraction 的 stable field_id。Header 字段仅能使用 header_field_ids_json;明细字段仅能使用 line_field_ids_json。不要用 field_code、显示名称或自然语言字段名代替 field_id。 -字段没有可信逐字证据时,直接省略该字段;不要输出空 observations、null、默认值、猜测值或模型解释。每个返回的 Observation 必须有 value、document_id、quote 和 0 到 1 的 confidence;quote 必须是当前 document_json.extracted_text 中能直接证明 value 的原文片段。 +字段没有可信逐字证据时,直接省略整个字段;不要输出空 observations、null、空字符串、`0` 占位、`not found`/“未找到”占位、猜测值或模型解释。每个返回的 Observation 必须有 value、document_id、quote 和 0 到 1 的 confidence;quote 必须是当前 document_json.extracted_text 中能直接证明 value 的原文片段。不得以 `Unit Price not found`、`项次 not found`、`AWS Sku not found` 等文本充当 quote,也不得在未找到金额/单价时输出数值 `0`。 + +`quote` 必须包含该 value 的逐字值,或仅经过允许的格式化(大小写、千分位、日期 `MM/DD/YYYY -> YYYY-MM-DD`)后可验证为同一值;不得截断、拼写改写或概括原文。例如 `IEC Technologies` 不能输出为 `iecnologies`。表格被拆为多行、字段归属不明时,宁可省略字段,也不得把裸料号、站点文字、项次或相邻行值猜入任何字段。 必须严格匹配 schema 中每个 field_id 的 value_type:decimal/integer 必须返回 JSON 数字;boolean 必须返回 JSON 布尔值;date 的 value 必须为 `YYYY-MM-DD`。例如原文 `06/22/2026` 的 date value 必须输出 `2026-06-22`,但 quote 仍保留原文 `06/22/2026`。不符合类型或无法规范化时省略字段,不得原样输出非 ISO 日期。 高风险行字段不得按位置或猜测映射:`line_no` 只能是订单行号(如 `00010`);`part_number` 是 HXOPS 内部料号,通常来自明确的 MPN、Supplier Part Number、Vendor Part Number 等供应商/制造商语义;`customer_part_number` 通常来自客户订单中的 `Material`、`Material No`、`Material Number`;`reservation_id` 只能是原文明确标注的 Reservation ID;`inventory_source_hint` 只能是明确库存源/仓库提示,绝不能填行号;`aws_part_number` 只能来自明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。若邮件正文或任一附件已有明确 AWS 料号,必须优先使用该证据,不能用 Material 覆盖。不得以料号、行号、描述、金额或数量互相替代。已发布的精确模板 Profile 可以覆盖裸表头的通常语义;例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法契约,Dify 不得重新改写。 +`Item deleted`、`Cancelled` 等删除标记可能独占一行并作用于前一条视觉明细,而非标记后的下一条明细。只有 `table_candidates_json` 已按版面行关系明确将候选行标记为 `role=deleted` 时,才忽略该行;纯文本或拆行文本中不得自行推断删除标记归属,也不得自动删除任何订单行,应保留候选并进入后续复核。若 Reservation ID 没有 `Reservation ID`、`COM ID`、`Reservation Order`、`Reservation No`、`Resv ID`、`PR Number` 或 `External reservation ID` 等明确标签和对应的 5 位或 10 位纯数字,必须省略 `reservation_id`;`EXW AWS HUB`、仓库/站点、贸易术语、项次和料号绝不能填入该字段。 + +【EML 正文专项规则】 + +当当前 `document_json.document_type` 为 `email_body`,或当前正文不是具有明确表头和行列关系的表格时,必须按“明确字段标签 + 紧邻逐字证据”提取;禁止按文本相邻位置、出现顺序、常识或空字段补位猜测字段。 + +`unit_price`、`amount`、`qty` 是数值字段,必须遵守以下规则: + +- `unit_price` 只能从明确标注为 `Unit Price`、`Price Each`、`Unit Cost`、`单价`、`价格` 的标签或同一明确表格列提取。 +- `amount` 只能从明确标注为 `Amount`、`Line Amount`、`Line Total`、`Total Amount`、`金额`、`小计`、`总价` 的标签或同一明确表格列提取。 +- `qty` 只能从明确标注为 `Qty`、`Quantity`、`Order Qty`、`数量`、`需求数量` 的标签或同一明确表格列提取。 +- 三者的 `value` 必须是 JSON 数字;不得输出字符串、料号、SKU、MPN、日期、站点或描述。 +- 未找到明确标签和逐字证据时,直接省略整个字段;不得填 `0`、不得猜测、不得用相邻字段代替。 + +料号严格规则: + +- 包含字母、连字符、斜杠或典型料号结构的值,例如 `D4-A08AR12000002`、`B3-AR1000270A1`,默认仅可作为料号候选,绝不能填入 `unit_price`、`amount` 或 `qty`。 +- 仅当原文明确标注 `MPN`、`Vendor Part Number`、`Supplier Part Number`、`Part Number`、`Material`、`Customer PN`、`AWS SKU` 等语义时,才按当前 Schema 的字段定义填入对应料号字段。 +- 料号角色无法可靠判断时直接省略;不得因为价格、金额或数量字段为空而把料号填入数值字段。 + +示例:正文为 `MPN: D4-A08AR12000002`,但没有 `Unit Price`、`Amount` 或 `Qty` 标签时,只能在 MPN 语义明确且满足当前 Schema 时输出对应料号字段;必须省略 `unit_price`、`amount` 和 `qty`,禁止把 `D4-A08AR12000002` 写入任何数值字段。 + +`[PROMPT_UPDATE]` 2026-07-22:补充 EML 正文的标签证据门禁,防止 MPN/料号因文本邻近或字段空缺被错填为单价、金额或数量。 + +`inventory_source_hint` 是可选字段:只有当前行或明确文档级文本含 Source Type、Hub Code、Warehouse、Site、仓库或站点语义时才输出。看到 `00010`、`00020` 等 Item/Line No 时必须输出 `line_no` 或省略,绝不能复制到 `inventory_source_hint`。Reservation ID 只允许原文明确标注的 5 位或 10 位纯数字;字母型编号和其他长度数字均不得输出。 + +`lines` 只能包含真实的订单货品行。不得把表头、跨页重复表头、空白占位行、版面解析产生的零值伪行输出为明细。`qty`/数量为 `0` 或负数时,默认省略整行;唯一例外是原文明确存在一条真实业务明细行且其数量确为 `0` 或负数:此时仍输出该行的原始逐字证据,让校验节点将其阻断并进入人工复核,绝不能把它伪装成正常订单行。若行号含料号字母,或数字行号被填入 `inventory_source_hint`,说明该行发生列错位;当该错位同时伴随非正数量时,必须省略整行,不得保留任何字段。 + +`table_candidates_json` 是 Code 节点从后端 `manifest.structured_table_candidates` 转换出的 Dify 内部变量。`field_policy=locked` 的 `field_id/value/quote` 必须原样返回,不得删除、改值或改字段;`field_policy=suggested` 只能作为列归属线索,仍须用当前文档原文判断并允许省略。`role=deleted` 的行不得恢复。不得要求或猜测 HTML、bbox、token、cell ID、evidence_ref 或内部 field_code;候选为空时按普通文档抽取。 + Reservation ID、料号、数量、金额、日期等不得根据常识、计算结果、文件名或其他字段反推。readonly_context_json 仅作提示,不得写入 header_fields、lines、conflicts 或输出。 -classification 只能是 shipping_request、non_shipping_request 或 uncertain,classification_confidence 必须是 0 到 1 的数字。一个单文档可以有零条、一条或多条独立订单;不得和不存在的 Document 合并。 +classification 只能是 shipping_request、non_shipping_request 或 uncertain,classification_confidence 必须是 0 到 1 的数字。采购订单、订单通知、PO、shipping order、delivery request 等需要发货处理的订单文档,一律使用 shipping_request。禁止输出 order_notice、purchase_order、shipping_order、invoice、order、other 或其他自定义分类值。一个单文档可以有零条、一条或多条独立订单;不得和不存在的 Document 合并。 + +【跨文档补全规则】 + +当前 Unit 不是完整订单边界。EML 与 PDF 必须各自独立抽取当前文档能证明的片段:EML 可以只返回 PO、地址、Reservation 或联系人;PDF 可以只返回订单行、料号、数量或价格。不得因为当前 Unit 缺少 PO、缺少任何必填 Header、缺少完整 Line、缺少 Reservation,或无法独立建单而返回失败、虚构字段或丢弃已验证证据。不要尝试读取、比较或合并其他 Document;尤其不得把 EML Reservation 复制到当前 PDF 行。HXOPS 会在所有 Unit 成功返回后以唯一强锚点保守关联行、完成冲突裁决和完整性门禁。 最终只输出一个 JSON Object,首字符必须是 {,末字符必须是 }。禁止输出 think、analysis、reasoning、XML/HTML、Markdown、代码围栏、自然语言、日志、Provider 信息或内部配置。 @@ -267,6 +374,9 @@ schema_contract_json: document_json: {{#parse_and_prepare_input.document_json#}} +table_candidates_json: +{{#parse_and_prepare_input.table_candidates_json#}} + readonly_context_json: {{#parse_and_prepare_input.readonly_context_json#}} @@ -292,7 +402,7 @@ line_field_ids_json: 输出:`orders`(String)、`order_count`(Number)、`validation_ok`(Boolean)、`validation_error`(String)。 -`extract_orders.text` 在不同 Dify 版本或模型连接器中可能是 JSON Object、JSON 字符串,或被额外 JSON 编码一次的字符串。验证节点最多解包两层;最终不是含 `orders` 数组的 JSON Object 时必须失败。此兼容仅处理序列化包装,不兼容 Markdown、思考文本或任意前后缀。 +`extract_orders.text` 在不同 Dify 版本或模型连接器中可能是 JSON Object、JSON 字符串,或被额外 JSON 编码一次的字符串。验证节点最多解包两层;模型偶发在完整 JSON Object 后额外输出最多两个 `]`/`}` 闭合符时,仅允许移除这些冗余闭合符。最终不是含 `orders` 数组的 JSON Object 时必须失败;不得吞掉 Markdown、思考文本、第二段 JSON 或任意其他前后缀。 将节点代码整体替换为: @@ -317,7 +427,7 @@ def _parse_json(value, name): def _parse_llm_output(value): - """兼容 Dify 对 LLM JSON 输出最多一次额外字符串化。""" + """兼容 Dify 字符串包装,以及模型偶发的少量冗余 JSON 闭合符。""" raw = value for _ in range(2): if isinstance(raw, dict): @@ -327,10 +437,18 @@ def _parse_llm_output(value): text = raw.strip() if not text: raise ValueError("llm_output is empty") + if text.startswith("```json") and text.endswith("```"): + text = text[7:-3].strip() + + decoder = json.JSONDecoder() try: - raw = json.loads(text) + parsed, end = decoder.raw_decode(text) except json.JSONDecodeError as exc: raise ValueError(f"llm_output is not valid JSON: {exc.msg}") from exc + trailing = text[end:].strip() + if trailing and (len(trailing) > 2 or any(char not in "]}" for char in trailing)): + raise ValueError("llm_output contains unexpected trailing content") + raw = parsed if isinstance(raw, dict): return raw raise ValueError("llm_output must unwrap to a JSON object") @@ -372,87 +490,182 @@ def _field_map(schema): "scope": str(field.get("scope") or "").strip().lower(), "value_type": str(field.get("value_type") or "string").strip().lower(), "field_code": str(field.get("field_code") or "").strip(), + "display_name": str(field.get("display_name") or field.get("field_code") or "未知字段").strip(), + "required": bool(field.get("required")), "validator_keys": list(field.get("validator_keys") or []), } return result -def _typed_value(value, config, field_id): - """在 Dify 侧拒绝无法落入冻结 Schema 类型的模型值。""" +def _field_label(config): + """返回校验日志使用的中文字段名称,禁止向业务用户暴露内部 field_id。""" + return config["display_name"] or config["field_code"] or "未知字段" + + +def _typed_value(value, config): + """在 Dify 侧拒绝无法落入冻结 Schema 类型的模型值,并返回业务可读错误。""" + label = _field_label(config) value_type = config["value_type"] if value_type == "decimal": if isinstance(value, bool) or not isinstance(value, (int, float)): - raise ValueError(f"{field_id} must be a JSON number") + raise ValueError(f"{label}格式错误:必须是 JSON 数字") elif value_type == "integer": if isinstance(value, bool) or not isinstance(value, int): - raise ValueError(f"{field_id} must be a JSON integer") + raise ValueError(f"{label}格式错误:必须是 JSON 整数") elif value_type == "boolean": if not isinstance(value, bool): - raise ValueError(f"{field_id} must be a JSON boolean") + raise ValueError(f"{label}格式错误:必须是 JSON 布尔值") elif value_type == "date": if not isinstance(value, str): - raise ValueError(f"{field_id} must be an ISO date string") + raise ValueError(f"{label}格式错误:必须是 YYYY-MM-DD 日期") try: date.fromisoformat(value) except ValueError as exc: - raise ValueError(f"{field_id} must use YYYY-MM-DD") from exc + raise ValueError(f"{label}格式错误:必须使用 YYYY-MM-DD") from exc elif value_type in {"string", "enum"}: if not isinstance(value, str) or not value.strip(): - raise ValueError(f"{field_id} must be a non-empty string") + raise ValueError(f"{label}格式错误:必须是非空文本") return value def _validate_field_semantics(value, config, field_id): """拦截模型常见的列位置错配,避免错误字段作为成功 Unit 进入 HXOPS。""" code = config["field_code"] + label = _field_label(config) validators = set(config["validator_keys"]) if "positive_decimal" in validators or "positive_integer" in validators: if value <= 0: - raise ValueError(f"{field_id} must be positive") + raise ValueError(f"{label}必须大于 0") if code == "line_no" and re.search(r"[A-Za-z]", value): - raise ValueError("line_no must not contain a part number") + raise ValueError("项次不能包含料号") if code == "inventory_source_hint" and re.fullmatch(r"\d+", value.strip()): - raise ValueError("inventory_source_hint must not be a line number") - if code == "reservation_id" and not re.fullmatch(r"\d{8,20}", value.strip()): - raise ValueError("reservation_id must be an explicit numeric reservation identifier") + raise ValueError("库存源线索不能是项次") + if code == "reservation_id" and not re.fullmatch(r"(?:\d{5}|\d{10})", value.strip()): + raise ValueError("预订单号必须恰好为 5 位或 10 位数字") return value +def _can_drop_field_error(error): + """字段不完整或错位只丢弃该证据;完整性由 HXOPS 在跨文档聚合后判断。""" + return isinstance(error, ValueError) + + +def _is_missing_evidence_observation(observation): + """丢弃模型明确表示未找到的占位输出;其他类型、来源或语义错误继续严格失败。""" + quote = str(observation.get("quote") or "").strip() + value = observation.get("value") + if not quote: + return True + lowered_quote = quote.lower() + if "not found" in lowered_quote or "未找到" in quote: + return True + if isinstance(value, str) and not value.strip(): + return True + return False + + +def _is_discardable_zero_quantity_pseudo_line(line, fields): + """仅丢弃有可验证列错位证据的零值伪行;真实零数量行仍须严格失败并复核。""" + items = line.get("fields") if isinstance(line, dict) else None + if not isinstance(items, list): + return False + has_non_positive_qty = False + has_invalid_line_no = False + has_numeric_inventory_hint = False + for item in items: + if not isinstance(item, dict): + continue + config = fields.get(str(item.get("field_id") or "").strip()) + observations = item.get("observations") + if not config or not isinstance(observations, list): + continue + for observation in observations: + if not isinstance(observation, dict) or _is_missing_evidence_observation(observation): + continue + value = observation.get("value") + code = config["field_code"] + if code == "qty" and isinstance(value, (int, float)) and not isinstance(value, bool) and value <= 0: + has_non_positive_qty = True + elif code == "line_no" and isinstance(value, str) and re.search(r"[A-Za-z]", value): + has_invalid_line_no = True + elif code == "inventory_source_hint" and isinstance(value, str) and re.fullmatch(r"\d+", value.strip()): + has_numeric_inventory_hint = True + return has_non_positive_qty and (has_invalid_line_no or has_numeric_inventory_hint) + + +def _quote_supports_value(value, quote, value_type): + """只保留能从逐字引文验证的候选值,允许日期和数字的标准化表示。""" + if value_type == "date" and isinstance(value, str): + try: + parsed = date.fromisoformat(value) + except ValueError: + return False + return parsed.strftime("%m/%d/%Y") in quote or value in quote + if value_type in {"decimal", "integer"} and isinstance(value, (int, float)) and not isinstance(value, bool): + target = float(value) + for token in re.findall(r"[-+]?\d[\d,]*(?:\.\d+)?", quote): + try: + if float(token.replace(",", "")) == target: + return True + except ValueError: + pass + return False + normalized_value = re.sub(r"[^a-z0-9]+", "", str(value).lower()) + normalized_quote = re.sub(r"[^a-z0-9]+", "", quote.lower()) + return bool(normalized_value) and normalized_value in normalized_quote + + def _field_group(items, scope, fields, document_id): if items is None: return [] if not isinstance(items, list): raise ValueError(f"{scope} fields must be an array") result = [] - seen = set() + result_by_field_id = {} for item in items: if not isinstance(item, dict): - raise ValueError(f"{scope} field must be an object") + raise ValueError(f"{scope}字段必须是对象") field_id = str(item.get("field_id") or "").strip() config = fields.get(field_id) - if not field_id or field_id in seen or not config or config["scope"] != scope: - raise ValueError(f"invalid {scope} field_id") - seen.add(field_id) + if not field_id or not config or config["scope"] != scope: + raise ValueError(f"无效的{scope}字段") + label = _field_label(config) observations = item.get("observations") if not isinstance(observations, list) or not observations: - raise ValueError(f"{field_id} must have at least one observation") + raise ValueError(f"{label}至少需要一条证据") normalized = [] for observation in observations: if not isinstance(observation, dict) or "value" not in observation: - raise ValueError(f"invalid observation for {field_id}") + raise ValueError(f"{label}存在无效证据") + if _is_missing_evidence_observation(observation): + continue if _as_int(observation.get("document_id"), "observation.document_id") != document_id: raise ValueError("observation.document_id must equal unit primary_document_id") quote = str(observation.get("quote") or "").strip() - if not quote: - raise ValueError(f"observation quote is required for {field_id}") - value = _typed_value(observation.get("value"), config, field_id) + try: + # [STEP 1] 单文档不完整是正常状态;字段错位或类型错误只丢弃该 Observation。 + value = _typed_value(observation.get("value"), config) + value = _validate_field_semantics(value, config, field_id) + if not _quote_supports_value(value, quote, config["value_type"]): + raise ValueError(f"{label}的取值无法由原文证据验证") + except ValueError as exc: + if _can_drop_field_error(exc): + continue + raise normalized.append({ - "value": _validate_field_semantics(value, config, field_id), + "value": value, "document_id": document_id, "quote": quote, "confidence": _confidence(observation.get("confidence"), "observation.confidence"), }) - result.append({"field_id": field_id, "observations": normalized}) + if normalized: + # [STEP 2] 同字段的多次模型输出合并为多条证据,交由 HXOPS 后端统一裁决冲突。 + existing = result_by_field_id.get(field_id) + if existing is None: + existing = {"field_id": field_id, "observations": []} + result_by_field_id[field_id] = existing + result.append(existing) + existing["observations"].extend(normalized) return result @@ -476,12 +689,28 @@ def main(llm_output, schema_contract_json: str, source_intake_no: str, primary_d raise ValueError("source_intake_no must equal unit intake_no") if _as_int(order.get("primary_document_id"), "primary_document_id") != expected_document: raise ValueError("primary_document_id must equal unit document_id") + # 兼容旧 Prompt 曾输出的订单类分类,归一化后仍只保留三个业务规范值。 classification = str(order.get("classification") or "").strip().lower() + classification = { + "order_notice": "shipping_request", + "purchase_order": "shipping_request", + "shipping_order": "shipping_request", + }.get(classification, classification) if classification not in {"shipping_request", "non_shipping_request", "uncertain"}: - raise ValueError("invalid classification") + raise ValueError("订单分类无效,仅支持发货请求、非发货请求或待确认") lines = order.get("lines") or [] if not isinstance(lines, list): raise ValueError("lines must be an array") + normalized_lines = [] + for line in lines: + if not isinstance(line, dict): + raise ValueError("line must be an object") + # 只忽略“非正数量 + 可证明列错位”的版面伪行;其他无效字段会在字段级被省略。 + if _is_discardable_zero_quantity_pseudo_line(line, fields): + continue + line_fields = _field_group(line.get("fields"), "line", fields, expected_document) + if line_fields: + normalized_lines.append({"fields": line_fields}) normalized_orders.append({ "schema_version_id": expected_schema_id, "schema_checksum": expected_checksum, @@ -490,7 +719,7 @@ def main(llm_output, schema_contract_json: str, source_intake_no: str, primary_d "source_intake_no": expected_intake, "primary_document_id": expected_document, "header_fields": _field_group(order.get("header_fields"), "header", fields, expected_document), - "lines": [{"fields": _field_group(line.get("fields"), "line", fields, expected_document)} for line in lines if isinstance(line, dict)], + "lines": normalized_lines, "conflicts": order.get("conflicts") if isinstance(order.get("conflicts"), list) else [], }) return { @@ -534,14 +763,33 @@ End 节点只配置: - 裸 `Part Number` 存在客户模板歧义,不应作为跨客户强制语义。已确认模板使用精确 Profile 表达 `Part Number -> customer_part_number`、`Vendor Item# -> part_number`;这类映射是合法模板规则,不是异常,不应复制为 Dify Prompt 中的全局特例。 - `qty` 可增加已经确认仍为独立数量列的完整精确别名,例如 `Q TY 数量`、`Q'TY 数量`、`Q TY UNIT`、`ORDER QUANTITY EA`。不得配置 `Quantity U M Delivery`,该文本同时粘连数量、单位和交期,无法证明单一列语义。 - 不得为含首条数据的污染表头增加别名,例如 `Item No 00010`、`Order Amount 941.76`。这类结果必须由版面质量门禁转复核,不能把样本值写入 Schema。 -- `reservation_id` 每条订单行最终都必须具备,但证据可能位于邮件正文或其他附件。单张 PDF 缺失 Reservation 时应保留其确定性行字段,由邮件/其他附件单元补充;补充失败时停在流程门禁,禁止进入库存匹配和发货 Excel。 +- `reservation_id` 每条订单行最终都必须具备,但证据可能位于邮件正文或其他附件。单张 PDF 缺失 Reservation 时应保留其确定性行字段;只有同 Intake、同 PO 下能以唯一且一致的内部料号或项次关联到邮件/附件 Reservation 时,HXOPS 才补入最终行。重复料号、项次冲突、多个候选或无强锚点一律不得猜测,补充失败时停在流程门禁,禁止进入库存匹配和发货 Excel。 - 保存或发布前检查标准化别名碰撞;同一字段在一张表命中多个列时必须进入复核,不得通过调整 Prompt 让模型选择其中一列。 上述 Schema 修改在 HXOPS 管理端手工完成,不在 Dify Code/LLM 节点复制别名字典。 +### 8.2 MinerU/Profile 接入后的 Dify 画布 + +本阶段不新增 Start 变量,仍只有 String 类型 `execution_manifest`。手工修改清单: + +- Code 节点解析 `manifest.document` 和可选的 `manifest.structured_table_candidates`,不存在时返回空数组,不得因可选字段缺失报错。 +- LLM Prompt 使用本手册 `table_candidates_json` 约束;不得要求 MinerU HTML 或坐标,也不得在 Dify 再维护 Profile 映射字典。 +- End 输出保持原 `orders` String 契约,不增加 Profile/布局调试输出。 +- 对候选中的 `status=deleted` 行直接忽略;`needs_review` 行只能作为补充线索,不能直接作为完整订单行。 +- Dify 不调用 MinerU,不配置 MinerU URL;MinerU 只由 HXOPS 独立文档布局 Worker 调用,Intake 仅负责创建版本化布局任务。 +- Profile 的样本选择、列映射、新版本、发布和退役全部在 HXOPS 管理端完成;Dify 不新增 Profile 管理 Tool,不读取 Profile 管理 API,也不维护模板映射副本。 + +L1 只调整 HXOPS 内部布局生命周期,不改变 `execution_manifest`、LLM Prompt、校验节点或 End 输出;如果当前画布已按本节完成配置,本阶段 **无需再次修改 Dify**。 + +L2 新增的 PDFium/OpenCV `layout_candidate` 只保存在 HXOPS 布局版本内部,并固定为 `needs_review`;它不会进入 `execution_manifest`。因此 L2 同样 **无需修改 Dify**。 + +L3 的 RapidOCR 坐标候选和清洗后 EML HTML DOM 布局也只保存在 HXOPS 内部,不会把 OCR 坐标、原始 HTML 或 `layout_candidate` 发送给 Workflow。因此 L3 **无需修改 Dify**。 + +L4 的 `layout_schema_candidates` 只冻结在 HXOPS Run snapshot v3 中,并在编译 Workflow Manifest 时强制删除。当前画布不会收到 cell/token/evidence_ref,因此 L4 **无需修改 Dify**。 + - [ ] Start 仅有 `execution_manifest`,且为 String。 -- [ ] `parse_and_prepare_input` 只接受 `shipping_order_extraction.unit.v2`。 -- [ ] 代码要求 `documents` 长度恰为 1,并且只读取 `documents[0].document`。 +- [ ] `parse_and_prepare_input` 只读取本手册定义的唯一 Manifest 字段。 +- [ ] 代码只读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`,不再读取 `documents[0].document`。 - [ ] LLM 仅收到 `document_json`,没有 `documents_json`、附件集合或整封邮件拼接输入。 - [ ] LLM 明确固定 `source_intake_no`、`primary_document_id` 和所有 Observation 的 `document_id`。 - [ ] LLM 不输出没有证据的字段;不输出空 Observation。 @@ -552,6 +800,9 @@ End 节点只配置: - [ ] 明确的 AWS SKU/APN 证据优先于 Material,且 Material 不覆盖已有 AWS 料号。 - [ ] Qty 只配置语义单一的完整表头;多语义粘连表头和含首条数据的污染表头未进入 Schema aliases。 - [ ] 单张 PDF 缺少 Reservation 时仍保留其确定性字段;邮件/其他附件负责补充,Dify 不伪造 Reservation,HXOPS 最终流程门禁负责阻断库存匹配。 +- [ ] 同 PO 的 EML/PDF 仅在唯一且一致的 `part_number` 或 `line_no` 下跨文档补入 Reservation;重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点必须保持 `needs_review`,不得自动复制 Reservation。 +- [ ] EML 或单张 PDF 缺少 PO、必填 Header、完整 Line 或 Reservation 时,Code 节点仍返回其余当前 Document 的有效证据;不得以“订单号至少需要一条证据”或任何订单完整性判断进入失败分支。 +- [ ] Code 节点仅因 JSON/结构、Schema、Intake/Document 来源不一致等协议错误失败;字段缺失、字段类型不符或明显字段错位只丢弃该字段,并由 HXOPS 跨文档合并后决定 `needs_review` 或后续处理。 - [ ] 校验节点对每个订单及每个 Observation 强制当前 Unit 的 Intake/Document 归属。 - [ ] 校验失败进入失败分支,不返回成功空数组。 - [ ] End 只有 String 类型的 `orders`,API 响应顶层键为 `outputs.orders`。 @@ -561,4 +812,6 @@ End 节点只配置: 发布 Dify 后,创建一次新的订单抽取 Run。管理员诊断中,每个 Unit 应独立成功或失败;某个 Unit 的 `orders`、`primary_document_id` 和所有 Observation `document_id` 必须一致。跨文档字段合并只会在 HXOPS 后端发生。 +对 PDF,Dify 的 `quote` 必须逐字引用本次输入 `document_json.extracted_text` 中的 MinerU 分页文本或 TSV 表格。HXOPS 会使用**同一个 Run 冻结且实际发送给 Dify 的文本**优先核验 quote,数据库旧 PDF 文本只作为兼容回退;这不会放宽 quote 或 value 校验。若 quote 不存在于冻结 MinerU 文本和旧文本两者,Observation 必须被拒绝并进入复核。 + Workflow 成功不代表 Task 已创建。HXOPS 仍会执行动态 Schema、Reservation 证据、重复检测、客户影子识别和自动建单开关等门禁。 diff --git a/docs/features/shipping-notice/pdf-order-truth-fill-form.md b/docs/features/shipping-notice/pdf-order-truth-fill-form.md new file mode 100644 index 00000000..759c6c18 --- /dev/null +++ b/docs/features/shipping-notice/pdf-order-truth-fill-form.md @@ -0,0 +1,875 @@ +# PDF 订单字段级人工真值填写表 + +这才是需要你实际填写的表。每个 PDF 都有一张独立表格。 + +填写原则: + +- 直接填写你确认的正确值。 +- PDF 中没有该字段,填写“原文无此值”。 +- 看得到信息但无法确定属于哪个字段或哪一条明细,填写“需要人工复核”。 +- 明细行不够时,复制最后一行继续填写。 +- 行状态只能填写:有效、已删除、需要人工复核。 +- 删除项不是唯一目标;表头、料号、预约单号、数量、单价、金额、币种、交期等字段都需要填写。 + +## PDF-001(已完成) + +- 来源 EML(完整文件名):[ACC_ACP] Welltrust PO#4518738152 & 4518838154 for UM17.eml +- PDF 附件名:4518838152.pdf +- 覆盖场景(填写):正常多行 / 跨行续行 / 删除项 / 跨页表头 / 扫描OCR / 无法可靠识别 +- 填写状态:待填写 / 已完成 +- 已确认信息:已知:项次 00010 为已删除;项次 00020 为有效。 + +### 表头字段 + + +| 字段 | 你确认的正确值 | +| ----- | --------------------------------------------------------- | +| 采购订单号 | 4518838152 | +| 账款客户 | Inventec Corporation | +| 账款地址 | 66 Hou-Kang Street, Shin-Lin Distr. 111059 Taipei, Taiwan | +| 收货客户 | Inventec IEC Technologies | +| 收货地址 | 9601 Pan American Drive, El Paso, Texas 79927, U.S.A. | + + + + +### 明细字段 + + +| 项次 | 行状态 | 删除标记归属说明 | 内部料号 | 客户料号 | AWS料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| ----- | --- | --------------------------------------------- | ---------------- | ------------ | ----- | ----- | --- | ---------- | -------- | --- | ---------- | --- | +| 00010 | 已删除 | 独占的 `** Item deleted **` 位于本行之后、00020 之前,归属本行 | D4-A08AR12000002 | 6Y70B2501901 | 原文无此值 | 原文无此值 | 0 | 0.000000 | 0.00 | USD | 2026-06-22 | | +| 00020 | 有效 | 原文无删除标记 | D4-A08AR12000002 | 6Y70B2501901 | 原文无此值 | 原文无此值 | 30 | 941.760000 | 28252.80 | USD | 2026-06-29 | | +| | | | | | | | | | | | | | + + + + +## PDF-002(已完成) + +- 来源 EML(完整文件名):[ACC_ACP] Welltrust PO#4518738152 & 4518838154 for UM17.eml +- PDF 附件名:4518838154.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------------------------- | +| 采购订单号 | 4518838154 | +| 账款客户 | Inventec Corporation | +| 账款地址 | 66 Hou-Kang Street, Shin-Lin Distr. 111059 Taipei, Taiwan | +| 收货客户 | Inventec IEC Technologies | +| 收货地址 | 9601 Pan American Drive, El Paso, Texas 79927, U.S.A. | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 00010 | 已删除 | 6Y70B2501401 | B3-AR1000270A1 | 4000111701 | 0 | 0 | 0.00 | USD | 2026-06-22 | | +| 00020 | 有效 | 6Y70B2501401 | B3-AR1000270A1 | 4000111701 | 36 | 50.43 | 1815.48 | USD | 2026-06-29 | | + +## PDF-003(已完成) + +- 来源 EML(完整文件名):_Revised PO with correct U_P _*Allocation_id#SBKTIETA260609E2-172 & reservation_id #3000099143_IEC PO* 4518814838, 合欣精密(泰國)有限公司, _TP15.eml +- PDF 附件名:4518814838_52D_R_price_20260629.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------ | +| 采购订单号 | 4518814838 | +| 账款客户 | Inventec Corporation | +| 账款地址 | 66 Hou-Kang Street, Shin-Lin Distr. 111059 Taipei, Taiwan | +| 收货客户 | Inventec Corporation Taoyuan Factory | +| 收货地址 | No.88, Dazhi Rd., Taoyuan Dist., Taoyuan City 330417, Taiwan | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 00010 | 有效 | 6Y17B2493101 | D4-AR1200163A1 | 3000099143 | 20 | 563.79 | 11275.80 | USD | 2026-07-22 | | + +## PDF-004(已完成) + +- 来源 EML(完整文件名):*Wiwynn-MY* 0000631884 New PO ZNE #0060180061 (HOXIN PRECISION THAILAND CO.,LTD.).eml +- PDF 附件名:F9A1 ZNE0060180061.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ---------------------------------------------------------------------------------------------------------- | +| 采购订单号 | 60180061 | +| 账款客户 | Wiwynn Corporation. | +| 账款地址 | 8F,90,Sec.1,Xintai 5th Rd., Xizhi Dist.,New Taipei City 22102,Taiwan(R.O.C.)New Taipei City 22102Taiwan | +| 收货客户 | Wiwynn Technology Service Malaysia Sdn. Bhd. | +| 收货地址 | C/O P1 DHL Supply Chain (Malaysia), Johor 81560, Malaysia | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | B3-A08AR10000018-A7 | 541-000175-007 | 3000092530 | 3 | 1645.11 | 4935.33 | USD | 2026-05-05 | | + +## PDF-005(已完成) + +- 来源 EML(完整文件名):*Wiwynn-TN* 0000631884 New PO ZNE #0060187624 (HOXIN PRECISION THAILAND CO.,LTD.).eml +- PDF 附件名:F9D1 ZNE0060187624.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ---------------------------------------------------------------------------------------------------------- | +| 采购订单号 | 60187624 | +| 账款客户 | Wiwynn Corporation. | +| 账款地址 | 8F,90,Sec.1,Xintai 5th Rd., Xizhi Dist.,New Taipei City 22102,Taiwan(R.O.C.)New Taipei City 22102Taiwan | +| 收货客户 | Wiwynn Smart Manufacturing Corporation (WYLZ) | +| 收货地址 | Rm. 1-2, 1F., No. 5, Luke 3rd Rd., Luzhu Dist., Kaohsiung City 821, Taiwan | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000001 | 504-006043-001 | 3000097059 | 1 | 898.72 | 898.72 | USD | 2026-05-26 | | + +## PDF-006(已完成) + +- 来源 EML(完整文件名):AWS allocation PO#60195839, 60195840, 60195841.eml +- PDF 附件名:F912 ZNE0060195839.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ---------------------------------------------------------------- | +| 采购订单号 | 60195839 | +| 账款客户 | Wiwynn International corporation | +| 账款地址 | 1430 Henry Brennan Drive El Paso, TX79936El Paso 79936USA | +| 收货客户 | Wiwynn International Corporation | +| 收货地址 | C/O Kuehne & Nagel, 490-A Bill Burnett Drive, El Paso 79928, USA | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000001 | 504-006043-001 | 2000485617 | 9 | 898.72 | 8088.48 | USD | 2026-07-10 | | + +## PDF-007(已完成) + +- 来源 EML(完整文件名):AWS allocation PO#60195839, 60195840, 60195841.eml +- PDF 附件名:F912 ZNE0060195841.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ---------------------------------------------------------------- | +| 采购订单号 | 60195841 | +| 账款客户 | Wiwynn International corporation | +| 账款地址 | 需要人工复核 | +| 收货客户 | 1430 Henry Brennan Drive El Paso, TX79936El Paso 79936USA | +| 收货地址 | C/O Kuehne & Nagel, 490-A Bill Burnett Drive, El Paso 79928, USA | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000001 | 504-006043-001 | 30550 | 37 | 898.72 | 33252.64 | USD | 2026-07-10 | | + +## PDF-008(已完成) + +- 来源 EML(完整文件名):AWS allocation PO#60195839, 60195840, 60195841.eml +- PDF 附件名:F912 ZNE0060195840.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ---------------------------------------------------------------- | +| 采购订单号 | 60195840 | +| 账款客户 | Wiwynn International corporation | +| 账款地址 | 1430 Henry Brennan Drive El Paso, TX79936El Paso 79936USA | +| 收货客户 | Wiwynn International Corporation | +| 收货地址 | C/O Kuehne & Nagel, 490-A Bill Burnett Drive, El Paso 79928, USA | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000001 | 504-006043-001 | 30547 | 54 | 898.72 | 48530.88 | USD | 2026-07-10 | | + +## PDF-009(已完成) + +- 来源 EML(完整文件名):AWS allocation released_0707.eml +- PDF 附件名:F6H1 ZNB0016776707.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------------------------------ | +| 采购订单号 | 16776707 | +| 账款客户 | Wistron Corporation | +| 账款地址 | No. 1, Zhihui Rd., Zhubei City,Hsinchu County 302059, TaiwanHsinchu County 302059Taiwan | +| 收货客户 | Wistron Corporation | +| 收货地址 | C/O Wistron InfoComm (Czech) s.r.o, Vlastimila Pecha 1269/10, Brno 62700, Czech Republic | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000002 | 504-006055-001 | 1000130205 | 30 | 941.76 | 28252.80 | USD | 2026-07-21 | | +| 20 | 有效 | D4-A08AR12000002 | 504-006055-001 | 1000130215 | 30 | 941.76 | 28252.80 | USD | 2026-07-21 | | +| 30 | 有效 | D4-A08AR12000002 | 504-006055-001 | 1000130214 | 30 | 941.76 | 28252.80 | USD | 2026-07-21 | | +| 40 | 有效 | B3-AR1000270A1 | 504-006063-001 | 1000148881 | 24 | 50.43 | 1210.32 | USD | 2026-07-21 | | +| 50 | 有效 | D4-A08AR12000002 | 504-006055-001 | 1000130207 | 30 | 941.76 | 28252.80 | USD | 2026-07-21 | | + +## PDF-010(已完成) + +- 来源 EML(完整文件名):new order, pls help to pull request into DBS system for pickup from SIN Hub 3400104730.eml +- PDF 附件名:3400104730_CEBG2606005108.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------------- | +| 采购订单号 | 3400104730 | +| 账款客户 | INGRASYS TECHNOLOGY INC. | +| 账款地址 | 5F., No. 1188, Nanqing Rd., Luzhu Dist., Taoyuan City 338, Taiwan(R.O.C.) | +| 收货客户 | INGRASYS TECHNOLOGY INC. | +| 收货地址 | No.1188, Nanqing Rd., Luzhu Dist., Taoyuan City 338, Taiwan | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 00010 | 有效 | D4-A08AR12000002 | TEMP-S000218929 | 3000092917 | 10 | 941.76 | 9417.60 | USD | 2026-06-12 | | + +## PDF-011(已完成) + +- 来源 EML(完整文件名):New PO Hoxin.eml +- PDF 附件名:4210012207.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------- | +| 采购订单号 | 4210012207 | +| 账款客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 账款地址 | 54 GENTING LANE, #03-05 RUBY LAND COMPLEX BLOCK II | +| 收货客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 收货地址 | Parque Industrial Altos 3 El Salto 2000-B, Las Pintitas | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000020 | AMTEMP-S000265007 | 2000485369 | 1 | 1731.60 | 1731.60 | USD | 2026-07-15 | | + +## PDF-012(已完成) + +- 来源 EML(完整文件名):New PO Hoxin.eml +- PDF 附件名:4210012208.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------- | +| 采购订单号 | 4210012208 | +| 账款客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 账款地址 | 54 GENTING LANE, #03-05 RUBY LAND COMPLEX BLOCK II | +| 收货客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 收货地址 | Parque Industrial Altos 3 El Salto 2000-B, Las Pintitas | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000020 | AMTEMP-S000265007 | 2000485676 | 1 | 1731.60 | 1731.60 | USD | 2026-07-15 | | + +## PDF-013(已完成) + +- 来源 EML(完整文件名):New PO Hoxin.eml +- PDF 附件名:4210012209.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------- | +| 采购订单号 | 4210012209 | +| 账款客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 账款地址 | 54 GENTING LANE, #03-05 RUBY LAND COMPLEX BLOCK II | +| 收货客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 收货地址 | Parque Industrial Altos 3 El Salto 2000-B, Las Pintitas | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000001 | AMTEMP-S000218922 | 2000485997 | 1 | 898.72 | 898.72 | USD | 2026-07-15 | | + +## PDF-014(已完成) + +- 来源 EML(完整文件名):New PO Hoxin.eml +- PDF 附件名:4210012210.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------- | +| 采购订单号 | 4210012210 | +| 账款客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 账款地址 | 54 GENTING LANE, #03-05 RUBY LAND COMPLEX BLOCK II | +| 收货客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 收货地址 | Parque Industrial Altos 3 El Salto 2000-B, Las Pintitas | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000001 | AMTEMP-S000218922 | 4000114173 | 28 | 898.72 | 25164.16 | USD | 2026-07-15 | | + +## PDF-015(已完成) + +- 来源 EML(完整文件名):New PO Hoxin.eml +- PDF 附件名:4210012211.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------- | +| 采购订单号 | 4210012211 | +| 账款客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 账款地址 | 54 GENTING LANE, #03-05 RUBY LAND COMPLEX BLOCK II | +| 收货客户 | INGRASYS (SINGAPORE) PTE. LTD. | +| 收货地址 | Parque Industrial Altos 3 El Salto 2000-B, Las Pintitas | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-A08AR12000020 | AMTEMP-S000265007 | 31088 | 4 | 1731.60 | 6926.40 | USD | 2026-07-15 | | + +## PDF-016(已完成) + +- 来源 EML(完整文件名):PO 4510039227, 4510039228, 4510039229 - Welltrust - ACC - 07_07.eml +- PDF 附件名:4510039227.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------- | +| 采购订单号 | 4510039227 | +| 账款客户 | Cloud Network Technology Kft. | +| 账款地址 | Bánki Donát u. 1, 2900 Komárom, Hungary | +| 收货客户 | Cloud Network Technology Kft. | +| 收货地址 | Bánki Donát u. 1, 2900 Komárom, Hungary | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | + +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | + +| 00010 | 有效 | D4-A08AR12000001 | TEMP-S000218922 | 2000485916 | 30 | 898.72| 26961.6 | USD | 14/07/2026 | | + +## PDF-017(已完成) + +- 来源 EML(完整文件名):PO 4510039227, 4510039228, 4510039229 - Welltrust - ACC - 07_07.eml +- PDF 附件名:4510039228.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------- | +| 采购订单号 | 4510039228 | +| 账款客户 | Cloud Network Technology Kft. | +| 账款地址 | Bánki Donát u. 1, 2900 Komárom, Hungary | +| 收货客户 | Cloud Network Technology Kft. | +| 收货地址 | Bánki Donát u. 1, 2900 Komárom, Hungary | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-AR1200115A1 | TEMP-S000196207 | 2000485915 | 60 | 623.72 | 37423.2 | USD | 14/07/2026 | | + +## PDF-018(已完成) + +- 来源 EML(完整文件名):PO 4510039227, 4510039228, 4510039229 - Welltrust - ACC - 07_07.eml +- PDF 附件名:4510039229.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------- | +| 采购订单号 | 4510039229 | +| 账款客户 | Cloud Network Technology Kft. | +| 账款地址 | Bánki Donát u. 1, 2900 Komárom, Hungary | +| 收货客户 | Cloud Network Technology Kft. | +| 收货地址 | Bánki Donát u. 1, 2900 Komárom, Hungary | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000001 | TEMP-S000218922 | 1000148820 | 1 | 898.72 | 898.72 | USD | 14/07/2026 | | + +## PDF-019(已完成) + +- 来源 EML(完整文件名):PO#312207 for Vendor#161185(HOXIN PRECISION (THAILAND) CO., LTD.).eml +- PDF 附件名:PO_312207.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------ | +| 采购订单号 | 312207 | +| 账款客户 | Hyve Solutions Corporation | +| 账款地址 | 44201 Nobel Drive, Fremont, CA 94538, United States | +| 收货客户 | Hyve Solutions Corporation | +| 收货地址 | 10381 State Line Rd, DOCK#5, Olive Branch, MS 38654, United States | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 1 | 有效 | B3-A08AR11000001 | WTP-B3-A08AR11000001 | 31221 | 7 | 1607.72 | 11254.04 | USD | 2026-07-15 | | + +## PDF-020(已完成) + +- 来源 EML(完整文件名):PO#50013 for Vendor#3300348(HOXIN PRECISION (THAILAND) CO., LTD.).eml +- PDF 附件名:PO_50013.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------------------------------ | +| 采购订单号 | 50013 | +| 账款客户 | Hyve Solutions China Limited | +| 账款地址 | Plot Z9-1, Comprehensive Bonded Zone, Wuxi, Jiangsu 214028, China | +| 收货客户 | Hyve Solutions China Limited | +| 收货地址 | CM481 Plot Z9-1, Comprehensive Bonded Zone, Wuxi New District, Wuxi, Jiangsu 214028, China | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 1 | 有效 | B3-A08AR10000017-A6 | WTP-B3-A08AR10000017-A6 | 3000104201 | 6 | 1525.08 | 9150.48 | USD | 2026-07-15 | | +| 2 | 有效 | D4-A08AR12000001 | WTP-D4-A08AR12000001 | 3000104272 | 2 | 898.72 | 1797.44 | USD | 2026-07-15 | | + +## PDF-021(已完成) + +- 来源 EML(完整文件名):PO#6073478 for Vendor#10804(HOXIN PRECISION (THAILAND) CO., LTD.).eml +- PDF 附件名:PO_6073478.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ---------------------------------------------------------------------- | +| 采购订单号 | 6073478 | +| 账款客户 | Hyve Solutions Europe Limited | +| 账款地址 | SYNNEX House, Nedge Hill, Telford, Shropshire, TF3 3AH, United Kingdom | +| 收货客户 | Hyve Solutions | +| 收货地址 | Halesfield 25, Telford, Shropshire, GB TF7 4LP, United Kingdom | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 1 | 有效 | D4-A08AR12000002 | WTP-D4-A08AR12000002 | 1000148078 | 30 | 941.76 | 28252.80 | USD | 2026-07-16 | | + +## PDF-022(已完成) + +- 来源 EML(完整文件名):WELLTRUST ACC PO 1000050815.eml +- PDF 附件名:1000050815.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ----------------------------------------------- | +| 采购订单号 | 1000050815 | +| 账款客户 | **ZT Group Int'l, Inc.** | +| 账款地址 | 200 Plaza DriveSECAUCUS NJ 07094USA | +| 收货客户 | ZT SYSTEMS - WAREHOUSE | +| 收货地址 | 1 EMERSON LANE, SECAUCUS, New Jersey 07094, USA | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| 10 | 有效 | D4-AR1200163A1 | BU-00014-001B | 31207 | 60 | 563.79 | 33827.40 | USD | 2026-07-09 | | + +## PDF-023(已完成) + +- 来源 EML(完整文件名):【WellTrust】New PO#4518814494 for ACC Part.eml +- PDF 附件名:4518814494_524.pdf +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------------------------------- | +| 采购订单号 | 4518814494 | +| 账款客户 | Inventec Corporation | +| 账款地址 | 66 Hou-Kang Street, Shin-Lin Distr. 111059 Taipei, Taiwan | +| 收货客户 | Inventec Corporation Taoyuan Factory英業達股份有限公司桃科廠 | +| 收货地址 | No.88, Dazhi Rd.,Taoyuan Dist., Taoyuan City 330417, Taiwan (R.O.C.) (330417)桃園市桃園區大智路88號 | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000002 | 6Y70B2501901 | **3000099132** | 1 | 941.76 | 941.76 | USD | 11/18/2026 | | + +## PDF-024(已完成) + +- 来源 EML(完整文件名):回复_ New allocation- enclosure 7_7.eml +- PDF 附件名:7911674612.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------------------------------------------------- | +| 采购订单号 | 7911674612 | +| 账款客户 | QCH, INC., A NEVADA CORPORATION | +| 账款地址 | 100 West Liberty Street, 10th Floor,Reno, NV 89501 USA | +| 收货客户 | QCH INC., A NEVADA CORPORATION c/o Quanta | +| 收货地址 | Manufacturing Nashville LLC, 1706 Heil QuakerBoulevard, LaVergne, TN 37086 U.S.A | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | B3-AR1000270A1 | FBL15202010  | 29710| 24 | 50.43 | 1210.32 | USD | 2026-07-15 | | + +## PDF-025(已完成) + +- 来源 EML(完整文件名):回复_ New allocation- enclosure 7_7.eml +- PDF 附件名:2881046551.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------- | +| 采购订单号 | 2881046551 | +| 账款客户 | Quanta Computer Inc. | +| 账款地址 | No.188, Wenhua 2nd Rd.,Guishan Dist., Taoyuan City 33377,Taiwan | +| 收货客户 | Quanta Computer Inc. DE 2470.58.340 | +| 收货地址 | C/O QCG Computer GmbHIndelandstrasse 2+4,52249 Eschweiler, Germany | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | B3-AR1000270A1 | FBL1520201 | 1000147114 | 24 | 50.43 | 1210.32 | USD | 2026-07-15 | | + +## PDF-026(已完成) + +- 来源 EML(完整文件名):回复_ New allocation- enclosure 7_7.eml +- PDF 附件名:2881046552.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------- | +| 采购订单号 | 2881046552 | +| 账款客户 | Quanta Computer Inc. | +| 账款地址 | No.188, Wenhua 2nd Rd.,Guishan Dist., Taoyuan City 33377,Taiwan | +| 收货客户 | Quanta Computer Inc. DE 2470.58.340 | +| 收货地址 | C/O QCG Computer GmbHIndelandstrasse 2+4,52249 Eschweiler, Germany | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000001 | FAL1602101 | 1000147035 | 3 | 898.72 | 2696.16 | USD | 2026-07-15 | | + +## PDF-027(已完成) + +- 来源 EML(完整文件名):回复_ New allocation- enclosure 7_7.eml +- PDF 附件名:2881046553.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ------------------------------------------------------------------- | +| 采购订单号 | 2881046553 | +| 账款客户 | Quanta Computer Inc. | +| 账款地址 | No.188, Wenhua 2nd Rd.,Guishan Dist., Taoyuan City 33377,Taiwan | +| 收货客户 | Quanta Computer Inc. DE 2470.58.340 | +| 收货地址 | C/O QCG Computer GmbHIndelandstrasse 2+4,52249 Eschweiler, Germany | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000001 | FAL1602101 | 1000146852 | 7 | 898.72 | 6291.04 | USD | 2026-07-15 | | + +## PDF-028(已完成) + +- 来源 EML(完整文件名):回复_ New allocation- enclosure 7_7.eml +- PDF 附件名:7911674610.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------------------------------------------------- | +| 采购订单号 | 7911674610 | +| 账款客户 | QCH, INC., A NEVADA CORPORATION | +| 账款地址 | 100 West Liberty Street, 10th Floor,Reno, NV 89501 USA | +| 收货客户 | QCH INC., A NEVADA CORPORATION c/o Quanta | +| 收货地址 | Manufacturing Nashville LLC, 1706 Heil QuakerBoulevard, LaVergne, TN 37086 U.S.A | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000002 | FAL1509701 | 30602 | 37 | 941.76 | 34845.12 | USD | 2026-07-15 | | + +## PDF-029(已完成) + +- 来源 EML(完整文件名):回复_ New allocation- enclosure 7_7.eml +- PDF 附件名:7911674611.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | --------------------------------------------------------------------------------- | +| 采购订单号 | 7911674611 | +| 账款客户 | QCH, INC., A NEVADA CORPORATION | +| 账款地址 | 100 West Liberty Street, 10th Floor,Reno, NV 89501 USA | +| 收货客户 | QCH INC., A NEVADA CORPORATION c/o Quanta | +| 收货地址 | Manufacturing Nashville LLC, 1706 Heil QuakerBoulevard, LaVergne, TN 37086 U.S.A | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000002 | FAL1509701 | 2000485990 | 3 | 941.76 | 2825.28 | USD | 2026-07-15 | | + +## PDF-030(已完成) + +- 来源 EML(完整文件名):转发_ New allocation- enclosure 6_30.eml +- PDF 附件名:1078429497.PDF +- 覆盖场景(待你确认): +- 填写状态:已完成 + + + +### 表头字段 + + +| 字段 | 机器预填值 | +| ----- | ----------------------------------------------------------------- | +| 采购订单号 | 1078429497 | +| 账款客户 | Quanta Computer Inc. | +| 账款地址 | No.188, Wenhua 2nd Rd.,Guishan Dist., Taoyuan City 33377,Taiwan | +| 收货客户 | Quanta Computer Inc. HQ Plant | +| 收货地址 | No 188. Wenhua 2nd Road,Guishan Dist.,Taoyuan City 33377, Taiwan | + + + + +### 明细字段 + +| 项次 | 行状态 | 内部料号 | 客户料号 | 预约单号 | 数量 | 单价 | 金额 | 币种 | 要求交期 | 备注 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 00010 | 有效 | D4-A08AR12000001 | FAL1602101 | 3000093539 | 20 | 898.72 | 17974.40 | USD | 2026-07-10 | | \ No newline at end of file diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 72727723..3c2cd0c0 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -37,6 +37,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open - **Provider 不写死**:阶段 2 由应用管理显式绑定 `shipping.order_extraction`;禁止名称匹配、固定 Agent/App ID 或环境变量回退。Dify Workflow 画布由管理员手工维护。 - **Provider 成功结果先提交**:Worker 取得结构化 `orders` 后立即保存 `provider_result_json` 并提交,再执行 HXOPS 订单落库;即使 Dify 未返回 `workflow_run_id`,落库重试也不得再次调用 Dify。 - **失败 Run 手工重试**:用户在订单识别失败卡片点击“重新识别”,调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/retry`。仅 `failed` 可重试;复用原 Run、冻结附件/正文、Schema、Provider 身份和 Intake 关系,不要求重新上传,也不创建新 Run。重试创建新的 Job 执行尝试;若 `provider_result_json.orders` 已保存,则跳过 Dify,只继续 HXOPS 落库。 +- **重新识别版本链**:终态且未消费的 Run 可调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse` 创建新的 Run,原因仅允许 `rule_updated/field_mapping_error/document_quality/other`。新版重新冻结当前已发布的 Schema、Binding、Profile 和当前 ready 布局快照,不复用 Provider 成功缓存,也不在用户路径重跑 MinerU/OpenCV;旧候选在新版执行期间只读,新版失败后恢复旧版选择状态。仅当前版本 Candidate 可建单,旧版永远保留审计。 - **订单抽取可观测进度(阶段化建设)**:订单抽取仍是后台异步作业。HXOPS 服务端消费专用 Workflow 的 Dify SSE 节点事件,按节点类型自动投影为脱敏业务阶段;浏览器只通过自适应短轮询读取 Run 投影,不建立新的浏览器长 SSE。Dify Workflow 无需新增节点、标记或其他手工配置。 - **变更边界**:Run 冻结 Provider App ID、Base URL、timeout 和 max attempts;App ID/Base URL 漂移阻断旧 Run,API Key 不入快照并允许轮换。用户态 Run API不返回正文、Provider 快照、原始结果或配置。 - **阶段 0 Review 门禁**:已执行的 Alembic revision 不得继续追加模型字段;`provider_config_json/provider_snapshot_json` 由后续独立 revision 增加。进入下一阶段前必须确认数据库处于唯一 head、模型可完整查询 Candidate/Extraction/Run,并通过迁移往返、Run 服务和能力绑定 Worker 测试。 @@ -72,13 +73,13 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open **阶段 2 Dify 手工配置**:无需修改画布。计划和单元完全由 HXOPS 持久化,Dify 当前仍接收既有 `execution_manifest`;不要新增子任务 ID、计划状态或调度节点。阶段 3 文档更新后再按新的单元级输入契约手工调整。 -**阶段 3 当前结论(2026-07-21)**:Worker 当前按计划顺序处理单元。每个单元先使用 Run 冻结 Schema 执行确定性表格解析;只有所有 required Header/Line 字段均可由明确列关系形成逐字证据时,才直接生成动态订单并以 `execution_mode=deterministic` 成功收口,Dify 调用为零。无法完整确定的单元才调用 Dify,`execution_manifest` 升级为 `shipping_order_extraction.unit.v2`,只含当前 `unit`、当前 Intake 的受控只读提示和一个冻结 Document;兄弟附件、整封邮件拼接和完整 Schema definition 均不进入模型输入。模型输出的 `source_intake_no`、`primary_document_id` 和每条 Observation `document_id` 必须全部等于当前单元,否则在局部结果落库前拒绝。所有单元结果按计划顺序汇总后,仍进入 HXOPS 现有严格 Schema、逐字证据、Reservation 安全和 Candidate/Task 门禁。 +**阶段 3 当前结论(2026-07-21)**:Worker 当前按计划顺序处理单元。每个单元先使用 Run 冻结 Schema 执行确定性表格解析;只有所有 required Header/Line 字段均可由明确列关系形成逐字证据时,才直接生成动态订单并以 `execution_mode=deterministic` 成功收口,Dify 调用为零。无法完整确定的单元才调用 Dify;唯一 `execution_manifest` 只含当前 `unit`、当前 Intake 的受控只读提示和一个冻结 Document。兄弟附件、整封邮件拼接和完整 Schema definition 均不进入模型输入。模型输出的 `source_intake_no`、`primary_document_id` 和每条 Observation `document_id` 必须全部等于当前单元,否则在局部结果落库前拒绝。所有单元结果按计划顺序汇总后,仍进入 HXOPS 现有严格 Schema、逐字证据、Reservation 安全和 Candidate/Task 门禁。 -**阶段 3 Dify 手工配置(必须由管理员执行)**:Start 节点仍只保留一个 String 输入 `execution_manifest`,但必须按 `contract_version=shipping_order_extraction.unit.v2` 解析。模型节点只能读取 `documents[0].document`,并把 `unit.intake_no` 写入每个订单的 `source_intake_no`、`unit.document_id` 写入 `primary_document_id` 和所有 Observation 的 `document_id`。不得遍历或期待多个 Intake/Document,不得从外部回读兄弟附件。End 仍只输出 `orders`。确定性完整表格不会进入 Dify,因此 Workflow 必须允许单个非表格/不完整文档返回零个或多个订单。 +**阶段 3 Dify 手工配置(必须由管理员执行)**:Start 节点只保留一个 String 输入 `execution_manifest`。模型节点只读取 `document`,并把 `unit.intake_no` 写入每个订单的 `source_intake_no`、`unit.document_id` 写入 `primary_document_id` 和所有 Observation 的 `document_id`。不得遍历或期待多个 Intake/Document,不得从外部回读兄弟附件。End 仍只输出 `orders`。确定性完整表格不会进入 Dify,因此 Workflow 必须允许单个非表格/不完整文档返回零个或多个订单。 **阶段 4 当前结论(2026-07-21)**:非确定性单元以 Run 冻结的 `unit_concurrency=2..4` 受控并行调用 Dify;线程只持有冻结 Run/Unit 和 Provider 网络字段的纯快照,不共享 ORM Session。每个单元按 `unit_max_attempts=1..3` 独立重试,并使用 `unit_retry_backoff_ms=100..5000` 指数退避加抖动;已成功和确定性单元不重跑。主线程串行写入单元状态、结果、attempt 和 latency,并按冻结 position 汇总,完成顺序不改变业务顺序。任一单元耗尽局部重试后保留其他成功结果,再由 Job 重试恢复失败单元;全局 Provider 治理与熔断在阶段 6 完成。 -**阶段 4 Dify 手工配置**:画布无需新增并行或重试节点,仍按阶段 3 的 `unit.v2` 单文档契约执行。并发、局部重试和退避全部由 HXOPS Worker 管理。管理员在入口 Agent 的订单抽取绑定中配置文档并发数、单文档最大尝试次数和重试退避;不要在 Dify 内叠加循环重试。 +**阶段 4 Dify 手工配置**:画布无需新增并行或重试节点,继续按唯一单文档 Manifest 执行。并发、局部重试和退避全部由 HXOPS Worker 管理;不要在 Dify 内叠加循环重试。 **阶段 5 当前结论(2026-07-21)**:HXOPS 在所有成功单元完成后按冻结 Schema 的稳定 `field_id -> field_code` 合并订单。同一 Intake 内仅当 Header 的唯一 `po_number` 一致,或至少一条 Line 的唯一 `(part_number, reservation_id)` 组合相同时才判为同一订单;只有料号、数量或弱文本相似度绝不合并。合并只追加并去重 Observation,不选值、不覆盖冲突,Qty/金额/日期等不同值继续由现有动态字段裁决形成阻断冲突。没有可靠身份的订单保持拆分。单元耗尽局部重试时,其他成功单元仍进入 HXOPS 提交;失败单元保留 `failed` 状态,Run 以 `needs_review` 收口并返回 `failed_unit_count`,不会把部分成功伪装成 completed。 @@ -88,7 +89,45 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open **阶段 6 Dify 手工配置**:无需修改画布。预算、Provider 并发和熔断全部由 HXOPS 管理;Dify 继续保持单文档无状态执行。管理员只在 HXOPS Runtime Binding 配置治理参数,不要在 Dify 内复制限流、循环重试或熔断逻辑。 -**阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试已不包含 `shipping_order_extraction.v1` 整包契约;唯一模型契约为 `shipping_order_extraction.unit.v2`。 +**阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试只维护唯一 Manifest 契约。 + +### L5 紧凑模型契约(2026-07-22) + +- 唯一 Manifest 只发送一个 String 类型 `execution_manifest`,当前 Document 位于 `document`,结构化表格位于 `structured_table_candidates`。候选只含页/表/行列、稳定 field_id、value、quote、status 和 issues,不含 HTML、bbox、token、cell_id、evidence_ref 或内部 field_code。 +- PDF Document 在 ready MinerU 快照存在时,`document.extracted_text` 改用按页排序的 MinerU 非表格文本块,并将 HTML 网格转换为 TSV;同时设置 `text_source=mineru`。快照不可用或无可用文本时保留旧解析文本并设置 `text_source=legacy`。两条路径均不向 Dify 发送 HTML、bbox 或 Provider 原始响应。 +- `status=candidate` 的字段策略为 `suggested`,仅供 LLM 补充与组合;`status=accepted` 的字段策略为 `locked`,模型不得删除、改值或换字段,后端会二次比对拒绝覆盖。 +- 唯一 accepted 表格覆盖全部 required Header/Line 字段且无问题码时,后端直接生成订单并零 Provider;needs_review/candidate 候选永不触发该路径。人工真值暂缓期间,生产解析器仍固定输出 needs_review,因此不宣称达到 95%,也不据此自动 accepted 或自动建单。 +- L5 工程 Review 已通过:后端 L0-L5 相关回归 `130 passed`,前端生产构建通过。真实样本准确率、覆盖率和性能指标因人工真值延期,不计为本阶段已验收。 +- 自动建单策略列由增量迁移 `a76f8091a2c2` 修复结构漂移:若数据库已记录旧迁移但 `shipping_order_schemas.auto_creation_policy_json` 实际缺失,则安全补列;已正确存在该列的环境只推进版本,不重复执行 DDL。部署验收必须同时核对 Alembic head 与实际列。 + +**L5 Dify 手工配置**:管理员按 `order-extraction-workflow-dify-guide.md` 完成唯一画布的节点修改与画布测试。禁止按字段存在自动判断输入格式,或把其他文档集合混入同一次模型调用。 + +### L6 证据裁决与诊断(2026-07-22) + +- 动态 Observation 新增 `evidence_ref` 和 `evidence_metadata_json`,迁移 head 为 `a70f8091a2b6`。文本证据保存不可逆 quote hash 引用;邮件头保存受控 option 引用;accepted 表格证据保存 `Document/Page/Table/Row/Column/Cell` 定位。 +- 旧 `PDF/EML -> extracted_text -> 猜列` 解析结果不再作为 `evidence_verified` 的 backend_table Observation。检测到纯文本表格时仅记录 `plain_text_table_has_no_cell_evidence`,保留模型逐字证据和业务候选,但强制 needs_review。 +- 只有 Run 冻结的 `mapping_status=accepted` 且同时存在稳定 `cell_id/evidence_ref` 的字段才能成为 `layout_schema_mapping` Observation。needs_review 表格记录 `layout_table_needs_review`;Document 对不上记录 `layout_candidate_document_mismatch`。 +- Layout 行关联只允许同 Document 的内部料号、客户料号、AWS 料号、Reservation、Line No 或 PO 等强身份字段。Qty、价格、日期等常见值不能用于跨 Document 关联,避免相同数量串值。 +- accepted layout 与模型值冲突时保留双方 Observation,由冻结 Schema 的 `cross_source_conflict` 门禁阻断;模型 confidence 不会提升版面可信等级。 +- Candidate 冲突携带脱敏机器可读原因,现有任务解析卡片以四语言展示。管理员诊断只返回 accepted/traceable Observation 计数、比例及 issue code 计数,不返回值、quote、evidence_ref、cell_id 或正文。 +- L6 Review 证据:相关回归 `128 passed`,迁移往返通过,Alembic 唯一 head 为 `a70f8091a2b6`,前端生产构建通过,静态搜索确认生产持久化不再生成旧 `backend_table` verified Observation。 + +**L6 验收结论**:工程门禁通过。当前生产布局候选仍因人工真值延期固定 needs_review,因此不会发生无真值 cell 自动 accepted;真实样本“accepted 证据追溯率 100%”与“错误自动建单为 0”的质量统计仍延期到 L7,不能用构造测试冒充真实质量达标。 + +**L6 Dify 手工配置**:无需新增节点或变量。唯一画布继续遵守 locked/suggested 字段策略;Dify 不生成 `evidence_ref`、不判断 cell 是否 accepted、不把模型 confidence 当证据等级,也不负责管理员诊断。 + +### L7 影子与正式切换准备(2026-07-22) + +- 已删除 Worker 的 Profile/纯文本确定性零 Provider 路径。现在只有完整 `mapping_status=accepted` layout 表格可以跳过 Provider;纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。 +- Profile 仍可生成不含 HTML/bbox/token 的紧凑候选供模型参考,并继续执行零 Qty 删除等候选清洗,但未获得 accepted cell 前不能直接生成订单。 +- 自动建单只能在质量门禁满足时由 Schema 策略开启;它不依赖 Dify 输入格式开关。 +- L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过,Alembic 唯一 head 为 `a72f8091a2b8`,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。 + +**L7 当前验收结论:未通过,不得开启自动建单。** 缺少人工单元格真值、真实字段准确率/召回率、解析性能指标、100 个影子 Run、20 个测试环境真实 Run、业务/技术负责人批准及 Dify 实际配置验收。当前完成的是安全切换准备,不是 L7 完成。 + +人工真值已明确延期后,工程侧新增不可绕过的 L7 质量批次门禁:批次锁定 Owner、当前发布 Schema 与阈值版本;同一真实 Run 必须由两名不同管理员提交完全一致的匿名计数才进入指标,至少 100 个一致样本且 precision>=99.5%、recall>=98%、错误合并/拆分各<=0.5%、错误自动建单为 0,之后还需不同账号分别完成业务与技术批准。首次批准后标签及对应角色批准均不可变。Run 创建时冻结质量门禁事实,Worker 执行前再次核验 Owner、Schema、阈值和指标。当前无人工真值即不会产生可选批准批次,管理端自动建单保持禁用。 + +**L7 Dify 手工配置顺序**:先完成本文要求的人工真值与影子指标;再按 Dify 手册完成唯一画布并发布;随后保持自动建单关闭,完成不少于 20 个测试环境真实 Run;书面批准后才允许开启自动建单。任一步失败立即关闭自动建单并修复画布或规则。 **阶段 7 影子验收与启用步骤(管理员执行)**: @@ -97,7 +136,11 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open 3. 所有阻断冲突必须保留双方 document/quote 证据;失败单元、预算阻断、熔断和部分成功必须可在管理员诊断定位,且诊断响应不得包含正文、orders、Prompt 或凭据。 4. 达标并经业务负责人、技术负责人书面批准后,在入口 Agent Runtime Binding 开启 `auto_create_enabled=true`。先在测试环境运行不少于 20 个真实脱敏 Run,再发布生产;任一错误建单立即关闭开关,已生成 Task 按既有人工修订/作废流程处理。 -**阶段 7 Dify 手工配置**:确认 Start 只含 `execution_manifest`,所有 Code/LLM/End 节点只接受 `shipping_order_extraction.unit.v2`;删除任何按旧 `documents[].documents[]` 遍历、整封邮件拼接、旧 v1 判断、跨附件合并和画布内自动建单逻辑。End 只输出当前 Unit 的 `orders`。 +**阶段 7 Dify 手工配置**:确认 Start 只含 String 类型 `execution_manifest`,所有 Code/LLM/End 节点只接受本手册定义的唯一 Manifest;删除任何按文档集合遍历、整封邮件拼接、输入格式判断、跨附件合并和画布内自动建单逻辑。End 只输出当前 Unit 的 `orders`。 + +**L7 第 4 阶段工程补充验收(2026-07-22)**:人工编辑 Candidate 的业务摘要时,系统在 `structured_result_json.manual_review_history` 追加编辑前摘要、冲突、校验状态、编辑人和编辑时间,避免“修订后清空冲突”丢失审计。自动建单 Binding 和每次 Run 均冻结 `quality_batch_id`;创建 Run 与 Worker 开始执行时都重新校验该批次的 Owner、Schema、阈值和双人批准状态。`auto_create_enabled=true` 的生产 Run 禁止作为影子质量标签样本,防止用生产结果反向证明质量。迁移 head 为 `a77f8091a2c3`;阶段回归为 `129 passed`,迁移往返和 `git diff --check` 通过。 + +**L7 状态不变**:以上仅完成工程硬门禁。人工真值、100 个影子 Run、Dify 实配验收、20 个测试环境真实 Run 及业务/技术双人书面批准完成前,必须保持 `auto_create_enabled=false`。 ## 2026-07-21 文档版面结构化升级路线(L0-L7) @@ -107,14 +150,31 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open | 阶段 | 目标 | Review 阻断点 | 通过标准 | | --- | --- | --- | --- | -| L0 契约与基线 | 冻结 `shipping_document_layout.v1`、人工真值和指标定义,完成样本/解析引擎评测准备 | 契约模板耦合、坐标不统一、ID 不稳定、样本类型缺失、依赖风险未评审 | 契约测试通过;至少 30 份脱敏文档完成人工单元格真值;覆盖原生/扫描 PDF、EML HTML、跨页、多表、表头后置等类型;候选解析引擎有同集评测证据 | +| L0 契约与基线 | 冻结 `shipping_document_layout.v1`、人工真值和指标定义,完成样本/解析引擎评测准备 | 契约模板耦合、坐标不统一、ID 不稳定、样本类型缺失、依赖风险未评审 | 工程契约/评测器通过后可继续建设非生产生命周期;至少 30 份脱敏文档人工单元格真值及完整类别覆盖仍是字段准确率、自动接受和生产切换的硬门禁 | | L1 生命周期 | 持久化布局版本、状态、checksum、质量结果并建立幂等重解析 | 数据库迁移、Worker 租约、超大 JSON、解析版本漂移 | 迁移往返、幂等、中断恢复、大小上限与错误码全部通过 | | L2 原生 PDF | 提取真实词元坐标并恢复有框/无框表格 | PDF 绘制顺序、字体编码、无框线、多表、页眉页脚、旋转/XFA | 表格检测召回率 >=98%;单元格归行归列准确率 >=99.5%;P95 <=5 秒 | | L3 OCR/EML HTML | 扫描 PDF 坐标 OCR 和 HTML DOM 表格输出同一契约 | OCR 易混字符、低分辨率、rowspan/colspan、转发重复、混合 PDF 重复文本 | 低置信高风险字符全部复核;HTML 跨行跨列正确;10 页扫描 PDF P95 <=30 秒 | | L4 Schema 映射 | 按 Run 锁定 Schema 映射表头/列并支持跨页、表头后置 | 别名碰撞、重复列、跨页误合并、客户特例硬编码 | accepted 字段均有 cell_id;高风险字段错误归列自动接受数为 0 | -| L5 Dify unit.v3 | 传入结构化表格和非表格文本;确定性完整时跳过 Provider | LLM 重做表格、覆盖确定性字段、契约重复序列化 | 模型不再猜列;完整确定性文档零 Provider 调用;调用量下降 >=50% | +| L5 Dify 紧凑契约 | 传入结构化表格和非表格文本;确定性完整时跳过 Provider | LLM 重做表格、覆盖确定性字段、契约重复序列化 | 模型不再猜列;完整确定性文档零 Provider 调用;调用量下降 >=50% | | L6 裁决与诊断 | 列证据门禁、冲突原因、管理员诊断和现有 UI 展示 | 无 cell 证据接受、跨 Document 串值、模型置信度冒充证据可信度 | accepted 证据可追溯率 100%;needs_review 原因机器可读;错误自动建单为 0 | -| L7 影子与切换 | 离线回归、影子运行、确定性裁决启用和 unit.v3 正式切换 | 人工真值不足、质量/性能未达标、纯文本猜列残留 | 全部质量/性能指标达标;无 unit.v2 和纯文本猜列运行路径;真实 API 验收通过 | +| L7 影子与启用 | 离线回归、影子运行和确定性裁决启用 | 人工真值不足、质量/性能未达标、纯文本猜列残留 | 全部质量/性能指标达标;无纯文本猜列运行路径;真实 API 验收通过 | + +### L0-L7 最终阶段 Review 矩阵(2026-07-22) + +本轮采用用户明确确认的例外推进规则:**人工单元格真值暂缓时,只允许继续后续阶段的工程建设,不允许提升布局可信级别、标记质量验收通过、自动 accepted、自动建单或对外声明准确率。** 因此“进入下一阶段”只表示上一阶段的工程阻断项已经关闭,并不表示上一阶段的真实质量门禁已经通过。任何后续阶段都不得绕过前序未完成的质量门禁。 + +| 阶段 | 工程 Review | 质量/真实环境验收 | 关键证据 | 遗留阻断 | 推进结论 | +| --- | --- | --- | --- | --- | --- | +| L0 契约与基线 | 通过 | 未通过 | 契约、checksum、bbox/引用闭合、评测器和匿名覆盖测试通过;30 PDF MinerU 结构审计完成 | 无人工 cell 真值;扫描/旋转/XFA/跨页等类别未完整覆盖;XFA fixture `docs/prototype/4510038672.pdf` 缺失 | 只允许进入非生产工程 L1;禁止可信级别提升 | +| L1 生命周期 | 通过 | 不适用真实准确率 | 布局版本、独立 Job、幂等、lease、恢复、迁移往返、管理员脱敏诊断通过 | 真实 Provider 长时间运行稳定性仍属于部署观察项 | 可进入 L2 工程建设 | +| L2 原生 PDF | 通过 | 未通过 | PDFium 真实字符坐标、严格文本对齐、OpenCV 双门禁、逐表隔离和降级测试通过 | 表格召回率>=98%、归行归列>=99.5%、P95<=5 秒未由真值证明;XFA 实例缺失 | 可输出 `needs_review` 候选并进入 L3;禁止 accepted | +| L3 OCR/EML HTML | 通过 | 未通过 | OCR 多边形/置信度、OpenCV+全文本门禁、HTML 白名单、DOM rowspan/colspan、摘要隐私测试通过 | 扫描真实字符质量、HTML 真实跨度准确率、10 页扫描 P95 未验收 | 可进入 L4 候选映射;全部保持 `needs_review` | +| L4 Schema 映射 | 通过 | 未通过 | Run 冻结 Schema、稳定 field_id、cell/token 引用、表头后置、重复列、零 Qty、显式 continuation 测试通过 | 真实字段映射准确率和错误归列率无人工真值证据 | 可进入 L5 紧凑候选;禁止自动接受 | +| L5 紧凑契约 | 通过 | Dify/性能未通过 | 唯一 Manifest、Run 冻结、紧凑候选、无布局载荷泄漏、locked 字段保护、accepted 完整表零 Provider测试通过 | Dify 画布需管理员手工验收;真实 Provider 调用下降>=50%未测 | 可进入 L6 后端裁决;生产保持显式开关 | +| L6 裁决与诊断 | 通过 | 真实质量未通过 | Observation 证据引用、纯文本伪证据阻断、跨 Document 强身份关联、冲突保留、管理员脱敏诊断和迁移测试通过 | 真实 accepted 追溯率、错误自动建单统计尚无质量批次 | 可进入 L7 工程门禁;自动建单继续关闭 | +| L7 影子与启用 | 通过 | 未通过 | 质量批次、双人一致标签、首次批准冻结、当前 Schema、双角色批准、Run 冻结、Worker 二次校验、管理 API 脱敏和 UI 门禁通过 | 人工真值、100 个影子 Run、20 个测试环境真实 Run、性能指标、Dify 实配、业务/技术批准均缺失 | 不得开启自动建单,`auto_create_enabled=false` | + +最终工程证据分两组执行:主链路 L0-L7 回归 `247 passed`;L0 契约/评测/覆盖/OpenCV/XFA 等补充审计 `102 passed, 1 skipped`,唯一 skip 为缺少 XFA PDF fixture。前端生产构建通过,Alembic 唯一 head 为 `a72f8091a2b8`,`git diff --check` 通过。上述结果只证明工程实现与安全降级,不证明真实订单准确率达到 95%。 ### L0 版面契约 @@ -155,7 +215,7 @@ ID 必须由内容哈希、页/表/行/列序等稳定组成部分生成,禁 | PNG/JPG/GIF | 18 | | 低文本量扫描 PDF 候选 | 0 | -这批样本已满足“至少 30 份 PDF 文档”的数量条件,并可用于原生 PDF、EML HTML、多附件和部分跨模板评测;但尚未证明以下类别覆盖:扫描 PDF、低清晰度/倾斜、旋转页面、OCR 易混字符、明确跨页连续表、表头后置、多层表头和人工单元格真值。因此 L0 当前状态为 **工程契约完成、样本验收未通过**,不得进入 L1。 +这批样本已满足“至少 30 份 PDF 文档”的数量条件,并可用于原生 PDF、EML HTML、多附件和部分跨模板评测;但尚未证明以下类别覆盖:扫描 PDF、低清晰度/倾斜、旋转页面、OCR 易混字符、明确跨页连续表、表头后置、多层表头和人工单元格真值。因此 L0 当前状态为 **工程契约完成、准确率/样本验收延期**。按项目交付优先级允许继续建设不提升业务可信级别的 L1 生命周期,但不得据此声明 95% 准确率、开放 cell 自动 `accepted` 或跳过后续影子验收。 原始真实样本只允许在受控目录做只读评测。仓库只能提交脱敏后的不可逆构造样本、真值 JSON 或统计结果,不得提交真实 EML/PDF、邮件地址、订单号、客户名称或附件正文。 @@ -251,11 +311,83 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏 使用内存中的推荐别名副本复评(不保存数据库)后,30/30 PDF 解析成功,47 张表中 23 张命中表头;`part_number` 命中从 3 次提升到 22 次,`customer_part_number` 承接 39 次 Material,但 Qty 仅命中 5 次,61 条候选行仍无 `part_number + qty` 同行完整结果。该证据说明三料号配置修正是必要条件,但不是充分条件;剩余主要问题是 Qty 表头变体、表头污染及表格行列恢复质量,不能直接归因于 LLM。 -邮件关系匿名统计显示:16 封邮件中 15 封含 PO、8 封含 Reservation、7 封两者同时出现;14 封包含多个 PO,没有一封满足“唯一 PO + 唯一 Reservation”。因此禁止把邮件 Reservation 广播到同一 Intake 的全部 PDF 行。后续 unit.v3 关系契约只允许明确 `PO -> Reservation`、`part_number -> Reservation`,或经过唯一性证明的一对一关系;多 PO/多 Reservation 且无明确关系时进入复核。 +邮件关系匿名统计显示:16 封邮件中 15 封含 PO、8 封含 Reservation、7 封两者同时出现;14 封包含多个 PO,没有一封满足“唯一 PO + 唯一 Reservation”。因此禁止把邮件 Reservation 广播到同一 Intake 的全部 PDF 行。唯一关系契约只允许明确 `PO -> Reservation`、`part_number -> Reservation`,或经过唯一性证明的一对一关系;多 PO/多 Reservation 且无明确关系时进入复核。 -本次 Review 结论为:HTML 网格和冻结别名映射代码通过单元测试与安全 Review,但真实覆盖验收未通过,L0 仍保持“工程契约完成、样本/真值/Provider 准入未完成”。不得因为阶段 0-7 的既有 unit.v2 路线已实现而跳过 L0-L4 门禁。下一步先由管理员按 Dify 手册把 Material 系列别名迁移到 `customer_part_number`,再实现结构化表格候选与非表格短文本的补充契约;Dify 不得重新猜测已确定列,明确 AWS 料号必须优先于客户 Material。 +本次 Review 结论为:HTML 网格和冻结别名映射代码通过单元测试与安全 Review,但真实覆盖验收未通过,L0 仍保持“工程契约完成、样本/真值/Provider 准入未完成”。不得跳过 L0-L4 门禁。下一步先由管理员按 Dify 手册把 Material 系列别名迁移到 `customer_part_number`,再实现结构化表格候选与非表格短文本的补充契约;Dify 不得重新猜测已确定列,明确 AWS 料号必须优先于客户 Material。 -订单字段语义还必须允许模板级覆盖,不能仅凭裸表头文字建立全局结论。例如已确认模板中,`Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是正确映射;这不是字段错位,也不得被全局 Schema 或 LLM 重新纠正。`document_layout/order_profile.py` 以表头网格精确结构指纹选择版本化 Profile,并只运行注册的固定列解析器;不做相似模板匹配,不执行自由正则或脚本。Profile 命中后优先于全局精确别名,未命中才进入通用 Schema 候选路径。MinerU 已丢失同行关系的模板只能标记 `unsupported_row_structure` 并转复核,不能用固定列配置伪装修复。当前 Profile 仍是纯执行契约,尚未持久化或接入生产 Worker;在该集成完成前不能宣称模板规则已在正式 Run 生效。 +订单字段语义还必须允许模板级覆盖,不能仅凭裸表头文字建立全局结论。例如已确认模板中,`Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是正确映射;这不是字段错位,也不得被全局 Schema 或 LLM 重新纠正。`document_layout/order_profile.py` 以表头网格精确结构指纹选择版本化 Profile,并只运行注册的固定列解析器;不做相似模板匹配,不执行自由正则或脚本。Profile 命中后优先于全局精确别名,未命中才进入通用 Schema 候选路径。MinerU 已丢失同行关系的模板只能标记 `unsupported_row_structure` 并转复核,不能用固定列配置伪装修复。 + +**Profile 持久化与运行接入 Review(2026-07-21)**:`shipping_order_document_profiles`、管理 API、发布唯一索引、Schema/稳定 field_id 门禁、Run `snapshot_version=2` 冻结和 Worker 精确执行已经实现。 + +**Profile 可视化治理 Review(2026-07-22)**:管理端 `/admin/shipping-order-document-profiles` 只展示 ready MinerU 样本文档及展开后的 cell 文本,不返回 HTML、bbox、全文或结构指纹。管理员选择表格、表头行、数据起始行、行结构和 Schema 明细字段;页面只允许 `direct` 与已注册 `temp_internal_parts` 解析器,阻止同一目标字段跨列重复映射。结构指纹始终由后端从持久化 HTML 计算,浏览器提交值无效。草稿支持乐观锁更新、发布、删除;不可变版本支持复制为下一草稿和退役。复制后的草稿必须选择样本重新确认映射才能更新,不允许直接编辑 JSON、HTML、正则、脚本或结构指纹。 + +MinerU 生产捕获固定使用 `pipeline`,通过 `/tasks` 异步提交、状态轮询和 `/result` 取回结果,不使用同步 `/file_parse` 长连接。Intake 不再内联调用 MinerU:它在持久化 Document/派生 FileAsset 后,同事务创建独立布局版本和 `shipping_document_layout` Job;布局 Worker 再读取对象存储并调用 Provider。`SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false` 时不创建布局 Job;启用后只保存 `shipping_document_table_snapshot.v1` 的页/整表 bbox、HTML 表格与能力摘要,不保存 task 原响应、model output、content list 或非表格文本块。默认每个 Intake 最多 4 个支持文档;超量建立 `unsupported` 审计版本。所有 HTML/bbox 在 Dify Manifest 编译前剥离,仅 Profile 映射后的 `field_id/value/quote` 紧凑候选可进入 Dify。 + +### L1 布局版本与独立任务生命周期 + +L1 已于 2026-07-22 完成工程 Review: + +- `shipping_document_layout_versions` 保存单文档递增版本、源内容哈希、parser identity、状态、checksum、大小、质量问题、Job/lease、尝试次数和时间戳。`ShippingNoticeDocument.current_layout_version_id` 只指向 `ready/needs_review` 成功版本,失败版本不能覆盖上一次可用结果。 +- parser key 固定包含 `mineru:pipeline:shipping_document_table_snapshot.v1:{revision}`。提升 `SHIPPING_NOTICE_LAYOUT_PARSER_REVISION` 后旧结果不再复用;迁移自历史单 JSON 的快照标记为 `:legacy`,后续会生成新版本。 +- 同一 Document 只允许一个 `queued/running` 活动版本;Worker lease 使用 `job_id:attempt`。超时回收或重试会清除/轮转 lease,旧 Worker 无权回写;尝试耗尽时 Job 与布局版本同步失败并记录机器问题码。 +- payload checksum 对规范 JSON 计算 SHA-256;超过 `SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES` 时只保留失败审计,不保存超大正文。管理员列表/重解析 API 只返回状态、大小、表数量、问题码和时间,不返回 HTML、bbox、全文、Provider 原始响应或内部异常。 +- Document 删除通过 current 引用 `ON DELETE SET NULL` 与版本 `ON DELETE CASCADE` 安全收口;旧 `layout_snapshot_json` 已从运行模型移除,避免单 JSON 与版本表双真相。 +- 当前 `ready` 仅表示布局可供 Profile/候选流程使用,不代表每个 cell 已获人工真值或可作为高风险字段 `accepted` 证据。人工真值暂缓不影响 L1 生命周期运行,但继续阻断准确率声明和自动接受。 + +管理员接口为 `GET /api/admin/shipping-notice/documents/{document_id}/layout-versions` 与 `POST /api/admin/shipping-notice/documents/{document_id}/layout-reparse`。L1 不改变 Dify 输入/输出契约,也不要求修改 Dify 画布。 + +### L2 原生 PDF 结构候选 + +L2 工程实现已于 2026-07-22 完成,parser revision 提升为 `v2`: + +- 使用项目既有 `pypdfium2` 直接从 PDF bytes 提取页面尺寸、旋转、原生字符和真实 bbox,不新增依赖、不写临时文件;扫描/空白 PDF 只产生无字符页面,不伪造 OCR/token。 +- MinerU `pipeline` 继续提供整表 bbox 与 HTML 行列。原生字符先走严格唯一文本对齐:必须唯一、同视觉行、连续且不与其他 cell 共享 glyph;结果保存实际 glyph 索引并转换为稳定 `LayoutToken` 引用。 +- 唯一文本无法完整覆盖时,只对严格有框表尝试 OpenCV 多参数网格共识,并要求独立 PDF 文本层对全部非空 cell 100% 匹配;无框、重复值、形状不一致或空证据均不生成 cell。 +- 通过契约校验的候选内嵌为 `layout_candidate: shipping_document_layout.v1`;只持久化表格区域使用的 token,非表格全文和页面图不入库,避免 payload/token 膨胀。 +- 所有 L2 候选的 Document/Table 状态固定为 `needs_review`,并包含 `native_pdf_cell_truth_deferred` blocking issue。它不改变现有 MinerU HTML/Profile 运行分支,不进入 Dify,也不能成为高风险字段自动 `accepted` 证据。 +- 单表失败按 table_id 隔离,不抹除同页其他成功候选;PDFium/OpenCV 候选失败只追加安全问题码,不丢弃已成功取得的 MinerU HTML 快照。 + +L2 工程回归已覆盖真实空白 PDF、唯一/重复文本、glyph/token 追溯、有框表双门禁、逐表故障隔离、runtime 降级、版本轮转及既有订单抽取链路。由于人工真值被延期,表格检测召回率、单元格归行归列准确率和真实 P95 尚无可审核依据,因此 L2 当前状态为 **工程完成、质量验收延期**;按本轮明确授权只允许进入保持 `needs_review` 的 L3 工程建设,不得提升 accepted、自动建单或宣称达到 95%。本阶段 Dify 无需修改。 + +### L3 扫描 PDF OCR 与 EML HTML + +L3 工程实现已于 2026-07-22 完成,parser revision 提升为 `v3`: + +- 扫描 PDF 不再复用只输出纯文本的 `edkb_system.ocr_text` 包装。布局专用适配器直接读取 RapidOCR 的“多边形 + 文本 + 置信度”,按渲染图和 PDF 页面尺寸映射为真实页面 bbox;默认只保留置信度不低于 0.8 的 OCR 行。 +- OCR 行本身不能证明列归属。只有 MinerU HTML 网格、OpenCV 多参数有框表共识和全部非空 cell OCR 文本 100% 一致时,才生成 `source=ocr` 的 LayoutToken/LayoutCell 候选。OCR 模型缺失、低置信、无框表、文本不一致或 token 缺失均只记录问题码,不回退纯文本猜列。 +- EML multipart/alternative 即使优先使用 plain 正文,也会额外读取对应 HTML table。临时片段只保留 `table/thead/tbody/tfoot/tr/th/td`、cell 文本和 `rowspan/colspan`;script/style/img/svg/object/embed/iframe/template 直接删除,链接、事件、样式及其他属性全部移除。 +- EML HTML 使用 DOM 逻辑行列坐标构造 `shipping_document_layout.v1`,不冒充浏览器像素。rowspan/colspan 由 DOM 网格证明;状态固定 `needs_review`,并记录 `html_logical_coordinates_only` blocking issue。 +- email_body 内容哈希同时覆盖正文文本和清洗后的 HTML table,避免 plain 不变而表格变化时复用旧布局。临时 `body_html_tables` 在 Document 布局生成后从 meta 删除,且结构化 Intake 摘要采用字段白名单,不保存或返回 HTML。 +- OCR/HTML layout 继续只存在 HXOPS 布局版本内部,不进入 Dify Manifest;主动内容、页面图、OCR 引擎原响应和非表格 HTML 均不入库。 + +L3 回归覆盖 OCR 坐标缩放、低置信过滤、引擎不可用、有框/无框与全文本门禁、最终 OCR token/cell 引用、HTML 主动内容清理、合并格、无效表、Document hash、端到端版本持久化和摘要隐私。由于人工真值与真实扫描样本延期,低置信高风险字符覆盖率、HTML 真实样本跨度正确率和 10 页扫描 PDF P95 暂无可审核依据,因此 L3 当前状态为 **工程完成、质量验收延期**。Dify 无需修改。 + +### L4 冻结 Schema 与真实 cell 证据映射 + +L4 工程实现已于 2026-07-22 完成: + +- 现有表头映射器已拆为 `HTML -> HtmlGrid` 与 `HtmlGrid -> frozen Schema` 两层。layout.v1 Table 可转换为保留真实 `cell_id/rowspan/colspan/role` 的 Grid,继续复用既有精确别名、后置表头、重复列、污染表头、类型规范化、Reservation 安全规则和显式零 Qty 删除。 +- `map_layout_document_to_schema` 输出每张表的 `page_no/table_id/continuation_of/layout_status/mapping_status`,每个字段包含冻结 `field_id/field_code`、真实 layout `cell_id/token_ids` 和 `layout:{document}:p{page}:{table}:{cell}` evidence_ref。 +- 跨页关系只接受 layout.v1 契约中显式且指向更早页面的 `continuation_of`;不会根据相似表头、相同列数或相邻页自动猜测拼表。 +- Run 输入快照提升为 `snapshot_version=3`,在创建时使用同一冻结 Schema 编译并保存 `layout_schema_candidates`。后续 Schema/Profile 修改不会污染已排队 Run。 +- 当前所有 L2/L3 表均为 `needs_review`,所以映射状态固定 `candidate` 并附 `layout_table_not_accepted`;不会被确定性 Worker、自动建单或 Dify 消费。Manifest 明确删除 `layout_snapshot` 和 `layout_schema_candidates`。 +- 管理员布局版本摘要的 table_count 优先统计统一 layout_candidate 表数量,仍不返回 HTML、bbox、token、字段值或正文。 + +L4 回归覆盖真实 cell/token 引用、后置表头、重复目标列、零 Qty、显式跨页、Run v3 冻结/重放、Profile 旧路径以及 Dify 隔离。当前没有任何 accepted 布局字段,因此“高风险错误归列自动接受数”为 0;但真实字段映射准确率仍因人工真值延期而无审核证据。L4 当前状态为 **工程完成、质量验收延期**,不得将 candidate 提升为 accepted。本阶段 Dify 无需修改。 + +自动跳过 Dify 的门禁为:Run 冻结 Profile 的 `schema_version_id/target field_id/field_code` 与冻结 Schema 完全一致;一张 Document 仅一张表形成有效 Profile 结果;该表仅一个 Profile 精确命中;没有 unsupported/multiple/snapshot mismatch 问题;所有非删除行均为 parsed 且包含 `part_number + qty`。多表命中不自动拼单,缺字段不把部分候选冒充完整订单。零 Qty 行按业务确认删除。Reservation 可以由邮件关系单元补充,但最终门禁不因此放宽。 + +环境变量: + +| 变量 | 默认值 | 说明 | +| --- | --- | --- | +| `SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED` | `false` | 是否在 Intake 异步解析阶段调用 MinerU;部署验收前保持关闭 | +| `SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL` | 空 | MinerU 服务根地址;由环境注入,不写入代码/文档真实生产地址 | +| `SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS` | `10` | 建连超时 | +| `SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS` | `300` | 配置上限;运行时还会受 Intake Job 总超时收紧 | +| `SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE` | `4` | 单 Intake 最多调用 MinerU 的文档数 | +| `SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY` | `2` | 单 Intake MinerU 最大并发 | +| `SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS` | `1000000` | 单文档持久化表格 HTML 总字符预算 | #### MinerU L0 适配器 @@ -312,6 +444,14 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏 OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工真值评测对象,不能单独支撑 95% 目标、不能替代无框表解析、不能接入自动建单。只有在人工 cell 真值上证明错误归列自动接受数为 0,并满足 L2/L4 阈值后,才允许将通过双门禁的子集转换为正式 `LayoutCell`。 +#### 严格原生文本 cell 候选复评(2026-07-22) + +`document_layout/text_cell_alignment.py` 新增了仅供 L0 人工标注辅助的严格候选算法,不接入 Intake Worker、Profile、Dify、Observation 或自动建单。它只在 MinerU 整表区域内接受 PDF 原生字符层的唯一文本匹配,并同时要求字符位于同一视觉行、阅读顺序一致、水平间距连续、与其他 cell 不共享 glyph。空 cell、重复 Qty/料号、文本缺失、页面外字符框、跨行拼接和重叠子串全部返回机器问题码;禁止选择第 N 个重复值、裁剪坏坐标或按 HTML 顺序分配。 + +使用相同 30 份 PDF 重新执行匿名审计:MinerU 异步 `pipeline` 30/30 成功,共 47 张表、1089 个 HTML cell,仍为 0 份原生完整 cell bbox。OpenCV 多参数共识产生 10 张几何候选表,其中 6 张通过独立 PDF 文本层门禁,但只覆盖 3 份完整样本文档的部分表格;其余表格仍无可信框。严格原生文本算法在可解析的 42 张表、1002 个 cell 上匹配 437 个,仅 1 张表完整匹配,没有一份文档的全部表格完成。主要阻断为真实空 cell、重复文本、MinerU HTML 与 PDF 原生文本差异,以及文本跨 cell/跨行不连续。 + +因此“让业务人员只确认字段值、不确认 bbox”不能形成 `shipping_document_layout_annotation.v1` 真值;当前自动候选最多减少少量框选工作,无法完成 30 份文档人工 cell 真值。L0 仍为 **代码契约与候选评测通过、人工真值和类别覆盖未通过**。后续只能选择人工标注完整表格,或引入独立 TSR 候选并在同一人工真值集评测;在此之前自动接受继续关闭。 + ### L0 Review 清单 1. 契约 Review:解析器无关、坐标统一、引用闭合、ID/checksum 稳定。 @@ -319,7 +459,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 3. 依赖 Review:许可证、镜像体积、Windows/Linux 一致性、CPU/内存和安全风险。 4. 指标 Review:检测、归行归列、字段映射分开计算,不能用最终订单正确掩盖版面错误。 5. 隐私 Review:真实原文不进仓库、不进日志、不进入测试失败输出。 -6. 门禁 Review:L0 全部阻断项关闭后方可实施数据库和运行时 L1。 +6. 门禁 Review:默认要求 L0 全部阻断项关闭后方可实施数据库和运行时 L1;本轮因用户明确批准人工真值延期,只允许继续不提升可信级别的工程建设,未完成质量项继续向后传播为硬门禁。 ### 订单抽取进度与诊断契约(阶段 0 冻结) @@ -376,7 +516,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 订单抽取服务的技术约束由货代 Agent Catalog 的 `required_runtime_capabilities.shipping.order_extraction` 声明;管理员在应用侧从启用的内部 Dify Workflow 中选择执行器,业务用途以 Runtime Binding 为准。 -3. Dify Workflow Start 节点只增加一个 string 输入:`execution_manifest`。该 JSON 字符串固定含 `contract_version`、`run.run_no`、`integrity.input_snapshot_hash`、`extraction_contract`、`documents`、`readonly_hints`;必须按传入内容解析,不能回读 HXOPS 可变文档。`extraction_contract.fields[]` 仅包含 `collection_mode=llm_extraction` 的字段;Workflow 只能返回其中列出的稳定 `field_id`,不得提取、补写或回传 `general_context/deterministic_context` 字段(包括发件人邮箱和企业域名)。`documents` 会显式剔除 `deterministic_context`;`readonly_hints` 仅按已发布 Schema 策略提供按 Intake 分组的提示/关联信息,Dify 不得将其中字段加入 `orders.header_fields` 或 `lines.fields`,也不得从正文、`Reply-To`、签名或转发内容重建被排除字段。 +3. Dify Workflow Start 节点只增加一个 string 输入:`execution_manifest`。该 JSON 字符串固定含 `run.run_no`、`unit`、`integrity.input_snapshot_hash`、`extraction_contract`、`document`、`structured_table_candidates` 和 `readonly_hints`;必须按传入内容解析,不能回读 HXOPS 可变文档。`extraction_contract.fields[]` 仅包含 `collection_mode=llm_extraction` 的字段;Workflow 只能返回其中列出的稳定 `field_id`,不得提取、补写或回传 `general_context/deterministic_context` 字段(包括发件人邮箱和企业域名)。`readonly_hints` 仅按已发布 Schema 策略提供当前单元提示/关联信息,Dify 不得将其中字段加入 `orders.header_fields` 或 `lines.fields`,也不得从正文、`Reply-To`、签名或转发内容重建被排除字段。 4. Workflow End 节点只输出结构化 `orders`;可以是数组,或 JSON 字符串形式的数组。推荐契约如下: ```json diff --git a/docs/funclist.md b/docs/funclist.md index 88186f97..1d12df5d 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -4,16 +4,25 @@ - 货代发货通知订单抽取只需指定内部执行器、超时与重试参数,不再重复勾选启用。 - 内部执行器禁止用户授权,Provider 绑定、删除和历史 Run 保持生命周期门禁。 - 用户授权、公开列表、工作台、收藏、默认应用、FAQ、指南、详情和普通 Chat 已全局排除内部执行器,并提供历史用户关系清理迁移。 -- 订单识别失败卡片支持“重新识别”:复用原 Run、冻结附件和 Provider 成功缓存,不要求用户重新上传文件。 +- 订单识别失败卡片支持“重试”:复用原 Run、冻结附件和 Provider 成功缓存,不要求用户重新上传文件。 +- 订单审核结果支持“按当前规则重新识别”:创建新的版本化 Run,重新冻结当前 Schema/Binding/Profile/ready 布局;旧候选只读保留,新版失败自动恢复旧版,只有当前版本可建单。 - 订单识别可观测进度已完成:Dify Workflow 事件采集、Run 脱敏阶段投影、用户时间线、服务端健康提示、终态会话待查看、管理员只读诊断审计和90天事件每日清理均已实现;自定义节点标题不持久化,用户端不暴露 Workflow/节点/Job/Provider。当前不要求手工修改 Dify Workflow。 - 文档级订单抽取优化:按 0–7 阶段实施。目标为确定性优先、一附件一抽取单元、邮件关系单元、受控并行 Dify、HXOPS 跨文档合并和影子验收,最终删除旧整单/全内容单次 LLM 模式;每阶段必须通过 Review 门禁后再进入下一阶段。 - 文档级订单抽取优化阶段 1 已完成:Run 冻结动态 Schema 驱动确定性表头映射、字段规范化和校验;别名碰撞/Reservation 禁用表头阻断保存发布,重复列进入复核;无契约不猜列,且不再广播文档 Reservation 或补默认 UOM。Dify 画布无需修改。 - 文档级订单抽取优化阶段 2 已完成:新 Run 同事务创建唯一抽取计划,邮件正文和每个附件形成独立、可恢复的持久化单元;单元具备局部状态机、尝试/结果/错误隔离和计划汇总,复合外键阻止跨 Intake 文档引用。Dify 画布暂不修改。 -- 文档级订单抽取优化阶段 3 已完成:完整确定性表格直接形成带逐字证据的动态订单并跳过 Dify;无法完整确定的单元改用 `unit.v2` 单文档清单,禁止看到兄弟附件或跨单元引用证据。Dify 需按技术手册手工更新输入解析。 +- 文档级订单抽取优化阶段 3 已完成:完整确定性表格直接形成带逐字证据的动态订单并跳过 Dify;无法完整确定的单元使用唯一单文档 Manifest,禁止看到兄弟附件或跨单元引用证据。Dify 需按技术手册手工更新输入解析。 - 文档级订单抽取优化阶段 4 已完成:单元以 2–4 并发调用 Dify,失败仅在该单元内指数退避重试;成功单元不重跑,attempt/latency 持久化,结果按冻结顺序汇总。管理端可配置并发、单元尝试次数和退避。 - 文档级订单抽取优化阶段 5 已完成:HXOPS 按唯一 PO 或 `(part_number, reservation_id)` 强身份跨文档合并,保留所有 Observation 并将值冲突交动态 Schema 裁决;弱身份不误合并。单元部分失败时成功结果继续提交,Run 转 needs_review。 - 文档级订单抽取优化阶段 6 已完成:支持模型单元预算、Provider 进程并发上限和短期熔断;管理员诊断可查看脱敏单元状态/尝试/耗时/错误码并保留访问审计,用户端不泄露内部信息。 -- 文档级订单抽取优化阶段 7 已完成:自动建单默认关闭,影子模式完整落 Candidate/证据但零 Task;批准后可在 Runtime Binding 显式开启,且所有既有安全门禁继续生效。旧整包 v1 契约已删除,真实脱敏样本验收阈值已文档化。 +- 文档级订单抽取优化阶段 7 已完成工程门禁、但质量验收延期:自动建单默认关闭,影子模式完整落 Candidate/证据但零 Task;只有当前 Schema 的达标质量批次和不同账号双角色批准全部满足后才可开启。人工真值、100 个影子 Run、20 个测试环境 Run 与 Dify 实配尚未验收,因此不得宣称阶段完成或达到 95%。 +- MinerU + 订单文档 Profile 运行基础已实现:Intake 持久化 Document 后创建独立版本化布局 Job,MinerU `pipeline` 不再阻塞 Intake;布局保存 parser revision/checksum/大小/质量/lease,失败版本不覆盖当前成功版本。版本化 Profile 绑定不可变 Schema 和稳定字段 ID,Run 冻结完整发布快照。唯一精确模板表且完整具备 `part_number + qty` 时由后端确定性解析并跳过该附件 LLM;模板级 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 合法,零 Qty 行删除。多表/多 Profile/结构漂移/Provider 失败均安全回退,布局 HTML 和坐标不进入 Dify。 +- PDF 模型输入优先使用 MinerU 分页文本块与表格 TSV,保留表头和行列关系;MinerU 不可用时回退原 `extracted_text`。Dify Manifest 仅携带紧凑纯文本,不包含 HTML、bbox、task 原响应或内部证据标识。 +- 订单文档 Profile 可视化治理已实现:管理员从 ready MinerU 样本文档选择表格、表头/数据行和受控列映射,可标记不支持的行结构;结构指纹仅由后端计算。支持草稿更新、发布、删除、新版本复制和退役,重复目标字段在前后端阻断;业务管理员无需编辑 JSON、HTML、正则或脚本。 +- L0 人工真值辅助继续保持非生产隔离:新增 PDF 原生字符坐标严格对齐候选,仅接受唯一、同视觉行、连续且非重叠文本;30 份真实 PDF 复评仍不足以自动生成完整 cell 真值,因此未开放 LayoutCell 自动接受、自动建单或 95% 准确率声明。 +- L1 文档布局生命周期已实现:Document 使用独立递增布局版本和当前成功引用;布局任务支持幂等调度、parser revision 防漂移、lease 防旧 Worker 回写、超时恢复、尝试耗尽、payload 大小门禁、级联删除、管理员脱敏诊断和显式重解析。人工真值延期不阻塞该生命周期,但继续阻断 cell 自动接受与准确率声明;Dify 无需修改。 +- L2 原生 PDF 工程能力已实现:PDFium 提取真实字符 bbox,MinerU HTML cell 通过唯一文本对齐或严格有框表 OpenCV+全文本门禁生成可追溯 token/cell 候选;只保存表格区域 token,失败逐表隔离,revision 升至 v2。候选固定 needs_review;人工真值、准确率和性能验收延期,因此未进入 OCR 自动接受,Dify 无需修改。 +- L3 OCR/HTML 工程能力已实现:RapidOCR 多边形坐标经页面缩放后,仅在 OpenCV 网格与全部 cell 文本一致时生成 OCR token/cell;EML HTML table 经主动内容白名单清理并按 DOM 合并格生成逻辑布局。email_body hash 覆盖清洗表格,HTML 不进入摘要/Dify,revision 升至 v3。候选固定 needs_review;真实扫描质量/P95 验收延期。 +- L4 Schema 证据映射已实现:layout.v1 Table 复用冻结 Schema 精确表头规则,字段保留真实 cell_id/token_ids/evidence_ref;支持后置表头、重复列阻断、零 Qty 和显式跨页 continuation。Run snapshot 升至 v3并冻结内部 candidate,Manifest 全部剥离;无 accepted 自动消费,真实映射准确率待人工真值。 # 智能HR请假管理功能清单 @@ -112,6 +121,11 @@ | 唯一订单 Schema 与动态字段基础 | 已实现 | 管理员以固定高度字段字典维护系统标识、版本显示名称、位置、格式和识别规则;两个名称不受“纳入当前版本”开关限制,未纳入字段配置可保存但不进入发布契约;系统标识可重命名且历史快照保留旧值,位置/类型与已发布版本保持安全门禁;管理端提供分页版本历史、严格只读快照、任意版本间服务端字段级差异、追加式配置审计时间线、版本实际使用统计和单次解析证据链;历史发布/退役版本可复制为新草稿,URL 可按业务版本号恢复;新版本移除下游引用字段时阻断发布 | | 通用上下文字段目录与运行时 | 已实现(阶段 3、5) | 复用订单解析字段目录,按通用上下文字段/订单信息/货品明细分组;迁移自动在当前草稿补齐发件人邮箱/企业域名两个完整字段配置,管理员审核后发布。首批受控来源为 EML From 邮箱/域名。Run 按 Intake 冻结规范值,Extraction 独立写入 Observation→Decision→FieldValue 与审计快照;缺失/非法/多地址不做其他来源兜底,公共域名保留真实值。Dify 契约和 documents 输入隔离确定性上下文;Schema 发布可审计地控制 `never`、受控不可逆 `redacted`、Run 冻结值 `confirmed_readonly`,并通过独立 `readonly_context` 只读输入按 Intake 传递。 | | Schema 驱动 Dify 订单解析 | 已实现 | Worker 向专用 Workflow 传入冻结 published Schema 与 Document;Workflow 按稳定 field_id 返回 Observation,后端完成类型校验、原文核验、跨文档裁决和类型化值持久化 | +| 订单文档解析 Profile | 已实现 | 版本化草稿/发布/退役、Schema/field_id 绑定、服务端结构指纹、固定注册解析器、Run 快照和 Worker 精确匹配已完成;管理端可从 MinerU 样本可视化维护表头、数据起始行、行结构和列映射,并完成新版本治理,无自由 JSON/脚本入口 | +| 文档布局版本与任务生命周期 | 已实现(L1) | 独立布局版本/Job、当前成功引用、parser revision、checksum/大小门禁、lease/超时恢复、重试耗尽、管理员诊断和显式重解析已完成;人工 cell 真值延期,不开放自动 accepted 或 95% 声明 | +| 原生 PDF 结构候选 | 工程已实现(L2 质量待验收) | PDFium 字符 bbox、稳定 token/cell、唯一文本对齐、OpenCV 有框表双门禁、逐表故障隔离和 revision v2 已完成;候选固定 needs_review,人工真值/准确率/P95 未验收 | +| 扫描 PDF OCR 与 EML HTML 布局 | 工程已实现(L3 质量待验收) | RapidOCR 坐标/置信度、OCR+网格+全文本门禁、HTML 主动内容清理、DOM rowspan/colspan、hash/摘要隐私和 revision v3 已完成;候选固定 needs_review,真实扫描质量/P95 未验收 | +| 冻结 Schema 与 cell 证据映射 | 工程已实现(L4 质量待验收) | layout.v1→Grid→冻结 Schema、真实 cell/token evidence、后置表头、重复列、零 Qty、显式 continuation、Run snapshot v3 和 Dify 隔离完成;candidate 不自动接受,真实准确率未验收 | | 订单字段全局显示顺序 | 已实现 | 字段目录独立保存 `display_sequence`,同分类拖拽后静默持久化且刷新保持;当前字段页、已发布/历史版本详情和对话订单信息均按全局顺序展示,历史已删除字段回退版本快照顺序 | | 动态订单字段驱动库存源路由 | 已实现 | 路由条件选择 published 订单稳定 field_id;运行时从 Task 当前 Extraction 的类型化 FieldValue 读取;系统事实仅保留受控枚举 | | 可复用库存解析 Profile | 已实现 | 管理端通过订单字段和库存标准字段结构化选择器版本化维护表头、列映射和 match_keys;多个 published 版本可并存,库存源显式迁移版本;引用中版本不可退役,正常库存源解析无需 LLM | @@ -615,3 +629,6 @@ | 目录展开/折叠与子应用点击 | 已实现 | Chat 侧边栏/移动端 Agent 切换器将目录渲染为树形节点;目录可点击,展开后成员应用也可点击并进入各自 Dify 问答。 | | 聚合 Chatflow 上下文注入 | 已实现 | 聊天时向 Dify inputs 注入成员应用 ID、名称、Dify App ID 与分类等元数据。 | | 多子 Agent 并行召回与答案融合 | 未纳入本期 | 当前由目录 Agent 对应的 Dify Chatflow 基于注入元数据完成聚合问答。 | +| 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 | +| 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 | +| 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 | diff --git a/docs/tec.md b/docs/tec.md index a604ec42..ad304362 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -7,6 +7,14 @@ ## 货代订单抽取文档级优化架构(2026-07-21) - 订单抽取从“邮件和全部附件一次性提交单个 LLM”迁移为“冻结 Run -> 抽取计划 -> 确定性解析 -> 文档级子任务 -> 受控并行无状态 Dify -> HXOPS 合并裁决 -> Candidate/Task”。最终不保留旧整单执行模式。 +- MinerU `pipeline` 已改为独立布局 Job:Intake 同事务创建 Document、`ShippingDocumentLayoutVersion` 和通用 Job 后即可完成预解析;布局 Worker 再通过 `/tasks` 短提交、轮询 `/tasks/{task_id}` 并读取 `/result`,不使用同步 `/file_parse` 长连接。版本表保存紧凑表格快照、parser revision、checksum、大小、质量问题和 lease,不保存完整 Provider 原始响应;Document 仅引用当前成功版本,旧单列 `layout_snapshot_json` 已移除。失败、超限和重试耗尽保留审计但不覆盖旧成功结果。 +- 布局 Job 使用活动版本唯一索引和 `job_id:attempt` lease 防止重复执行及旧 Worker 回写;超时回收可安全 requeue,parser revision 变化自动生成新版本。管理员可查看脱敏版本摘要并显式重解析;诊断不返回 HTML、bbox、全文或内部异常。人工真值当前延期,因此 ready 布局仍只是 Profile/候选输入,不等于 cell 证据已获准自动接受。 +- 原生 PDF 候选使用已有 `pypdfium2` 提取字符 bbox,并只为 MinerU 表格区域生成稳定 token。HTML cell 优先做唯一/连续/非重叠字符对齐;失败时仅允许 OpenCV 多参数有框网格共识,并由原生文本 100% 验证。结果以内嵌 `shipping_document_layout.v1` 保存且固定 `needs_review`;parser revision 已提升为 `v2`,使历史 v1 结果不会静默复用。 +- L3 将 parser revision 提升为 `v3`。扫描 PDF 直接适配 RapidOCR 多边形坐标,OCR cell 必须同时通过 OpenCV 网格和全部非空 cell 文本一致性;EML HTML 只保留清洗后的 table DOM,并用逻辑网格表达 rowspan/colspan。OCR/HTML 均固定 needs_review,原始 OCR 响应、页面图、主动 HTML 和临时表格片段不入库或 Dify。 +- L4 新增 layout.v1→冻结 Schema 映射层,复用现有 HTML Grid 安全规则并保留真实 cell/token evidence。Run snapshot 升级为 v3并冻结内部 `layout_schema_candidates`;跨页只读显式 continuation。Manifest 强制剥离布局及映射候选,needs_review 不参与当前确定性执行。 +- `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、精确表头结构指纹、固定列规则、稳定目标 field_id、checksum 和乐观锁。同一模板只允许一个 published 版本;Run `snapshot_version=2` 冻结全部匹配 Schema 的 published Profile 与 Document 布局快照,后续发布/退役不会改变排队中的运行。 +- Worker 仅对唯一表/唯一 Profile 精确命中执行确定性模板映射。Profile 可以合法覆盖裸表头的通用语义,如 `Part Number -> customer_part_number`、`Vendor Item# -> part_number`;显式零 Qty 删除。多 Profile 命中、多表命中、冻结 field_id 漂移、MinerU 行关系丢失或缺少 `part_number + qty` 时不自动合并,转 Dify/复核。Dify Manifest 会剥离布局 HTML、bbox 和内部 field_code,只携带稳定 field_id 的紧凑候选,避免 Token 膨胀。 +- Profile 管理端从 ready MinerU 布局生成最小网格预览;HTML、bbox、全文和结构指纹不下发浏览器。`from-sample` 创建/更新接口重新读取持久化 HTML 并计算指纹,更新草稿要求 `expected_lock_version`。页面仅允许注册解析器与 Schema line field 下拉,重复目标字段由前端提示、Pydantic 契约再次阻断;发布/复制/退役形成完整不可变版本生命周期。 - Dify 是无状态模型执行层;HXOPS 是计划、并发/重试、Schema、跨文档合并、冲突、审计、成本、业务状态和持久化真相源。Reservation/Allocation 等安全语义由后端硬规则兜底,管理员配置不可覆盖。 - 默认一附件一个抽取单元,单元可返回多个订单;邮件正文作为独立事实/关系单元。确定性表格和邮件头可以绕过 LLM,模型只接收无法确定解析的最小必要内容。 - published Schema 在 Run 创建时冻结,并逐阶段收敛为表头别名、normalizer、validator、证据优先级和冲突策略的唯一业务配置真相;发布时必须拒绝标准化别名碰撞。 @@ -16,9 +24,10 @@ - 阶段 4 已实现 Run 内 2–4 单元受控并行与单元局部指数退避重试。网络线程不共享数据库 Session;主线程按冻结顺序持久化和汇总,成功单元可跨 Job 重试复用。并发/重试参数随 Runtime Binding 冻结到 Run。 - 阶段 5 已实现 HXOPS 保守跨文档合并与部分成功:只按唯一 PO 或强行身份合并并保留全部 Observation;弱身份保持拆分,冲突交统一字段裁决。失败单元不抹除成功单元,Run 以 needs_review 收口。 - 阶段 6 已补齐模型单元预算、进程级 Provider 并发闸门、连续失败短期熔断和管理员脱敏单元诊断。治理参数由 Runtime Binding 校验并冻结,用户 API 不暴露内部单元或 Provider 细节。 -- 阶段 7 已完成影子/自动建单硬门禁:默认只落可审核 Candidate,显式开启后仍复用全部业务安全门禁。旧 `shipping_order_extraction.v1` 整包契约已从代码、测试和配置手册删除,唯一模型契约为 `unit.v2`。 +- 阶段 7 已完成影子/自动建单工程硬门禁、质量验收延期:默认只落可审核 Candidate,显式开启后仍复用全部业务安全门禁。订单抽取只使用唯一 Manifest 契约;人工真值与真实影子批准完成前不得开启自动建单。 - 每阶段执行测试、自检和 Review 门禁,阻断问题全部关闭后方可进入下一阶段。Dify 画布由管理员按 `docs/features/shipping-notice/technical.md` 手工修改。 - 订单抽取可观测进度已完成:用户仅见通用阶段、健康和时间线;新终态会话待查看、管理员只读诊断审计、90天事件每日清理均已实现。Workflow/节点/Job/Provider/正文不进入用户契约,自定义节点标题不持久化。 +- 重新识别采用 Run 谱系而非原地覆盖:`reparse_of_run_id/superseded_by_run_id` 连接来源和新版,Candidate 按 `(intake_id,candidate_key,order_extraction_run_id)` 版本化,`is_current_version` 是唯一可建单门禁。新版创建时冻结旧候选,失败时恢复其原选择状态;用户端仅见来源/后继编号、原因和 Schema/Profile/layout 是否变化的脱敏摘要。 # 智能HR请假管理技术架构 @@ -81,7 +90,7 @@ - 阶段 4 可观测性端点为 `GET /api/admin/shipping-notice/order-extraction-runs/health`,仅管理员可访问;支持 `window_hours/queued_stale_seconds/running_stale_seconds`,服务端钳制安全范围并返回 health、计数、状态/phase/error_code 分布及 queue/provider/HXOPS/total 时延。 - 健康窗口按终态 `finished_at` 统计,活动 Run 始终纳入;queued 默认 300 秒、running/result_persisted 默认 1800 秒判积压。至少 5 个终态且失败率达到 20%,或存在积压 Run 时标记 degraded。 - Worker 结构化日志只记录 `run_no/job_id/attempt/phase/status/elapsed_ms/error_code`,禁止记录异常正文、输入快照、Provider 配置、API Key 或 orders 原始结果。 -- 前端 GET 使用 AbortController:每次查询 10 秒超时,切会话/卸载立即 abort;Abort 只视为传输失败并退避,不写 Run failed,也不取消后台作业。 +- 前端 GET 使用 AbortController:每次查询 10 秒超时,切会话/卸载立即 abort;Abort 只视为传输失败并退避,不写 Run failed,也不取消后台作业。用户 Run DTO 与持久化聊天状态只保留错误码和通用提示,Worker/Provider 错误正文仅限服务端日志与管理员脱敏诊断边界。 - Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v4` 双层判重;内容版本覆盖单头、V2 订单行、价格与分配字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。 - Candidate 唯一键为 `(intake_id, candidate_key)`,支持一个 Document 产生多个 Candidate;Task 与 Candidate 一对一关联。 - 自动建单后若仍有未消费/待处理 Candidate,Intake 保持 `parsed + partially_completed`;全部处理后才 `consumed`。后补订单可创建新的 Batch,并继续关联原 Intake/Candidate。 @@ -1219,3 +1228,11 @@ Dify - **发货任务分页与批次下载**:`GET /api/workspace/shipping-tasks` 接收 `page`、`page_size` 和可选状态筛选,由数据库返回 `{ items, page, page_size, total }`;工作台默认每页 10 条,筛选、刷新或切页不保留跨页选择。`POST /api/workspace/shipping-exports/archive` 只接收 `batch_no` 或 `task_nos[]`,后端重新做用户归属校验并选择仍与 Task 当前导出路径一致的最新 ready Artifact;ZIP 使用可溢写临时文件,含 `manifest.json`,同名追加任务号,单次最多 100 票。 - **发货任务处置与 Dify 边界**:`ShippingTask` 以独立生命周期和回收站字段管理 delete/void/archive,后台 worker、RPA 回调和履约入口统一读取生命周期熔断。Dify 不新增 Tool、不修改画布、不参与批量处置;工作台调用 HXOPS `/api/workspace/shipping-tasks/batch-*` API。外部货代作废能力接入前,上传中/已上传任务只允许归档。 - **订单通用上下文字段目录**:订单 Schema 的稳定字段增加 `field_category` 与 `collection_mode`,`general_context` 固定为 Header + `deterministic_context`。`shipping_context_providers/options` 只维护展示、敏感等级、默认 Dify 策略和启停;可执行能力、允许暴露策略和脱敏器必须同时命中代码注册表。首批注册 `mail_header/from_email`、`mail_header/from_domain`,来源语义固定为原始 EML `From`,禁止任意 JSONPath、SQL、模型属性、模板指纹或自由 selector。版本快照冻结 provider/option/source key、敏感等级与 Dify 策略;来源停用或代码能力移除会阻止新发布,但不改写历史快照。Workflow 在 `execution_manifest.readonly_hints` 中接收按 Intake 分组的受控 JSON:`never` 不输出,`redacted` 只输出受控不可逆占位值,`confirmed_readonly` 只输出 Run 冻结值;三者均不进入 `extraction_contract.fields[]`,Dify 回传对应 `field_id` 仍由后端拒绝。 +## 2026-07-22 订单抽取唯一 Manifest 技术决策 + +- Runtime Binding 只绑定执行器和运行参数;运行时不进行输入格式探测或多格式混传。 +- 唯一 Manifest 使用单 `document` 和 `structured_table_candidates`。候选只暴露稳定 field_id、值、短引文、行列位置与质量问题;原始布局证据保留在 HXOPS 冻结快照中。 +- accepted 完整表走确定性零 Provider 路径;需要模型补充时,后端校验 accepted 字段集合和值未被删改。人工真值未完成前生产候选不提升 accepted。 +- L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。 +- L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。 +- L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。 diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md index 0a19eb09..f21cd691 100644 --- a/docs/test_plan_matrix.md +++ b/docs/test_plan_matrix.md @@ -39,17 +39,24 @@ | **发货通知** | **订单抽取前端 Run 切流与恢复** | parsed Intake 发送只创建订单抽取 Run,不进入普通 Chatflow;新会话、刷新、断网和切会话均由 Run 状态恢复。 | `useChatShippingSendHandler.spec.ts`、`useShippingOrderExtractionRuns.spec.ts`、`useShippingNoticeIntakes.spec.ts` | 新会话、同状态重复轮询、列表请求失败、旧会话迟到响应、Run failed | `sendMessage` 未调用;URL 使用返回的 conversation;稳定 formId 原位更新;无变化不重复写 ChatLog;旧响应不污染当前会话;失败附件可重试。 | | **发货通知** | **订单抽取能力显式绑定** | 货代 Agent 只能绑定启用的 internal Dify Workflow;无绑定、停用或类型不符时不创建 Run/Job。 | `test_agent_runtime_bindings.py`、`test_agent_runtime_binding_migration.py` | 无绑定、Chatflow/workspace Provider、停用 Provider、合法 Workflow | 非法配置返回稳定错误码;合法绑定安全序列化且不泄露 API Key;内部 Provider 不进入用户 Agent 列表。 | | **发货通知** | **订单抽取可靠性与健康监控** | Run 健康端点聚合积压、失败、重试和四段时延;Worker 日志安全;浏览器 GET 可超时/取消。 | `test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py`、`useShippingOrderExtractionRuns.spec.ts` | queued/running 超阈值、终态失败、Provider 成功后 DB 失败、挂起 GET、切会话 abort、普通用户/非法参数 | health 正确 degraded/healthy;缓存结果不重复调用 Dify;日志/API 不含正文和 Provider;GET abort 不取消 Run、不伪造失败且继续退避。 | +| **发货通知** | **版本化重新识别** | 终态未消费 Run 使用当前发布规则创建新版本;失败 Run 的执行重试保持原冻结快照。 | `test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts`、前端 build | 终态/运行中/跨用户 Run、无效原因、重复点击、新版成功/失败、候选建单、当前 Schema/Profile/layout 变化 | 新 `run_no` 有来源谱系且无 Provider 缓存;同一活跃后继幂等复用;旧候选在新版执行期间不能建单;新版失败精确恢复旧候选选择状态;仅当前版本 Candidate 可建单;用户 API 仅输出脱敏版本关系与规则/布局差异摘要。 | | **发货通知** | **订单抽取优化阶段 0 进度基础** | Dify 原生生命周期事件写入独立短事务并投影通用阶段;用户摘要/时间线按白名单展示;迁移可往返。 | `test_shipping_order_extraction_progress.py`、`test_order_extraction_progress_migration.py`、`test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts` | 重复/迟到/并行节点、自定义敏感节点标题、跨用户读取、阶段变化但 Run 状态不变、upgrade/downgrade | 事件幂等;终态及 HXOPS 落库阶段不回退;节点标题不持久化;用户仅见阶段/状态/时间;进度版本变化触发卡片更新;迁移无残留回滚;不展示虚假百分比。 | | **发货通知** | **订单抽取优化阶段 1 动态表格契约** | Run 冻结 Schema 的字段编码、显示名、别名、规范化器和校验器驱动确定性表格解析;后端安全规则不可由管理员覆盖。 | `test_order_schema_table_contract.py`、`test_shipping_order_schema_runtime.py`、`test_shipping_notice_extract.py` | 未配置别名、禁用/不支持字段、标准化别名碰撞、Reservation 禁用表头、重复列、retired 冻结版本、文档级 Reservation、未配置 UOM/币种/金额 | 无契约不猜列;碰撞/禁用表头阻止保存发布;重复列进入复核;旧冻结版本可重放;不扫描任意单元格、不广播 Reservation、不注入未启用字段。 | | **发货通知** | **订单抽取优化阶段 2 抽取计划与文档单元** | Run 创建时持久化唯一计划;正文关系和附件分别成为冻结、可恢复的局部状态单元。 | `test_order_extraction_plan_migration.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 重复创建、邮件正文+附件顺序、跨 Intake 文档、局部成功/失败、非法状态跃迁、失败回到 pending、Worker 恢复、迁移往返 | 计划/单元幂等;复合外键阻止错挂;成功结果不被其他失败清除;计划准确汇总 partial_failed;重启可复用;迁移无残留回滚。 | -| **发货通知** | **订单抽取优化阶段 3 确定性优先与紧凑契约** | 每个单元先确定性解析;仅不完整单元以 `unit.v2` 单文档清单调用无状态 Dify。 | `test_agent_runtime_bindings.py`、`test_order_schema_table_contract.py`、`test_shipping_order_schema_runtime.py` | 完整表格、缺必填字段、兄弟附件敏感文本、伪造 sibling document_id、冻结只读提示、Provider 结果重放 | 完整表格 Dify 调用为零;模型输入只有当前 Document;跨单元 Intake/主文档/Observation 被拒;确定性和模型结果均通过统一 Schema/证据裁决。 | +| **发货通知** | **订单抽取优化阶段 3 确定性优先与紧凑契约** | 每个单元先确定性解析;仅不完整单元以唯一单文档 Manifest 调用无状态 Dify。 | `test_agent_runtime_bindings.py`、`test_order_schema_table_contract.py`、`test_shipping_order_schema_runtime.py` | 完整表格、缺必填字段、兄弟附件敏感文本、伪造 sibling document_id、冻结只读提示、Provider 结果重放 | 完整表格 Dify 调用为零;模型输入只有当前 Document;跨单元 Intake/主文档/Observation 被拒;确定性和模型结果均通过统一 Schema/证据裁决。 | | **发货通知** | **订单抽取优化阶段 4 并行与局部重试** | Dify 单元按冻结配置受控并行;失败只重试对应单元,主线程串行持久化并按 position 汇总。 | `test_agent_runtime_bindings.py`、前端 i18n parity/build | 峰值并发、首次超时后成功、成功单元复用、SQLite/线程隔离、配置边界、完成乱序 | 峰值不超过 2–4 配置且实际并行;单元 attempts/latency 可审计;线程不共享 ORM;已成功单元不重跑;四语言和构建通过。 | | **发货通知** | **订单抽取优化阶段 5 跨文档合并与部分成功** | HXOPS 以唯一 PO 或强行身份合并 Observation;弱身份拆分,冲突阻断,失败单元不抹除成功结果。 | `test_order_extraction_merge.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_schema_runtime.py` | 同 PO 数量冲突、同料号不同 Reservation、无可靠身份、一个单元永久失败 | 同订单只生成一个合并候选且保留双方证据;冲突不覆盖;弱身份不误合并;成功单元继续提交,Run needs_review 并显示失败单元数。 | | **发货通知** | **订单抽取优化阶段 6 运行治理** | 冻结模型预算、Provider 进程级限流/熔断,并在管理员诊断中展示脱敏单元指标。 | `test_order_extraction_provider_guard.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py`、前端 i18n/build | 模型单元超预算、连续失败开路、成功复位、跨 Run 并发、管理员/普通用户、诊断正文泄露 | 超预算零请求;熔断快速失败且可恢复;Provider 合计并发受限;管理员只见单元状态/attempt/duration/error_code,访问留痕;用户 API 不变。 | | **发货通知** | **订单抽取优化阶段 7 影子验收与自动建单门禁** | 默认只落可审核 Candidate;明确开启后仍须通过所有现有业务与安全门禁。 | `test_shipping_notice_order_extraction.py`、`test_agent_runtime_bindings.py`、静态 v1 扫描、真实脱敏样本人工验收 | 默认关闭、显式开启、低置信/缺证据/冲突/重复、旧 v1 残留、100+ 脱敏 Run | 影子期合格 Candidate ready 但零 Task;开启后仅全门禁通过者建单;错误建单为 0;核心字段精确率≥99.5%、召回率≥98%;代码/手册无旧 v1。 | | **发货通知** | **文档版面结构化 L0 契约与评测基线** | 用 `shipping_document_layout.v1` 统一页、真实坐标、词元、表格、行列、单元格、跨页关系和质量问题;人工真值与候选结果按 content hash 和 bbox IoU 评测;MinerU 仅输出经能力审计的候选。 | `test_shipping_document_layout_contract.py`、`test_shipping_document_layout_evaluation.py`、`test_shipping_document_layout_mineru.py`、至少 30 份脱敏文档人工真值 Review | 越界/零面积 bbox、标准化坐标越界、未知 token、重复 ID、跨度重叠、单元格超出表格、悬空/前向 continuation、blocking issue 冒充 accepted、真值哈希漂移、漏表/漏单元格/字段错配、MinerU 字符串 JSON/多文件/超大响应/Provider 错误、HTML 表格无或缺少 cell bbox | 契约和评测测试通过;ID/checksum 稳定;检测/归行归列/字段映射指标分离;MinerU 无完整 cell bbox 时确定性证据必须为 false;真实样本不进仓库/日志;原生与扫描 PDF、EML HTML、跨页、表头后置、多表等类别全部有人工真值后,L0 才可通过。 | | **发货通知** | **文档版面结构化 L0 MinerU 批量结构审计** | 使用 pipeline 对 30 个真实 PDF 做匿名结构与容量审计,验证页、bbox、HTML 表格和适配器坐标空间。 | `test_shipping_document_layout_mineru.py`、30 PDF 只读审计记录 | content bbox 0..1000 坐标转换、并发连接中断、顺序重试、无表格、无 cell bbox、响应大小 | 30/30 最终可解析;并发失败可分类且顺序复测成功;初始生产并发低于服务上限并使用异步任务;无完整 cell bbox 时不得接受高风险字段。 | +| **发货通知** | **文档版面结构化 L1 版本与独立 Job 生命周期** | Intake 只调度布局,独立 Worker 按 Document 版本执行 MinerU;当前成功引用与失败历史隔离。 | `test_shipping_document_layout_lifecycle.py`、`test_shipping_document_layout_lifecycle_migration.py`、`test_shipping_document_layout_job.py`、`test_admin_shipping_document_layouts.py`、`test_shipping_notice_intakes.py` | 相同 parser 幂等、revision 漂移、旧 JSON 回填、超大 payload、Provider 异常、重试耗尽、超时回收、旧 lease 回写、Document 删除、管理员越权/隐私 | Intake 不内联调用 MinerU;迁移可往返且旧快照标记 legacy;活动版本唯一;失败不覆盖 current;旧 Worker 无法回写;Job/版本同步终结;诊断无 HTML/bbox/全文/内部异常;人工真值延期不影响生命周期测试但不得转化为准确率结论。 | +| **发货通知** | **文档版面结构化 L2 原生 PDF 候选** | PDFium 提取真实字符坐标;MinerU HTML 仅通过唯一文本或严格有框表双门禁形成 layout.v1 cell/token 候选。 | `test_shipping_document_layout_native_pdf.py`、`test_shipping_document_layout_text_cell_alignment.py`、`test_shipping_document_layout_opencv_table.py`、`test_shipping_document_layout_runtime.py` | 真实空白 PDF、唯一/重复文本、跨行/重叠 glyph、有框/无框表、文本不一致、坏表与好表同页、PDFium 失败、revision v1→v2 | 不伪造扫描文本;cell 可追溯 token;歧义零 cell;逐表隔离;候选失败不丢 MinerU HTML;layout 固定 needs_review 且不进入 Dify。人工真值延期时只判工程测试,不判召回率/归行归列准确率/P95。 | +| **发货通知** | **文档版面结构化 L3 OCR 与 EML HTML** | RapidOCR 保留多边形坐标;扫描表必须通过 OCR+OpenCV+全文本门禁。EML HTML 经白名单清理后按 DOM 网格输出同一 layout.v1。 | `test_shipping_document_layout_ocr_pdf.py`、`test_shipping_document_layout_html_layout.py`、`test_shipping_document_layout_native_pdf.py`、`test_shipping_notice_extract.py`、`test_shipping_notice_intakes.py` | OCR 坐标缩放、低置信、引擎缺失、有框/无框、OCR cell token;script/style/img/事件/链接、rowspan/colspan、坏表、plain 不变 HTML 变化、摘要泄漏 | OCR 无坐标或全文本不一致零 cell;HTML 主动内容清零;DOM 合并格不重叠;正文 hash 覆盖清洗表格;临时/原始 HTML 不入摘要/Dify;全部候选 needs_review。人工真值延期时不判真实 OCR 字符质量、跨度准确率和 10 页 P95。 | +| **发货通知** | **文档版面结构化 L4 冻结 Schema 证据映射** | layout.v1 Table 直接按 Run 冻结 Schema 映射,字段证据必须引用真实 cell/token;跨页只接受显式 continuation。 | `test_shipping_document_layout_schema_mapping.py`、`test_shipping_document_layout_html_table.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 后置表头、重复目标列、Qty=0、真实 cell/token/evidence_ref、显式/缺失 continuation、Run 后 Schema 漂移、Manifest 泄漏 | 映射复用既有安全规则;重复列全 ambiguous;零 Qty 删除;Run v3冻结候选不漂移;needs_review 只标 candidate且不进 Dify/确定性执行。人工真值延期时不判真实字段映射准确率,但错误自动接受数必须为 0。 | | **发货通知** | **订单文档模板 Profile 纯契约** | 以表头网格精确结构指纹选择固定列规则,允许模板级字段语义覆盖全局 Schema;只运行注册解析器。 | `test_shipping_order_document_profile.py` | `Part Number -> customer_part_number`、`Vendor Item# -> part_number`、复合料号 cell、零 Qty、结构漂移、MinerU 行关系丢失、自由解析器注入 | 精确命中时模板映射原样生效;零 Qty 行删除;结构变化不做相似匹配;行关系丢失显式阻断;未知解析器或非法目标字段拒绝保存。 | +| **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、Provider 失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、布局 HTML 泄漏 Dify、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;Provider 失败安全回退;唯一完整表跳过 Dify;多表不自动合并;HTML/bbox/field_code 不进入 Dify;零 Qty 删除。 | +| **发货通知** | **订单文档 Profile 可视化治理** | 管理员只从 ready MinerU 样本选择表格、行和受控字段/解析器,完成草稿、新版本、发布与退役;浏览器不持有可伪造运行契约。 | `test_shipping_order_document_profile_service.py`、`orderProfileForm.utils.spec.ts`、`shippingConfigNavigation.spec.ts`、前端生产构建 | 普通用户访问、伪造结构指纹、HTML/bbox 泄漏、越界行、重复目标字段、复合解析器冲突、过期 lock、新版本重配、unsupported 行结构 | 普通用户拒绝;预览仅 cell 文本;指纹后端计算;越界/过期锁/重复字段阻断;只允许注册解析器;复制草稿须用样本重新确认;无需编辑 JSON/HTML/脚本。 | | **发货通知** | **Workflow 结果缓存与重试** | Dify 成功后先独立保存结构化 orders;即使无 workflow_run_id,HXOPS 落库失败重试也不得再次调用 Dify。 | `test_agent_runtime_bindings.py::test_worker_caches_provider_output_and_does_not_call_dify_twice` | 首次 Provider 成功、后续 DB 暂时失败 | Dify 调用 1 次、持久化尝试 2 次,Run 最终 completed。 | | **发货通知** | **Provider 变更与密钥轮换** | App ID/Base URL 漂移阻断旧 Run;API Key 轮换允许旧 Run 使用新密钥继续。 | `test_agent_runtime_bindings.py` Provider drift / key rotation 用例 | 排队后修改 App ID、Base URL 或 API Key | 前两者 Run/Job failed 且不调用 Dify;密钥轮换成功完成。 | | **发货通知** | **Run 安全视图与事务原子性** | 用户 API 不返回正文、Provider 快照/原始结果/配置;Agent 与 binding 保存同事务。 | `test_shipping_order_extraction_runs.py`、`tests/services/admin/test_agent_service.py` | 查询 Run;创建/更新时绑定校验失败 | 响应无敏感快照;失败后 Agent 字段和 binding 均不留下半成品。 | @@ -67,15 +74,16 @@ | **发货通知** | **Candidate 双指纹判重** | 同身份同内容与同身份修订必须给出不同重复状态。 | `test_shipping_notice_business_dedup.py::test_candidate_content_fingerprint_distinguishes_same_content_and_revision` | 相同 PO/Reservation,不同或相同行数量 | 分别返回 `same_business_content`、`possible_revision`。 | | **发货通知** | **Candidate 审核 API** | owner 可选择/修订/刷新/决策;越权不可见;已消费不可修改。 | `test_shipping_notice_intakes.py::test_candidate_review_duplicate_api_and_access_guards` | owner/other 用户、已消费 Candidate | 成功路径 200,越权 404,已消费 409,修订后清空旧重复决策。 | | **发货通知** | **Candidate 安全门禁** | 空摘要、无效行、附件不完整、过期、选择漂移、无候选旧路径均不可建单。 | `test_shipping_notice_intakes.py` Candidate validation/gate 用例 | 非法摘要与异常 Intake | API 返回明确 400/409;不创建 Task;合法幂等重放不受影响。 | -| **发货通知** | **关键字段真值校验** | LLM 候选必须经后端格式、来源和列证据裁决;多模板字母/数字 ID 兼容,内部 hex/UUID 与来源冲突必须阻断。 | `test_shipping_notice_reservation_id.py`、`test_shipping_notice_extract.py`、`test_shipping_notice_tools.py` | External Reservation、COM ID、PR Number、AWS-311、32 位 hex、拍平文本、冲突 TSV | 有唯一列证据时纠正并留痕;无证据或冲突时进入 `rsv_req/parse_review`;确认与匹配旁路均不可绕过。 | +| **发货通知** | **关键字段真值校验** | LLM 候选必须经后端格式、来源和列证据裁决;Reservation ID 只接受 5 位或 10 位纯数字,格式或来源冲突必须阻断。 | `test_shipping_notice_reservation_id.py`、`test_shipping_notice_extract.py`、`test_shipping_notice_tools.py` | 5 位/10 位数字、字母型编号、其他长度数字、内部 hex/UUID、拍平文本、冲突 TSV | 仅格式与列证据同时可信时采用;无证据或冲突时进入 `rsv_req/parse_review`;确认与匹配旁路均不可绕过。 | | **发货通知** | **HTML 表格冻结 Schema 安全映射** | HTML 表格展开 rowspan/colspan 后只按 Run 冻结精确别名映射;未知、重复或语义不稳定列不得按位置和值形态猜字段。 | `test_shipping_document_layout_html_table.py` | 多层/后置/重复表头、嵌套表、删除/汇总行、裸 Material、AWS HUB、重复料号列、纯行号 Reservation | 嵌套表不污染主表;重复字段列全部 ambiguous;裸 Material 未显式配置时保持 unmapped;纯行号不成为 Reservation;未知列不挤入其他字段。 | | **发货通知** | **真实表头覆盖与安全别名 Review** | 对不少于 30 份真实脱敏 PDF 分别统计解析成功率、表头命中、mapped/unmapped/ambiguous 列和核心字段组合;覆盖率不得冒充字段准确率。 | L0 匿名审计脚本/Review 记录、published Schema 快照、Dify 手工配置验收 | Material 与 VendorPartNumber 同表、明确 AWS SKU/APN、Item No、表头后置、MinerU 首行数据拼接、缺 Reservation 表格 | Material 系列映射 `customer_part_number`;明确 MPN/Supplier/Vendor PN 映射 `part_number`;明确 AWS SKU/APN 映射 `aws_part_number` 且优先;歧义列自动接受数为 0;缺 Reservation 时保留确定字段并由跨文档补充,最终库存/Excel 门禁仍阻断。 | | **发货通知** | **Qty 表头与版面污染门禁** | 只允许语义单一且保持独立列的完整 Qty 别名;多语义粘连和首条数据混入表头必须转复核。 | HTML 网格匿名 Review、`test_shipping_document_layout_html_table.py`、Dify 手工配置验收 | `Q TY 数量`、`Q TY UNIT`、`ORDER QUANTITY EA`、`Quantity U M Delivery`、`Item No 00010` | 独立数量列可按精确 alias 命中;粘连列不得自动映射;含样本值的污染表头不得进入 Schema;不以模糊前缀匹配提高覆盖率。 | | **发货通知** | **匿名 Schema 覆盖报告** | L0/L4 对同一脱敏样本集生成可重复聚合报告,并区分建单完整率与全部 required 完整率。 | `test_shipping_document_layout_coverage.py` | 含真实值/表 ID/evidence 的映射结果、无表格、缺 Reservation 行、未知/歧义列 | 报告计数和比率正确;仅含 field_code/issue_code;不含文件名、表头、字段值、table/cell/evidence 标识;覆盖率不得标记为准确率。 | | **发货通知** | **Cell bbox Provider 准入与伪证据禁用** | 高风险字段 cell 证据只能来自 Provider 原生 cell 身份坐标或经人工真值验收的专用 TSR;低成本字符串/线投影实验仅作候选评测。 | L0 Cell bbox 匿名 Review、`test_shipping_document_layout_mineru.py`、后续 TSR 评测测试 | 重复 Qty、相同料号、空 cell、无框/断线表、复杂表头、仅整表 bbox、HTML 无 cell ID | 不按第 N 个字符串、整表均分或简单线投影生成 cell;MinerU 无 cell 身份时 `deterministic_cell_evidence_ready=false`;无人工真值达标证据不得进入 accepted/自动建单。 | +| **发货通知** | **原生文本 cell 候选反伪证据门禁** | PDF 字符坐标只能为人工标注生成候选;文本必须在整表内唯一、同视觉行、连续且不与其他 cell 共享 glyph。 | `test_shipping_document_layout_text_cell_alignment.py`、30 PDF 匿名复评 | 重复 Qty、空 cell、缺失文本、重叠子串、跨行唯一字符串、页面外 glyph/table bbox | 重复/空白/缺失/跨行/重叠均不输出候选;坏 glyph 丢弃并留问题码,不裁剪坐标;候选不导出为生产 `LayoutCell`,不计作未人工确认的真值。 | | **发货通知** | **OpenCV 有框表双门禁** | pipeline 整表 bbox 内以多参数形态学共识恢复严格有框网格,再由独立 PDF 文本层验收 bbox 内容;两者职责不可混合。 | `test_shipping_document_layout_opencv_table.py`、L0 真实样本匿名 Review | 完整 2x2 网格、rowspan、无框表、HTML/图像形状不一致、单参数偶然命中、总体文本错位、高风险 cell 错位 | 至少两组边界一致且与 HTML 网格完全同形才输出候选;无框/不一致零 cell;整表非空文本 >=95% 且高风险 cell 100% 匹配才进入后续人工真值评测;未达标不转换 LayoutCell。 | | **发货通知** | **MinerU pipeline-only Provider 边界** | 当前阶段只使用 MinerU pipeline;未评测 Provider 不得形成隐藏 fallback、自动切换或兼容分支。 | MinerU 适配器测试、技术路线 Review、依赖/代码搜索 | pipeline 成功/失败、VLM/hybrid 配置、MonkeyOCR 未部署 | 生产候选只来自 pipeline;VLM/hybrid/MonkeyOCR 不参与运行;Provider 变化必须建立独立评测阶段后再接入。 | -| **发货通知** | **跨文档 Reservation 关系门禁** | 邮件中的 Reservation 只能按明确 PO/内部料号关系补充订单行;同 Intake 或同邮件不是广播依据。 | unit.v3 关系契约测试、跨文档合并测试、Dify 手工配置验收 | 多 PO 单 Reservation、多 PO 多 Reservation、明确 PO-Reservation 对、明确 Part-Reservation 对、唯一一对一 | 仅明确或唯一关系补充;多义关系保持 needs_review;每条最终行仍需 Reservation 才可库存匹配和生成发货 Excel。 | +| **发货通知** | **跨文档 Reservation 关系门禁** | 邮件中的 Reservation 只能按明确 PO/内部料号关系补充订单行;同 Intake 或同邮件不是广播依据。 | 关系契约测试、跨文档合并测试、Dify 手工配置验收 | 多 PO 单 Reservation、多 PO 多 Reservation、明确 PO-Reservation 对、明确 Part-Reservation 对、唯一一对一 | 仅明确或唯一关系补充;多义关系保持 needs_review;每条最终行仍需 Reservation 才可库存匹配和生成发货 Excel。 | | **发货通知** | **Candidate 迁移往返** | 内容指纹、订单抽取状态与多 Candidate 唯一键迁移须可独立 upgrade/downgrade。 | `test_shipping_notice_candidate_migration.py` | 前一版本最小 schema;同 Document 多 Candidate | 新列/约束存在;安全场景完整降级;多 Candidate 场景明确拒绝降级。 | | **发货通知** | **动态订单唯一真相** | 订单头/行仅保存在任务锁定的 `ShippingOrderExtraction/FieldValue`;固定投影表和 JSON 快照不得存在。 | `test_shipping_task_field_reconciliation.py`、`test_shipping_notice_order_extraction.py`、迁移结构检查 | 人工改单、open_existing 回填、重解析、旧表/列结构检查 | 业务读取只见动态 FieldValue;旧表/列不存在;冲突按动态行 `position` 保留。 | | **发货通知** | **字段对账与冲突门禁** | Candidate 空字段可补齐;双方非空不同落冲突;未解决冲突阻断库存/RPA/匹配/导出;改单带版本。 | `test_shipping_task_field_reconciliation.py` | open_existing 补 Reservation;多行同字段冲突;行重建后冲突存活 | applied/conflicted 可区分;下游入口无副作用;resolve 后重算 Gate。 | @@ -104,3 +112,6 @@ | **发货通知** | **共享库存文件解析方案** | 多库存站点共享版本化文件结构和订单匹配定义。 | `test_inventory_parsing_profile.py`、`test_shipping_inventory_service.py` | 结构化目录、published 绑定、禁用站点分步配置、多版本并存、退役引用、当前订单模板字段门禁 | 同方案可绑定多站点;新版本不破坏旧绑定;引用中版本不可退役;定义 checksum 不可变。 | | **发货通知** | **版本化 Excel 模板与 Artifact** | 库存源选择 published 模板,按稳定动态字段与 Profile match_keys 生成并锁定完整输入版本。 | `test_shipping_excel_template.py`、`test_shipping_template_migrations.py` | MinIO 替身、真实 xlsx、反序库存、歧义多命中、Header/Line、多 Source、迁移往返、提交失败 | 模板不依赖本机磁盘;行序不影响匹配;冲突阻断且无孤立文件;Artifact 含模板、Schema、Profile、checksum。 | | **发货通知** | **批次 ZIP 下载** | 工作台按批次或显式勾选任务集合下载每票当前可信 Artifact。 | `test_shipping_export_archive.py`、`exportSelection.spec.ts` | 同名、失效引用、缺失文件、损坏 checksum、越权、API attachment、选择去重/取消/可见范围/100 票上限 | 当前有效文件均包含且不覆盖;旧失效 Artifact 排除;manifest 完整;越权整体拒绝;返回 application/zip;显式选择不会携带筛选后不可见任务。 | +| **发货通知** | **唯一 Manifest 与紧凑候选** | Run 冻结唯一 Manifest;模型输入不含版面原始载荷。 | `test_agent_runtime_bindings.py`、前端 `npm run build` | Binding 运行中改动、needs_review/accepted 候选、完整 accepted 表 | 只含稳定字段候选;HTML/bbox/token/cell/evidence/field_code 不泄漏;accepted 值不可覆盖;完整 accepted 表零 Provider。人工真值与 95% 质量指标延期。 | +| **发货通知** | **L6 可追溯证据裁决** | accepted Observation 必须有稳定证据引用;无 cell 纯文本表格不可冒充 verified;跨文档不得按 Qty 串值。 | `test_shipping_order_schema_runtime.py`、`test_shipping_notice_order_extraction.py`、`test_shipping_order_extraction_runs.py`、`test_shipping_order_layout_evidence_migration.py` | accepted cell 补字段、layout/LLM 冲突、纯文本表格、同 Qty 多附件、迁移往返、诊断隐私、UI 原因码 | accepted layout 保存 Document/Page/Table/Row/Column/Cell;文本与邮件头也有引用;needs_review 原因机器可读;管理员只见计数/原因码;无值、quote、cell ID 泄漏。真实质量统计延期 L7。 | +| **发货通知** | **L7 启用准备与旧路径清理** | 零 Provider 只允许 accepted layout;Profile/纯文本不得自动生成订单;无批准质量批次不得开启自动建单。 | `test_agent_runtime_bindings.py`、`test_shipping_order_extraction_quality_gate.py`、质量迁移往返、前端 `npm run build`、静态代码搜索 | 完整纯文本表、精确 Profile、accepted layout、双人一致/分歧标签、同人双批准、首次批准后改标签、当前 Schema 漂移、Run/Worker 批次漂移、管理 API 脱敏、启用 UI | 纯文本/Profile 均调用 Provider;accepted layout 仍可零 Provider;自动建单要求当前 Schema、100 个达标一致样本、不同业务/技术批准和 Run 冻结批次,Worker 执行前复核。人工真值延期时没有批准批次、UI/后端均保持关闭;100+20 真实 Run和Dify实配缺失时 L7 明确未通过。 | diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index ed311568..80319dd4 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -53,6 +53,8 @@ const ShippingIdentityRulesPage = () => import("@/features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue"); const ShippingOrderExtractionRunsPage = () => import("@/features/admin/modules/shipping-order-extraction-runs/ShippingOrderExtractionRunsPage.vue"); +const ShippingOrderDocumentProfilesPage = () => + import("@/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue"); export const adminRoutes: RouteRecordRaw[] = [ { @@ -169,6 +171,12 @@ export const adminRoutes: RouteRecordRaw[] = [ component: ShippingOrderExtractionRunsPage, meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_extraction_runs', title: "订单识别运行" }, }, + { + path: "shipping-order-document-profiles", + name: "AdminShippingOrderDocumentProfiles", + component: ShippingOrderDocumentProfilesPage, + meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "订单文档模板" }, + }, { path: "announcements", diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index 96279d13..9915d323 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -513,10 +513,14 @@ export const listAdminAgentRuntimeBindings = (agentId: number) => requestJson( `/api/admin/agents/${agentId}/runtime-bindings`, auth(), ); +export const listApprovedOrderExtractionQualityBatches = (ownerAgentId: number) => + requestJson( + `/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id=${ownerAgentId}`, auth(), + ); export const saveAdminAgentRuntimeBinding = ( agentId: number, capabilityCode: string, - payload: { provider_agent_id: number; enabled: boolean; config: Record }, + payload: { provider_agent_id: number; enabled: boolean; config: Record }, ) => requestJson( `/api/admin/agents/${agentId}/runtime-bindings/${capabilityCode}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) }, diff --git a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts new file mode 100644 index 00000000..40a7d790 --- /dev/null +++ b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts @@ -0,0 +1,74 @@ +/** + * features/admin/api/shipping-order-document-profile.api.ts + * 用途:订单文档 Profile 管理、MinerU 样本选择和发布 API。 + * 依赖:shared/api/client、auth headers、Profile DTO。 + * 逻辑:页面只使用结构化接口;结构指纹和 HTML 始终由后端持有。 + */ + +import { requestJson } from '@/shared/api/client'; +import { getAuthHeaders } from '@/shared/utils/auth'; +import type { + CreateOrderProfileFromSampleInput, + OrderProfileSampleDocument, + OrderProfileSamplePreview, + ShippingOrderDocumentProfile, +} from '../types/shipping-order-document-profile.types'; + +const auth = () => ({ headers: getAuthHeaders() }); +const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); + +/** 列出全部 Profile 版本。 */ +export const listOrderDocumentProfiles = () => + requestJson('/api/admin/shipping-notice/order-document-profiles', auth()); + +/** 列出已具备 ready MinerU 表格的样本文档。 */ +export const listOrderProfileSamples = () => + requestJson('/api/admin/shipping-notice/order-document-profile-samples', auth()); + +/** 读取一个样本文档的网格预览,不返回 HTML 或 bbox。 */ +export const getOrderProfileSampleTables = (documentId: number) => + requestJson( + `/api/admin/shipping-notice/order-document-profile-samples/${documentId}/tables`, auth(), + ); + +/** 由真实样本和结构化列选择创建 Profile 草稿。 */ +export const createOrderProfileFromSample = (payload: CreateOrderProfileFromSampleInput) => + requestJson('/api/admin/shipping-notice/order-document-profiles/from-sample', { + method: 'POST', body: JSON.stringify(payload), ...jsonAuth(), + }); + +/** 用新样本和乐观锁更新已存在草稿。 */ +export const updateOrderProfileFromSample = ( + profileId: number, payload: CreateOrderProfileFromSampleInput & { expected_lock_version: number }, +) => requestJson( + `/api/admin/shipping-notice/order-document-profiles/${profileId}/from-sample`, { + method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(), + }, +); + +/** 发布草稿并退役同编码旧版本。 */ +export const publishOrderDocumentProfile = (profileId: number, expectedLockVersion: number) => + requestJson( + `/api/admin/shipping-notice/order-document-profiles/${profileId}/publish`, + { method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth() }, + ); + +/** 从不可变版本复制下一草稿。 */ +export const cloneOrderDocumentProfile = (profileId: number) => + requestJson( + `/api/admin/shipping-notice/order-document-profiles/${profileId}/clone`, + { method: 'POST', ...jsonAuth() }, + ); + +/** 退役当前发布版本。 */ +export const retireOrderDocumentProfile = (profileId: number) => + requestJson( + `/api/admin/shipping-notice/order-document-profiles/${profileId}/retire`, + { method: 'POST', ...jsonAuth() }, + ); + +/** 删除错误草稿。 */ +export const deleteOrderDocumentProfile = (profileId: number) => + requestJson(`/api/admin/shipping-notice/order-document-profiles/${profileId}`, { + method: 'DELETE', ...auth(), + }); diff --git a/frontend/src/features/admin/api/shipping-order-schema.api.ts b/frontend/src/features/admin/api/shipping-order-schema.api.ts index 4ff3eaf9..5595b5f7 100644 --- a/frontend/src/features/admin/api/shipping-order-schema.api.ts +++ b/frontend/src/features/admin/api/shipping-order-schema.api.ts @@ -25,6 +25,12 @@ const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getA export const getShippingOrderSchemaState = () => requestJson('/api/admin/shipping-order-schema', auth()); +/** 保存订单字段模板中的自动建单总开关。 */ +export const saveShippingOrderAutoCreationPolicy = (enabled: boolean) => + requestJson<{ enabled: boolean }>('/api/admin/shipping-order-schema/auto-creation-policy', { + method: 'PUT', body: JSON.stringify({ enabled }), ...jsonAuth(), + }); + /** 初始化全局唯一订单 Schema。 */ export const initializeShippingOrderSchema = (payload: { display_name: string; description?: string }) => requestJson('/api/admin/shipping-order-schema', { @@ -116,7 +122,11 @@ export const getShippingOrderExtractionAudit = (extractionId: number) => /** 整体保存草稿字段配置及每个字段的版本纳入状态。 */ export const saveShippingOrderSchemaDraft = ( versionId: number, - payload: { fields: ShippingOrderFieldConfig[]; change_note?: string; expected_lock_version: number }, + payload: { + fields: ShippingOrderFieldConfig[]; + change_note?: string; + expected_lock_version: number; + }, ) => requestJson(`/api/admin/shipping-order-schema/versions/${versionId}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(), }); diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts index 715f423a..34ca3e91 100644 --- a/frontend/src/features/admin/constants/modules.ts +++ b/frontend/src/features/admin/constants/modules.ts @@ -15,8 +15,8 @@ export interface AdminModuleMeta { export interface ShippingConfigSubModuleMeta { id: ShippingConfigSubModuleId; - routeName: 'AdminShippingInventory' | 'AdminShippingIdentityRules' | 'AdminShippingOrderExtractionRuns'; - path: 'shipping-notice' | 'shipping-identity-rules' | 'shipping-order-extraction-runs'; + routeName: 'AdminShippingInventory' | 'AdminShippingIdentityRules' | 'AdminShippingOrderExtractionRuns' | 'AdminShippingOrderDocumentProfiles'; + path: 'shipping-notice' | 'shipping-identity-rules' | 'shipping-order-extraction-runs' | 'shipping-order-document-profiles'; labelKey: string; } @@ -47,6 +47,7 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [ { id: 'inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingInventory' }, { id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules' }, { id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns' }, + { id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles' }, ]; export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [ diff --git a/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue b/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue index 36ade923..15c976b8 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue @@ -371,61 +371,31 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =

    {{ t('admin.agent.runtimeBinding.title') }}

    {{ t('admin.agent.runtimeBinding.subtitle') }}

    -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    - +
    + + + + + + + + + + +
    {{ t('admin.agent.runtimeBinding.capability') }}{{ t('admin.agent.runtimeBinding.provider') }}{{ t('admin.agent.runtimeBinding.timeout') }}{{ t('admin.agent.runtimeBinding.maxAttempts') }}
    {{ t('admin.agent.runtimeBinding.orderExtraction') }}

    {{ t('admin.agent.runtimeBinding.noProvider') }}

    +
    +

    {{ t('admin.agent.runtimeBinding.executorGovernance') }}

    +
    +
    +
    +
    +
    +