From 4fbaed2b4c265bf797f4e2e81eed8b27b37a9be2 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 16 Jul 2026 08:16:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E8=B4=A7=E4=BB=A3=E5=AE=A2=E6=88=B7=E7=AE=A1=E7=90=86=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=EF=BC=8C=E6=94=AF=E6=8C=81=E5=AE=A2=E6=88=B7=E5=AF=BC?= =?UTF-8?q?=E5=85=A5=E3=80=81=E8=AF=86=E5=88=AB=E8=AF=81=E6=8D=AE=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E4=B8=8E=E5=AE=A2=E6=88=B7=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.shared | 4 + backend/app/api/admin/__init__.py | 1 + backend/app/api/admin/shipping_customers.py | 244 ++++ backend/app/api/chat.py | 188 ++- backend/app/api/shipping_notice_tools.py | 9 + backend/app/api/workspace/shipping_notice.py | 36 + backend/app/core/config/settings.py | 6 + backend/app/models/__init__.py | 17 + backend/app/models/shipping.py | 17 +- backend/app/models/shipping_customer.py | 176 +++ .../app/models/shipping_customer_import.py | 86 ++ .../models/shipping_customer_resolution.py | 54 + backend/app/services/admin/__init__.py | 4 + .../admin/shipping_customer_import_service.py | 706 +++++++++ .../admin/shipping_customer_service.py | 342 +++++ .../services/agent_registry/handlers/base.py | 2 +- .../handlers/shipping_notice.py | 310 +++- .../app/services/chat/executors/__init__.py | 21 +- .../app/services/chat/executors/builtin.py | 4 +- .../app/services/chat/executors/dify_chat.py | 9 +- backend/app/services/chat/executors/hybrid.py | 10 +- backend/app/services/chat/log_service.py | 62 +- backend/app/services/chat/stream_relay.py | 2 +- backend/app/services/dify.py | 44 +- backend/app/services/schedule/job_options.py | 2 +- .../shipping_notice/batch_from_intakes.py | 23 +- .../shipping_notice/business_case_service.py | 88 ++ .../shipping_notice/business_fingerprint.py | 6 +- .../business_numbering_service.py | 170 +++ .../shipping_notice/candidate_validation.py | 6 +- .../app/services/shipping_notice/constants.py | 1 + .../customer_auto_resolution.py | 425 ++++++ .../shipping_notice/customer_identity_gate.py | 231 +++ .../shipping_notice/customer_normalization.py | 132 ++ .../customer_shadow_resolution.py | 274 ++++ .../document_candidate_persist.py | 7 +- .../app/services/shipping_notice/export.py | 8 +- .../shipping_notice/fulfillment_workflow.py | 15 +- .../shipping_notice/intake_business_parser.py | 1 - .../shipping_notice/intake_service.py | 33 +- .../shipping_notice/inventory_file_store.py | 2 +- .../shipping_notice/inventory_rpa_workflow.py | 17 +- .../inventory_snapshot_store.py | 2 +- .../shipping_notice/inventory_source_gate.py | 14 +- .../inventory_source_identity.py | 16 +- .../shipping_notice/inventory_source_rules.py | 30 +- .../shipping_notice/inventory_sources.py | 32 +- .../shipping_notice/inventory_workflow.py | 10 +- .../shipping_notice/notice_line_constants.py | 11 +- .../shipping_notice/notice_line_table.py | 15 +- .../services/shipping_notice/notice_lines.py | 26 +- .../open_existing_reservation_backfill.py | 216 +++ .../services/shipping_notice/openapi_spec.py | 39 +- .../order_candidate_builder.py | 2 +- .../shipping_notice/order_extraction.py | 622 +++++++- .../shipping_notice/progress_workflow.py | 7 +- .../services/shipping_notice/query_service.py | 121 +- backend/app/services/shipping_notice/rpa.py | 2 +- .../services/shipping_notice/state_machine.py | 51 +- .../services/shipping_notice/task_workflow.py | 119 +- backend/app/services/shipping_notice/tools.py | 4 +- .../config/shipping_inventory_sources.yaml | 62 +- .../a2c3d4e5f6a7_shipping_customer_imports.py | 108 ++ ...7b8_shipping_customer_shadow_resolution.py | 66 + ...inventory_source_type_to_connector_type.py | 43 + ...4d5e6_shipping_customer_case_foundation.py | 175 +++ backend/tests/conftest.py | 2 +- .../test_shipping_customer_import_service.py | 199 +++ .../admin/test_shipping_customer_service.py | 165 +++ .../tests/test_admin_shipping_customers.py | 217 +++ backend/tests/test_chat_executors_registry.py | 37 +- backend/tests/test_chat_user_attachments.py | 98 ++ .../tests/test_dify_workflow_reliability.py | 73 + backend/tests/test_freight_rpa_worker.py | 4 +- .../tests/test_shipping_business_numbering.py | 181 +++ .../test_shipping_customer_auto_resolution.py | 283 ++++ .../test_shipping_customer_identity_gate.py | 175 +++ .../test_shipping_customer_migrations.py | 89 ++ ...est_shipping_customer_shadow_resolution.py | 177 +++ ..._shipping_inventory_connector_migration.py | 35 + backend/tests/test_shipping_notice_batches.py | 273 +++- .../test_shipping_notice_business_case.py | 149 ++ .../test_shipping_notice_business_dedup.py | 6 +- backend/tests/test_shipping_notice_extract.py | 6 +- ...hipping_notice_inventory_snapshot_reuse.py | 20 +- ...t_shipping_notice_inventory_source_gate.py | 30 + ...hipping_notice_inventory_sources_config.py | 22 +- .../test_shipping_notice_openapi_contract.py | 77 + .../test_shipping_notice_order_extraction.py | 1213 +++++++++++++++- ...st_shipping_notice_rpa_trigger_for_task.py | 12 +- backend/tests/test_shipping_notice_tools.py | 113 +- .../tests/test_tasks_0304_chat_features.py | 77 + docs/demand.md | 21 +- docs/features/shipping-notice/business.md | 81 +- .../shipping-notice/inventory_source_plan.md | 13 +- docs/features/shipping-notice/technical.md | 1259 +++++++++++++---- docs/funclist.md | 13 +- docs/openapi/shipping_notice_tools.dify.json | 86 +- docs/tec.md | 21 +- docs/test_plan_matrix.md | 3 +- .../src/app/router/routes/admin.routes.ts | 7 + .../src/app/router/routes/workspace.routes.ts | 14 +- .../src/constants/shippingNoticeActions.ts | 2 + frontend/src/features/admin/api/admin.api.ts | 127 +- .../src/features/admin/constants/modules.ts | 1 + .../ShippingCustomersPage.vue | 86 ++ .../components/CustomerFormModal.vue | 54 + .../components/CustomerIdentifiersPanel.vue | 95 ++ .../components/CustomerImportDialog.vue | 121 ++ .../components/CustomerShadowQualityPanel.vue | 85 ++ .../composables/useShippingCustomersAdmin.ts | 327 +++++ .../admin/types/shipping-customer.types.ts | 177 +++ .../src/features/chat/api/chat.api.spec.ts | 87 ++ frontend/src/features/chat/api/chat.api.ts | 27 +- .../src/features/chat/api/shipping.api.ts | 15 + .../features/chat/components/ChatInputBar.vue | 184 ++- .../chat/components/ChatViewOverlays.vue | 9 + .../ShippingBatchWorkspaceDrawer.vue | 7 +- .../ShippingCustomerConfirmDialog.vue | 41 + .../ShippingNoticeCandidateReview.vue | 46 +- .../messages/ChatMessageAttachmentList.vue | 63 + .../components/messages/ChatMessageBubble.vue | 142 +- .../features/chat/composables/useChat.spec.ts | 128 +- .../src/features/chat/composables/useChat.ts | 122 +- .../composables/useChatAttachments.spec.ts | 132 ++ .../chat/composables/useChatAttachments.ts | 62 +- .../features/chat/composables/useChatPage.ts | 7 + .../chat/composables/useChatShipping.spec.ts | 88 +- .../chat/composables/useChatShipping.ts | 341 ++++- .../features/chat/composables/useChatTurn.ts | 8 +- .../chat/page/useChatPageConversation.spec.ts | 32 +- .../chat/page/useChatPageMarkdown.spec.ts | 87 ++ .../features/chat/page/useChatPageMarkdown.ts | 9 + .../chat/page/useChatPageSend.spec.ts | 121 ++ .../src/features/chat/page/useChatPageSend.ts | 42 +- .../chat/shipping/shippingConversation.ts | 2 +- .../features/chat/shipping/shippingTaskId.ts | 15 +- .../shipping/useChatShippingMenuHandler.ts | 10 + .../shipping/useChatShippingRefresh.spec.ts | 29 +- .../chat/shipping/useChatShippingRefresh.ts | 19 +- .../useChatShippingSendHandler.spec.ts | 139 +- .../shipping/useChatShippingSendHandler.ts | 32 +- .../shipping/useShippingNoticeIntakes.spec.ts | 35 + .../chat/shipping/useShippingNoticeIntakes.ts | 57 +- .../src/features/chat/types/chat.types.ts | 55 +- .../features/chat/types/shipping.api.types.ts | 40 +- .../src/features/chat/types/shipping.types.ts | 38 +- .../chat/utils/attachmentCard.utils.spec.ts | 188 +++ .../chat/utils/attachmentCard.utils.ts | 179 +++ .../workspace/components/WorkspaceSidebar.vue | 87 +- .../composables/useWorkspaceNavigation.ts | 3 +- .../features/workspace/constants/routes.ts | 4 +- frontend/src/locales/en/admin.json | 15 +- frontend/src/locales/en/chat.json | 24 +- frontend/src/locales/en/errors.json | 29 +- frontend/src/locales/en/workspace.json | 2 + frontend/src/locales/th/admin.json | 15 +- frontend/src/locales/th/chat.json | 24 +- frontend/src/locales/th/errors.json | 29 +- frontend/src/locales/th/workspace.json | 14 + frontend/src/locales/zh-CN/admin.json | 15 +- frontend/src/locales/zh-CN/chat.json | 24 +- frontend/src/locales/zh-CN/errors.json | 29 +- frontend/src/locales/zh-CN/workspace.json | 2 + frontend/src/locales/zh-TW/admin.json | 15 +- frontend/src/locales/zh-TW/chat.json | 24 +- frontend/src/locales/zh-TW/errors.json | 29 +- frontend/src/locales/zh-TW/workspace.json | 3 + frontend/src/shared/api/client.ts | 8 +- scripts/rpa/README.md | 10 +- scripts/rpa/crane_export_smoke.py | 2 +- scripts/rpa/dsv_driver.py | 2 +- scripts/rpa/dsv_export_smoke.py | 6 +- scripts/rpa/dsv_report_export.py | 2 +- scripts/rpa/freight_rpa_worker.py | 30 +- scripts/rpa/run_inventory_batch_trigger.py | 6 +- 176 files changed, 14011 insertions(+), 994 deletions(-) create mode 100644 backend/app/api/admin/shipping_customers.py create mode 100644 backend/app/models/shipping_customer.py create mode 100644 backend/app/models/shipping_customer_import.py create mode 100644 backend/app/models/shipping_customer_resolution.py create mode 100644 backend/app/services/admin/shipping_customer_import_service.py create mode 100644 backend/app/services/admin/shipping_customer_service.py create mode 100644 backend/app/services/shipping_notice/business_case_service.py create mode 100644 backend/app/services/shipping_notice/business_numbering_service.py create mode 100644 backend/app/services/shipping_notice/customer_auto_resolution.py create mode 100644 backend/app/services/shipping_notice/customer_identity_gate.py create mode 100644 backend/app/services/shipping_notice/customer_normalization.py create mode 100644 backend/app/services/shipping_notice/customer_shadow_resolution.py create mode 100644 backend/app/services/shipping_notice/open_existing_reservation_backfill.py create mode 100644 backend/migrations/versions/a2c3d4e5f6a7_shipping_customer_imports.py create mode 100644 backend/migrations/versions/b3d4e5f6a7b8_shipping_customer_shadow_resolution.py create mode 100644 backend/migrations/versions/c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type.py create mode 100644 backend/migrations/versions/f1a2b3c4d5e6_shipping_customer_case_foundation.py create mode 100644 backend/tests/services/admin/test_shipping_customer_import_service.py create mode 100644 backend/tests/services/admin/test_shipping_customer_service.py create mode 100644 backend/tests/test_admin_shipping_customers.py create mode 100644 backend/tests/test_chat_user_attachments.py create mode 100644 backend/tests/test_shipping_business_numbering.py create mode 100644 backend/tests/test_shipping_customer_auto_resolution.py create mode 100644 backend/tests/test_shipping_customer_identity_gate.py create mode 100644 backend/tests/test_shipping_customer_migrations.py create mode 100644 backend/tests/test_shipping_customer_shadow_resolution.py create mode 100644 backend/tests/test_shipping_inventory_connector_migration.py create mode 100644 backend/tests/test_shipping_notice_business_case.py create mode 100644 backend/tests/test_shipping_notice_openapi_contract.py create mode 100644 frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue create mode 100644 frontend/src/features/admin/modules/shipping-customers/components/CustomerFormModal.vue create mode 100644 frontend/src/features/admin/modules/shipping-customers/components/CustomerIdentifiersPanel.vue create mode 100644 frontend/src/features/admin/modules/shipping-customers/components/CustomerImportDialog.vue create mode 100644 frontend/src/features/admin/modules/shipping-customers/components/CustomerShadowQualityPanel.vue create mode 100644 frontend/src/features/admin/modules/shipping-customers/composables/useShippingCustomersAdmin.ts create mode 100644 frontend/src/features/admin/types/shipping-customer.types.ts create mode 100644 frontend/src/features/chat/api/chat.api.spec.ts create mode 100644 frontend/src/features/chat/components/ShippingCustomerConfirmDialog.vue create mode 100644 frontend/src/features/chat/components/messages/ChatMessageAttachmentList.vue create mode 100644 frontend/src/features/chat/composables/useChatAttachments.spec.ts create mode 100644 frontend/src/features/chat/page/useChatPageMarkdown.spec.ts create mode 100644 frontend/src/features/chat/page/useChatPageSend.spec.ts create mode 100644 frontend/src/features/chat/shipping/useShippingNoticeIntakes.spec.ts create mode 100644 frontend/src/features/chat/utils/attachmentCard.utils.spec.ts create mode 100644 frontend/src/features/chat/utils/attachmentCard.utils.ts diff --git a/.env.shared b/.env.shared index 46a40beb..9c19e6de 100644 --- a/.env.shared +++ b/.env.shared @@ -160,3 +160,7 @@ FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈 FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除) # Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. FREIGHT_RPA_MOCK=false +# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。 +SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=false +# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。 +SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300 diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index de51361d..5aa19161 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -19,5 +19,6 @@ import app.api.admin.permissions # noqa: F401 import app.api.admin.users # noqa: F401 import app.api.admin.wecom # noqa: F401 import app.api.admin.announcements # noqa: F401 +import app.api.admin.shipping_customers # noqa: F401 __all__ = ['admin_bp'] diff --git a/backend/app/api/admin/shipping_customers.py b/backend/app/api/admin/shipping_customers.py new file mode 100644 index 00000000..8fe1ef3c --- /dev/null +++ b/backend/app/api/admin/shipping_customers.py @@ -0,0 +1,244 @@ +""" +backend/app/api/admin/shipping_customers.py + +用途:货代客户主数据、识别证据与期初导入管理 API。 +依赖:admin blueprint、require_admin、shipping_customer_* services、customer_shadow_resolution、customer_auto_resolution。 +逻辑:薄路由完成鉴权、参数读取和文件响应;业务校验与事务全部委托服务层。 +""" + +from __future__ import annotations + +from io import BytesIO + +from flask import g, jsonify, request, send_file + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.errors import ValidationError +from app.services.admin import shipping_customer_import_service, shipping_customer_service +from app.services.shipping_notice.customer_shadow_resolution import ( + get_shadow_quality_report, + label_shadow_resolution, +) +from app.models import ShippingTask +from app.services.shipping_notice.customer_auto_resolution import ( + backfill_historical_task_customer, + correct_numbered_task_customer, + get_auto_resolution_metrics, +) +from app.services.shipping_notice.query_service import get_task_by_ref + +XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + + +def _actor_id() -> int | None: + """返回 require_admin 已解析的当前管理员 ID。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _query_params() -> dict[str, str]: + """将管理列表 query 参数转换为普通字符串字典。""" + return {key: str(value) for key, value in request.args.items()} + + +@admin_bp.route('/shipping-customers', methods=['GET']) +@require_admin +def list_shipping_customers(): + """分页查询货代标准客户。""" + return jsonify(shipping_customer_service.list_customers(_query_params())) + + +@admin_bp.route('/shipping-customers/', methods=['GET']) +@require_admin +def get_shipping_customer(customer_id: int): + """查询单个标准客户及识别证据。""" + return jsonify(shipping_customer_service.get_customer(customer_id)) + + +@admin_bp.route('/shipping-customers', methods=['POST']) +@require_admin +def create_shipping_customer(): + """创建货代标准客户。""" + return jsonify(shipping_customer_service.create_customer(request.get_json(silent=True) or {}, actor_id=_actor_id())), 201 + + +@admin_bp.route('/shipping-customers/', methods=['PUT']) +@require_admin +def update_shipping_customer(customer_id: int): + """更新货代标准客户。""" + return jsonify(shipping_customer_service.update_customer( + customer_id, + request.get_json(silent=True) or {}, + actor_id=_actor_id(), + )) + + +@admin_bp.route('/shipping-customers//deactivate', methods=['POST']) +@require_admin +def deactivate_shipping_customer(customer_id: int): + """停用标准客户并保留历史引用。""" + return jsonify(shipping_customer_service.deactivate_customer(customer_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-customers//identifiers', methods=['POST']) +@require_admin +def create_shipping_customer_identifier(customer_id: int): + """为客户新增名称、邮箱、域名或模板指纹识别证据。""" + return jsonify(shipping_customer_service.create_identifier( + customer_id, + request.get_json(silent=True) or {}, + actor_id=_actor_id(), + )), 201 + + +@admin_bp.route('/shipping-customer-identifiers/', methods=['PUT']) +@require_admin +def update_shipping_customer_identifier(identifier_id: int): + """审核、停用或调整客户识别证据的自动匹配授权。""" + return jsonify(shipping_customer_service.update_identifier( + identifier_id, + request.get_json(silent=True) or {}, + actor_id=_actor_id(), + )) + + +@admin_bp.route('/shipping-customers/import-template', methods=['GET']) +@require_admin +def download_shipping_customer_import_template(): + """下载期初客户标准 Excel 模板。""" + content = shipping_customer_import_service.build_import_template() + return send_file( + BytesIO(content), + as_attachment=True, + download_name='shipping_customer_import_template.xlsx', + mimetype=XLSX_MIME_TYPE, + ) + + +@admin_bp.route('/shipping-customer-imports', methods=['POST']) +@require_admin +def upload_shipping_customer_import(): + """上传并预检期初客户 Excel,不直接写正式客户表。""" + upload = request.files.get('file') + if upload is None: + raise ValidationError( + 'Customer import file is required', + code='SHIPPING.CUSTOMER_IMPORT_FILE_REQUIRED', + ) + source_system = str(request.form.get('source_system') or 'INITIAL_EXCEL').strip() + return jsonify(shipping_customer_import_service.create_import_batch( + upload, + source_system=source_system, + actor_id=_actor_id(), + )), 201 + + +@admin_bp.route('/shipping-customer-imports/', methods=['GET']) +@require_admin +def get_shipping_customer_import(batch_id: int): + """查询导入批次统计、错误、警告和逐行决定。""" + return jsonify(shipping_customer_import_service.get_import_batch(batch_id)) + + +@admin_bp.route('/shipping-customer-import-rows//decision', methods=['PUT']) +@require_admin +def decide_shipping_customer_import_row(row_id: int): + """保存警告行的新增、更新、合并或跳过决定。""" + return jsonify(shipping_customer_import_service.decide_import_row( + row_id, + request.get_json(silent=True) or {}, + )) + + +@admin_bp.route('/shipping-customer-imports//publish', methods=['POST']) +@require_admin +def publish_shipping_customer_import(batch_id: int): + """单事务发布已完成预检和冲突决定的客户导入批次。""" + return jsonify(shipping_customer_import_service.publish_import_batch(batch_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-customer-imports//reconciliation', methods=['GET']) +@require_admin +def download_shipping_customer_import_reconciliation(batch_id: int): + """下载导入批次逐行对账 CSV。""" + content, filename = shipping_customer_import_service.build_reconciliation_csv(batch_id) + return send_file( + BytesIO(content), + as_attachment=True, + download_name=filename, + mimetype='text/csv; charset=utf-8', + ) + + +@admin_bp.route('/shipping-customer-shadow-report', methods=['GET']) +@require_admin +def get_shipping_customer_shadow_report(): + """查询客户影子识别分布、已标注准确率和最近样本。""" + try: + limit = int(request.args.get('limit') or 100) + except (TypeError, ValueError) as exc: + raise ValidationError('Invalid report limit') from exc + report = get_shadow_quality_report(limit=limit) + report['auto_resolution'] = get_auto_resolution_metrics() + return jsonify(report) + + +@admin_bp.route('/shipping-customers/historical-task-backfill', methods=['POST']) +@require_admin +def backfill_shipping_historical_task_customer(): + """管理员为历史无业务单任务确认客户;默认不生成历史业务编号。""" + data = request.get_json(silent=True) or {} + task_no = str(data.get('task_no') or '').strip().upper() + try: + customer_id = int(data.get('customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('Customer id is required') from exc + task = ShippingTask.query.filter_by(task_no=task_no).first() + if task is None: + raise ValidationError('Historical task not found', code='SHIPPING.HISTORICAL_TASK_NOT_FOUND') + try: + return jsonify(backfill_historical_task_customer(task, customer_id=customer_id, actor_id=_actor_id())) + except ValueError as exc: + raise ValidationError(str(exc), code='SHIPPING.HISTORICAL_BACKFILL_INVALID') from exc + + +@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST']) +@require_admin +def correct_shipping_numbered_task_customer(): + """管理员更正已编号任务客户;保留原号作废并生成有替代关系的新号。""" + data = request.get_json(silent=True) or {} + task_ref = str(data.get('task_ref') or data.get('task_no') or '').strip().upper() + if not task_ref: + raise ValidationError( + 'Task reference is required', + code='SHIPPING.CUSTOMER_CORRECTION_TASK_REQUIRED', + ) + try: + customer_id = int(data.get('customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('Customer id is required', code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED') from exc + task = get_task_by_ref(task_ref) + if task is None: + raise ValidationError('Shipping task not found', code='SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING') + return jsonify(correct_numbered_task_customer( + task, + customer_id=customer_id, + reason=str(data.get('reason') or ''), + actor_id=_actor_id(), + )) + + +@admin_bp.route('/shipping-customer-shadow-resolutions//label', methods=['PUT']) +@require_admin +def label_shipping_customer_shadow_resolution(resolution_id: int): + """为影子识别样本写入人工客户真值,不执行业务绑定。""" + data = request.get_json(silent=True) or {} + try: + customer_id = int(data.get('customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Customer id is required', + code='SHIPPING.CUSTOMER_SHADOW_LABEL_REQUIRED', + details={'field': 'customer_id'}, + ) from exc + return jsonify(label_shadow_resolution(resolution_id, customer_id=customer_id, actor_id=_actor_id())) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 39b3d82b..5cecd6de 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -12,6 +12,7 @@ import ntpath import posixpath import tempfile import os +import re import subprocess import uuid import json @@ -42,11 +43,100 @@ from app.core.errors import ( chat_bp = Blueprint('chat', __name__) SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' +CHAT_USER_ATTACHMENT_LIMIT = 20 +CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024 +CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'} +CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'} PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip() +def _normalize_user_attachments(value) -> list[dict]: + """ + 校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。 + + 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。 + + Args: + value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。 + + Returns: + 可安全写入 JSON 的附件快照列表;非法项目被忽略。 + """ + if not isinstance(value, list): + return [] + normalized: list[dict] = [] + for item in value[:CHAT_USER_ATTACHMENT_LIMIT]: + if not isinstance(item, dict): + continue + raw_name = str(item.get('name') or '') + basename = re.split(r'[\\/]+', raw_name)[-1] + name = re.sub(r'[\x00-\x1f\x7f]', '', basename).strip()[:255] + attachment_type = str(item.get('type') or '').strip().lower() + source = str(item.get('source') or '').strip().lower() + if not name or attachment_type not in CHAT_USER_ATTACHMENT_TYPES or source not in CHAT_USER_ATTACHMENT_SOURCES: + continue + snapshot = { + 'name': name, + 'type': attachment_type, + 'source': source, + } + attachment_id = re.sub(r'[\x00-\x1f\x7f]', '', str(item.get('id') or '')).strip()[:128] + if attachment_id: + snapshot['id'] = attachment_id + extension = str(item.get('extension') or '').strip().lower() + if re.fullmatch(r'[a-z0-9]{1,16}', extension): + snapshot['extension'] = extension + try: + size = int(item.get('size')) if item.get('size') is not None else None + except (TypeError, ValueError): + size = None + if size is not None and 0 <= size <= CHAT_USER_ATTACHMENT_MAX_SIZE: + snapshot['size'] = size + normalized.append(snapshot) + return normalized + + +def _merge_user_attachments_from_terminal_event( + event_data: dict, + *, + user_id: int, + agent_id: int, + session_id: str, + user_attachments: list[dict], +) -> bool: + """ + 在终态 SSE 已给出 ChatLog ID 后,按归属校验合并用户附件快照。 + + Args: + event_data: 上游终态 SSE 数据,必须包含正整数 chat_log_id。 + user_id: 当前用户 ID。 + agent_id: 当前 Agent ID。 + session_id: 当前 HXOPS 本地会话 ID。 + user_attachments: 已完成白名单校验的附件快照。 + + Returns: + 找到归属一致的 ChatLog 并成功合并时返回 True,否则返回 False。 + """ + if not user_attachments: + return False + try: + chat_log_id = int(event_data.get('chat_log_id') or 0) + except (TypeError, ValueError): + return False + if chat_log_id <= 0: + return False + from app.services.chat.log_service import merge_chat_log_payload + return merge_chat_log_payload( + chat_log_id=chat_log_id, + user_id=int(user_id or 0), + agent_id=int(agent_id or 0), + session_id=session_id, + payload_patch={'user_attachments': user_attachments}, + ) + + def _build_chat_adapter_hints( *, shipping_task_id: str | None = None, @@ -1030,19 +1120,29 @@ def get_chat_messages(): messages = [] agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic' for log in logs: - if log.query: - messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)}) + raw_payload = log.payload if isinstance(log.payload, dict) else {} + user_attachments = _normalize_user_attachments(raw_payload.get('user_attachments')) + assistant_payload = { + key: value + for key, value in raw_payload.items() + if key != 'user_attachments' + } + if log.query or user_attachments: + user_msg = {'role': 'user', 'content': _user_facing_chat_query(log.query or '', agent_code=agent_code)} + if user_attachments: + user_msg['attachments'] = user_attachments + messages.append(user_msg) if ( not log.answer and not log.message_type - and not log.payload + and not assistant_payload ): continue if ( log.query and log.answer == log.query and (not log.message_type or log.message_type == 'text') - and not log.payload + and not assistant_payload ): continue assistant_msg = { @@ -1056,8 +1156,8 @@ def get_chat_messages(): assistant_msg['run_id'] = log.run_id if log.message_type: assistant_msg['type'] = log.message_type - if log.payload: - assistant_msg['payload'] = log.payload + if assistant_payload: + assistant_msg['payload'] = assistant_payload messages.append(assistant_msg) return jsonify(messages) @@ -1279,7 +1379,9 @@ def chat_completions(): """ data = request.get_json() or {} query = data.get('query') - display_query = str(data.get('display_query') or query or '').strip() + display_query = str( + data.get('display_query') if 'display_query' in data else query or '' + ).strip() # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() @@ -1293,6 +1395,8 @@ def chat_completions(): if str(item or '').strip() }) kb_type = data.get('kb_type', '企业知识库') + user_attachments = _normalize_user_attachments(data.get('user_attachments')) + session_title = display_query or (user_attachments[0]['name'] if user_attachments else str(query or '').strip()) files = data.get('files') request_id = uuid.uuid4().hex[:12] user = getattr(g, 'current_user', None) @@ -1350,7 +1454,7 @@ def chat_completions(): user_id, agent_id, existing_session.session_id, - title=display_query, + title=session_title, status='running', ) external_conversation_id = session.external_conversation_id @@ -1372,13 +1476,20 @@ def chat_completions(): user_id, agent_id, conversation_id, - title=display_query, + title=session_title, status='running', external_conversation_id=conversation_id, ) external_conversation_id = session.external_conversation_id else: - session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running') + session = _ensure_chat_session(user_id, agent_id, None, title=session_title, status='running') + + # [STEP 1] 流式响应可能在原请求 DB Session 清理后才开始迭代;提前快照会话标量, + # 避免 Handler 的事务提交使 ORM 对象过期后触发 DetachedInstanceError。 + local_session_id = str(session.session_id) + initial_session_status = str(session.status or 'running') + initial_external_conversation_id = str(external_conversation_id or '').strip() or None + stream_session = SimpleNamespace(session_id=local_session_id) normalized_files: list[dict] | None = None if files is not None: @@ -1414,8 +1525,8 @@ def chat_completions(): display_query=display_query, user=user_proxy, agent=agent_proxy, - session=session, - external_conversation_id=external_conversation_id, + session=stream_session, + external_conversation_id=initial_external_conversation_id, request_id=request_id, normalized_files=normalized_files, adapter_hints=_build_chat_adapter_hints( @@ -1438,8 +1549,8 @@ def chat_completions(): agent=agent_proxy, query=query, agent_id=agent_id, - session_id=session.session_id, - external_conversation_id=external_conversation_id, + session_id=local_session_id, + external_conversation_id=initial_external_conversation_id, normalized_files=normalized_files, kb_type=kb_type, leave_supported=leave_supported, @@ -1451,13 +1562,13 @@ def chat_completions(): query, user_proxy.id, agent_proxy, - external_conversation_id, + initial_external_conversation_id, request_id=request_id, - session_id=session.session_id, + session_id=local_session_id, files=normalized_files, inputs=build_chat_dify_inputs( agent_proxy, - session_id=session.session_id, + session_id=local_session_id, request_id=request_id, trigger_source="frontend_chat", user_role=user_proxy.role, @@ -1480,14 +1591,14 @@ def chat_completions(): relay_first_chunk_at: float | None = None created_event = { 'event': 'session_created', - 'conversation_id': session.session_id, - 'provider_conversation_id': session.external_conversation_id, - 'session_status': session.status, + 'conversation_id': local_session_id, + 'provider_conversation_id': initial_external_conversation_id, + 'session_status': initial_session_status, } yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n" - known_provider_conversation_id = session.external_conversation_id - known_status = session.status + known_provider_conversation_id = initial_external_conversation_id + known_status = initial_session_status emitted_handler_state_keys: set[str] = set() from app.services.chat.stream_relay import ( @@ -1499,6 +1610,7 @@ def chat_completions(): yield preface_line try: + merged_attachment_log_ids: set[int] = set() for chunk in generator: if relay_first_chunk_at is None: relay_first_chunk_at = time.perf_counter() @@ -1515,6 +1627,20 @@ def chat_completions(): provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None event_name = event_data.get('event') + if event_name in ('error', 'message_end', 'workflow_finished') and user_attachments: + try: + attachment_chat_log_id = int(event_data.get('chat_log_id') or 0) + except (TypeError, ValueError): + attachment_chat_log_id = 0 + if attachment_chat_log_id > 0 and attachment_chat_log_id not in merged_attachment_log_ids: + if _merge_user_attachments_from_terminal_event( + event_data, + user_id=user_id, + agent_id=agent_id, + session_id=local_session_id, + user_attachments=user_attachments, + ): + merged_attachment_log_ids.add(attachment_chat_log_id) should_touch = False if provider_conversation_id and provider_conversation_id != known_provider_conversation_id: known_provider_conversation_id = provider_conversation_id @@ -1530,7 +1656,7 @@ def chat_completions(): updated_session = _update_chat_session( user_id, agent_id, - session.session_id, + local_session_id, status=known_status, external_conversation_id=known_provider_conversation_id, touch=True, @@ -1539,7 +1665,7 @@ def chat_completions(): known_status = updated_session.status event_data['provider_conversation_id'] = provider_conversation_id - event_data['conversation_id'] = session.session_id + event_data['conversation_id'] = local_session_id event_data['session_status'] = known_status if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'): relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None @@ -1547,7 +1673,7 @@ def chat_completions(): current_app.logger.info( '[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s', request_id, - session.session_id, + local_session_id, relay_first_ms, relay_total_ms, event_name, @@ -1557,7 +1683,7 @@ def chat_completions(): 'total_relay_ms': relay_total_ms, } yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n" - if event_name in ('message_end', 'workflow_finished'): + if event_name in ('error', 'message_end', 'workflow_finished'): for terminal_line in iter_handler_terminal_sse( relay_stream_ctx, event_data, @@ -1565,9 +1691,15 @@ def chat_completions(): ): yield terminal_line except Exception as exc: - current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id) - payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'} + current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id) + payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'} yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" + for terminal_line in iter_handler_terminal_sse( + relay_stream_ctx, + payload, + emitted_keys=emitted_handler_state_keys, + ): + yield terminal_line # 返回 SSE 响应,mimetype 设为 text/event-stream return Response( diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 1768593d..dad7b020 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -291,6 +291,15 @@ def tool_confirm_inventory_source(): return jsonify(shipping_tools.confirm_inventory_source(_payload())) +@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST']) +def tool_confirm_customer(): + """ + 确认任务所属标准客户(仅提交 customer_id)。 + 【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。 + """ + return jsonify(shipping_tools.confirm_customer(_payload())) + + @shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST']) def tool_generate_shipment_excel(): """ diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 63b51fca..60d99253 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -40,6 +40,10 @@ from app.services.shipping_notice.query_service import ( task_export_error_message, ) from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state +from app.services.shipping_notice.customer_identity_gate import ( + confirm_task_customer, + list_customer_options, +) workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) @@ -79,6 +83,38 @@ def workspace_shipping_batches(): limit = int(request.args.get('limit') or 100) return jsonify(list_batches_for_user(user.id, limit=limit)) + +@workspace_shipping_notice_bp.route('/shipping-customers', methods=['GET']) +def workspace_shipping_customers(): + """列出可供当前业务用户确认的启用标准客户。""" + _require_user() + query = str(request.args.get('q') or '').strip() + try: + limit = int(request.args.get('limit') or 100) + except (TypeError, ValueError) as exc: + raise ValidationError('Invalid customer limit') from exc + return jsonify(list_customer_options(query=query, limit=limit)) + + +@workspace_shipping_notice_bp.route('/shipping-tasks//confirm-customer', methods=['POST']) +def workspace_confirm_shipping_customer(task_no: str): + """为当前用户任务确认标准客户,并原子生成正式业务编号。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + try: + customer_id = int(data.get('customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Customer id is required', + code='SHIPPING.CUSTOMER_CONFIRMATION_CUSTOMER_REQUIRED', + details={'field': 'customer_id'}, + ) from exc + updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id) + return jsonify(serialize_task_detail(updated)) + @workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) def workspace_shipping_conversation_batch_workspace(conversation_id: str): """返回一个 Agent 会话下的多批次执行工作台快照。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 65d966c9..b5be6ef6 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -148,6 +148,9 @@ class Config: SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int( os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180' ) + SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS = int( + os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS') or '300' + ) SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower() SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2')) SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( @@ -155,6 +158,9 @@ class Config: ) SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true') SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true' + SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = ( + os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'false').lower() == 'true' + ) SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = ( os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true' ) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index cbf17dc3..9e0c065f 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -28,6 +28,15 @@ from app.models.shipping import ( ShippingTaskEvent, ShippingTaskInventoryLink, ) +from app.models.shipping_customer import ( + ShippingBusinessSequence, + ShippingCase, + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, +) +from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow +from app.models.shipping_customer_resolution import ShippingCustomerShadowResolution from app.models.training import TrainingRecord from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit @@ -66,6 +75,14 @@ __all__ = [ 'ScheduleRun', 'ShippingBatch', 'ShippingTask', + 'ShippingCustomer', + 'ShippingCustomerIdentifier', + 'ShippingCustomerExternalRef', + 'ShippingCustomerImportBatch', + 'ShippingCustomerImportRow', + 'ShippingCase', + 'ShippingBusinessSequence', + 'ShippingCustomerShadowResolution', 'ShippingTaskEvent', 'ShippingInventoryFile', 'ShippingTaskInventoryLink', diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 9bf7b8a8..99f8f62e 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -98,6 +98,11 @@ class ShippingTask(Base): id: Mapped[int] = mapped_column(primary_key=True) task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) + shipping_case_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_cases.id'), + index=True, + nullable=True, + ) batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True) user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) @@ -142,13 +147,18 @@ class ShippingTask(Base): raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True) customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + customer_resolution_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) + customer_resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + customer_identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + customer_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + customer_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True) destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - inventory_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) @@ -197,6 +207,11 @@ class ShippingTask(Base): back_populates='tasks', foreign_keys=[batch_id], ) + shipping_case: Mapped[Optional['ShippingCase']] = relationship( + 'ShippingCase', + back_populates='tasks', + lazy='joined', + ) events: Mapped[List['ShippingTaskEvent']] = relationship( 'ShippingTaskEvent', back_populates='task', diff --git a/backend/app/models/shipping_customer.py b/backend/app/models/shipping_customer.py new file mode 100644 index 00000000..af2be75a --- /dev/null +++ b/backend/app/models/shipping_customer.py @@ -0,0 +1,176 @@ +""" +backend/app/models/shipping_customer.py + +用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。 +依赖:models.base.Base、users、shipping_tasks。 +逻辑:客户主数据提供稳定身份;ShippingCase 聚合任务修订链;流水表供后续编号服务原子递增。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from typing import List, Optional + +from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingCustomer(Base): + """货代标准客户主数据;简码由管理员维护并用于业务编号前缀。""" + + __tablename__ = 'shipping_customers' + __table_args__ = ( + CheckConstraint( + "length(short_code) BETWEEN 2 AND 6 " + "AND short_code = upper(short_code) " + "AND short_code NOT GLOB '*[^A-Z]*'", + name='ck_shipping_customers_short_code_shape', + ).ddl_if(dialect='sqlite'), + CheckConstraint( + "short_code ~ '^[A-Z]{2,6}$'", + name='ck_shipping_customers_short_code_shape', + ).ddl_if(dialect='postgresql'), + Index('ix_shipping_customers_status_name', 'status', 'standard_name'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True) + short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active') + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + 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) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + identifiers: Mapped[List['ShippingCustomerIdentifier']] = relationship( + 'ShippingCustomerIdentifier', + back_populates='customer', + cascade='all, delete-orphan', + ) + cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer') + + +class ShippingCustomerIdentifier(Base): + """标准客户的可审核识别证据;同一别名可属于多个客户以表达歧义。""" + + __tablename__ = 'shipping_customer_identifiers' + __table_args__ = ( + UniqueConstraint( + 'customer_id', + 'identifier_type', + 'normalized_value', + name='uq_shipping_customer_identifiers_customer_type_value', + ), + Index( + 'ix_shipping_customer_identifiers_lookup', + 'identifier_type', + 'normalized_value', + 'status', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True) + identifier_type: Mapped[str] = mapped_column(String(32), nullable=False) + raw_value: Mapped[str] = mapped_column(String(500), nullable=False) + normalized_value: Mapped[str] = mapped_column(String(500), nullable=False) + auto_match_allowed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false')) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') + source: Mapped[str] = mapped_column(String(32), nullable=False, default='manual', server_default='manual') + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + confirmed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='identifiers') + + +class ShippingCustomerExternalRef(Base): + """客户在期初文件或外部系统中的稳定来源键,用于重复导入幂等。""" + + __tablename__ = 'shipping_customer_external_refs' + __table_args__ = ( + UniqueConstraint( + 'source_system', + 'legacy_customer_key', + name='uq_shipping_customer_external_refs_source_key', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True) + source_system: Mapped[str] = mapped_column(String(64), nullable=False) + legacy_customer_key: Mapped[str] = mapped_column(String(128), nullable=False) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer') + + +class ShippingCase(Base): + """一票发货业务聚合;多个线性任务修订版本共享同一业务单。""" + + __tablename__ = 'shipping_cases' + __table_args__ = ( + Index('ix_shipping_cases_customer_created', 'customer_id', 'created_at'), + Index('ix_shipping_cases_status_created', 'status', 'created_at'), + UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + case_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) + customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True) + business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True) + customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) + business_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + numbering_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') + status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open') + replaces_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_cases.id'), nullable=True) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases') + tasks: Mapped[List['ShippingTask']] = relationship( + 'ShippingTask', + back_populates='shipping_case', + lazy='selectin', + ) + + +class ShippingBusinessSequence(Base): + """按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。""" + + __tablename__ = 'shipping_business_sequences' + __table_args__ = ( + CheckConstraint( + 'current_value BETWEEN 0 AND 99', + name='ck_shipping_business_sequences_current_value', + ), + UniqueConstraint( + 'business_type', + 'customer_id', + 'business_date', + name='uq_shipping_business_sequences_type_customer_date', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + business_type: Mapped[str] = mapped_column( + String(32), + nullable=False, + default='shipping_notice', + server_default='shipping_notice', + ) + customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True) + business_date: Mapped[date] = mapped_column(Date, nullable=False, index=True) + current_value: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) diff --git a/backend/app/models/shipping_customer_import.py b/backend/app/models/shipping_customer_import.py new file mode 100644 index 00000000..eadbd69a --- /dev/null +++ b/backend/app/models/shipping_customer_import.py @@ -0,0 +1,86 @@ +""" +backend/app/models/shipping_customer_import.py + +用途:保存货代期初客户导入批次、原始文件与逐行预检/发布结果。 +依赖:models.base.Base、users、shipping_customers。 +逻辑:上传仅写暂存批次与行;管理员解决冲突后由发布服务单事务写入正式客户主数据。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy import ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingCustomerImportBatch(Base): + """期初客户导入批次,保存文件哈希、原始内容、统计和发布审计。""" + + __tablename__ = 'shipping_customer_import_batches' + __table_args__ = ( + UniqueConstraint('file_hash', 'source_system', name='uq_shipping_customer_import_batches_hash_source'), + Index('ix_shipping_customer_import_batches_status_created', 'status', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + batch_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) + file_name: Mapped[str] = mapped_column(String(255), nullable=False) + file_hash: Mapped[str] = mapped_column(String(64), nullable=False) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + source_system: Mapped[str] = mapped_column(String(64), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='validated', server_default='validated') + total_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + valid_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + warning_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + error_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + published_rows: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0') + uploaded_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) + published_at: Mapped[Optional[datetime]] = mapped_column(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) + + rows: Mapped[List['ShippingCustomerImportRow']] = relationship( + 'ShippingCustomerImportRow', + back_populates='batch', + cascade='all, delete-orphan', + order_by='ShippingCustomerImportRow.row_order', + ) + + +class ShippingCustomerImportRow(Base): + """导入文件逐行暂存、校验、人工决定与正式发布结果。""" + + __tablename__ = 'shipping_customer_import_rows' + __table_args__ = ( + UniqueConstraint('batch_id', 'sheet_name', 'row_no', name='uq_shipping_customer_import_rows_location'), + Index('ix_shipping_customer_import_rows_batch_status', 'batch_id', 'validation_status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + batch_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_import_batches.id'), nullable=False, index=True) + sheet_name: Mapped[str] = mapped_column(String(32), nullable=False) + row_no: Mapped[int] = mapped_column(Integer, nullable=False) + row_order: Mapped[int] = mapped_column(Integer, nullable=False) + row_type: Mapped[str] = mapped_column(String(32), nullable=False) + legacy_customer_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + raw_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + normalized_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + validation_status: Mapped[str] = mapped_column(String(32), nullable=False, default='valid') + errors_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + warnings_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + suggested_action: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + decision_action: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + target_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + decision_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + result_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + result_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + batch: Mapped['ShippingCustomerImportBatch'] = relationship('ShippingCustomerImportBatch', back_populates='rows') diff --git a/backend/app/models/shipping_customer_resolution.py b/backend/app/models/shipping_customer_resolution.py new file mode 100644 index 00000000..c39953c8 --- /dev/null +++ b/backend/app/models/shipping_customer_resolution.py @@ -0,0 +1,54 @@ +""" +backend/app/models/shipping_customer_resolution.py + +用途:保存订单候选的客户影子识别结果与人工标签。 +依赖:ShippingNoticeCandidate、ShippingNoticeIntake、ShippingCustomer、User。 +逻辑:订单候选抽取后幂等刷新本表;阶段 3 仅用于质量观测,禁止据此绑定业务单或生成编号。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, JSON, String +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class ShippingCustomerShadowResolution(Base): + """每个订单候选唯一一条影子识别快照,可追加管理员真值标签。""" + + __tablename__ = 'shipping_customer_shadow_resolutions' + __table_args__ = ( + CheckConstraint( + "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')", + name='ck_shipping_customer_shadow_status', + ), + Index('ix_shipping_customer_shadow_status_created', 'status', 'created_at'), + Index('ix_shipping_customer_shadow_labeled_created', 'manual_customer_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + candidate_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_candidates.id', ondelete='CASCADE'), + nullable=False, + unique=True, + ) + intake_id: Mapped[int] = mapped_column( + ForeignKey('shipping_notice_intakes.id', ondelete='CASCADE'), + nullable=False, + index=True, + ) + resolution_version: Mapped[str] = mapped_column(String(32), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, index=True) + evidence_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + candidate_matches_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + top_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + top_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True) + manual_customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + labeled_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + labeled_at: Mapped[Optional[datetime]] = mapped_column(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) diff --git a/backend/app/services/admin/__init__.py b/backend/app/services/admin/__init__.py index 8d07c3d7..88f85486 100644 --- a/backend/app/services/admin/__init__.py +++ b/backend/app/services/admin/__init__.py @@ -14,6 +14,8 @@ from . import ( guide_service, permission_service, report_service, + shipping_customer_import_service, + shipping_customer_service, user_service, wecom_admin_service, ) @@ -28,6 +30,8 @@ __all__ = [ 'guide_service', 'permission_service', 'report_service', + 'shipping_customer_import_service', + 'shipping_customer_service', 'user_service', 'wecom_admin_service', ] diff --git a/backend/app/services/admin/shipping_customer_import_service.py b/backend/app/services/admin/shipping_customer_import_service.py new file mode 100644 index 00000000..b9578a29 --- /dev/null +++ b/backend/app/services/admin/shipping_customer_import_service.py @@ -0,0 +1,706 @@ +""" +services/admin/shipping_customer_import_service.py + +用途:货代期初客户 Excel 模板、上传预检、行级决策、单事务发布与对账。 +依赖:openpyxl、客户/导入模型、shipping_customer_service、customer_normalization。 +逻辑:上传仅落暂存;发布前阻断错误与未决警告,正式客户及识别证据在一个事务内写入。 +""" + +from __future__ import annotations + +import csv +import hashlib +import io +import uuid +from datetime import date, datetime, time +from typing import Any + +from openpyxl import Workbook, load_workbook +from sqlalchemy.exc import IntegrityError + +from app import db +from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerImportBatch, + ShippingCustomerImportRow, +) +from app.services.admin.shipping_customer_service import serialize_customer +from app.services.shipping_notice.customer_normalization import ( + clean_text, + is_public_email_domain, + normalize_customer_name, + normalize_identifier, + normalize_short_code, +) + +MAX_IMPORT_BYTES = 5 * 1024 * 1024 +MAX_IMPORT_ROWS = 10_000 +CUSTOMER_HEADERS = ('legacy_customer_key', 'standard_name', 'short_code', 'status', 'source_system', 'remark') +IDENTIFIER_HEADERS = ( + 'legacy_customer_key', + 'source_system', + 'identifier_type', + 'identifier_value', + 'auto_match_allowed', + 'remark', +) +ROW_DECISIONS = frozenset({'create', 'update', 'merge', 'skip'}) + + +def generate_import_batch_no() -> str: + """生成客户导入批次号。""" + return f"SCI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def build_import_template() -> bytes: + """生成包含 customers/identifiers 两个 Sheet 的标准期初导入模板。""" + wb = Workbook() + customers = wb.active + customers.title = 'customers' + customers.append(CUSTOMER_HEADERS) + customers.append(('INIT-000001', '无锡宇辰有限公司', 'WYC', 'active', 'INITIAL_EXCEL', '示例行,可删除')) + identifiers = wb.create_sheet('identifiers') + identifiers.append(IDENTIFIER_HEADERS) + identifiers.append(('INIT-000001', 'INITIAL_EXCEL', 'name_alias', 'WUXI YUCHEN', False, '历史英文名称')) + output = io.BytesIO() + wb.save(output) + return output.getvalue() + + +def _cell_bool(value: Any) -> bool: + """将 Excel 常见真假写法转换为 bool。""" + if isinstance(value, bool): + return value + return clean_text(value).lower() in {'1', 'true', 'yes', 'y', '是'} + + +def _json_safe_cell(value: Any) -> Any: + """将 Excel 单元格转换为 JSON 可持久化值,日期时间使用 ISO 8601。""" + if value is None or isinstance(value, (str, int, float, bool)): + return value + if isinstance(value, (datetime, date, time)): + return value.isoformat() + return str(value) + + +def _sheet_rows(workbook, sheet_name: str, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]: + """校验 Sheet 表头并返回非空数据行。""" + if sheet_name not in workbook.sheetnames: + raise ValidationError( + f'Missing sheet: {sheet_name}', + code='SHIPPING.CUSTOMER_IMPORT_SHEET_MISSING', + details={'sheet': sheet_name}, + ) + sheet = workbook[sheet_name] + actual = tuple(clean_text(cell.value) for cell in sheet[1]) + missing = [header for header in headers if header not in actual] + if missing: + raise ValidationError( + 'Customer import columns missing', + code='SHIPPING.CUSTOMER_IMPORT_COLUMNS_MISSING', + details={'sheet': sheet_name, 'missing': missing}, + ) + positions = {header: actual.index(header) for header in headers} + result: list[tuple[int, dict[str, Any]]] = [] + for row_no, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2): + if not any(value not in (None, '') for value in values): + continue + result.append((row_no, {header: values[index] if index < len(values) else None for header, index in positions.items()})) + if len(result) > MAX_IMPORT_ROWS: + raise ValidationError( + 'Customer import contains too many rows', + code='SHIPPING.CUSTOMER_IMPORT_TOO_MANY_ROWS', + details={'sheet': sheet_name, 'max_rows': MAX_IMPORT_ROWS}, + ) + return result + + +def _existing_customer_by_ref(source_system: str, legacy_key: str) -> ShippingCustomer | None: + """按外部来源稳定键查找已导入客户。""" + ref = db.session.query(ShippingCustomerExternalRef).filter_by( + source_system=source_system, + legacy_customer_key=legacy_key, + ).first() + return db.session.get(ShippingCustomer, ref.customer_id) if ref else None + + +def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]: + """预检单条 customers 行,返回标准化字段、错误、警告和建议动作。""" + errors: list[dict[str, Any]] = [] + warnings: list[dict[str, Any]] = [] + legacy_key = clean_text(raw.get('legacy_customer_key')) + name = clean_text(raw.get('standard_name')) + source_system = clean_text(raw.get('source_system') or default_source_system).upper() + status = clean_text(raw.get('status') or 'active').lower() + short_code = '' + if not legacy_key: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'}) + elif len(legacy_key) > 128: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'}) + if not name: + errors.append({'code': 'SHIPPING.CUSTOMER_NAME_REQUIRED', 'field': 'standard_name'}) + elif len(name) > 200: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_TOO_LONG', 'field': 'standard_name'}) + if not source_system or len(source_system) > 64: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'}) + try: + short_code = normalize_short_code(raw.get('short_code')) + except ValidationError as exc: + errors.append({'code': exc.code, 'field': 'short_code'}) + if status not in {'active', 'inactive'}: + errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'}) + existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None + code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None + if code_owner and (not existing_ref or code_owner.id != existing_ref.id): + warnings.append({ + 'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT', + 'customer_id': code_owner.id, + 'short_code': short_code, + }) + normalized_name = normalize_customer_name(name) + similar = [ + item for item in db.session.query(ShippingCustomer).all() + if normalize_customer_name(item.standard_name) == normalized_name and (not existing_ref or item.id != existing_ref.id) + ] if normalized_name else [] + if similar: + warnings.append({ + 'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_MATCH', + 'candidate_customer_ids': [item.id for item in similar], + }) + suggested_action = 'update' if existing_ref else 'create' + target_customer_id = existing_ref.id if existing_ref else None + validation_status = 'error' if errors else 'warning' if warnings else 'valid' + return { + 'legacy_customer_key': legacy_key or None, + 'normalized': { + 'legacy_customer_key': legacy_key, + 'standard_name': name, + 'short_code': short_code, + 'status': status, + 'source_system': source_system, + 'remark': clean_text(raw.get('remark')), + }, + 'errors': errors, + 'warnings': warnings, + 'validation_status': validation_status, + 'suggested_action': suggested_action, + 'target_customer_id': target_customer_id, + } + + +def _identifier_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]: + """预检单条 identifiers 行,补齐来源系统并将公共邮箱证据降级为人工匹配。""" + errors: list[dict[str, Any]] = [] + warnings: list[dict[str, Any]] = [] + legacy_key = clean_text(raw.get('legacy_customer_key')) + source_system = clean_text(raw.get('source_system') or default_source_system).upper() + kind = clean_text(raw.get('identifier_type')).lower() + value = clean_text(raw.get('identifier_value')) + auto_allowed = _cell_bool(raw.get('auto_match_allowed')) + normalized = '' + if not legacy_key: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'}) + elif len(legacy_key) > 128: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'}) + if not source_system or len(source_system) > 64: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'}) + try: + normalized = normalize_identifier(kind, value) + except ValidationError as exc: + errors.append({'code': exc.code, 'field': 'identifier_value'}) + if kind in {'domain', 'email'} and normalized and is_public_email_domain(normalized): + if auto_allowed: + warnings.append({'code': 'SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN'}) + auto_allowed = False + validation_status = 'error' if errors else 'warning' if warnings else 'valid' + return { + 'legacy_customer_key': legacy_key or None, + 'normalized': { + 'legacy_customer_key': legacy_key, + 'source_system': source_system, + 'identifier_type': kind, + 'identifier_value': value, + 'normalized_value': normalized, + 'auto_match_allowed': auto_allowed, + 'remark': clean_text(raw.get('remark')), + }, + 'errors': errors, + 'warnings': warnings, + 'validation_status': validation_status, + 'suggested_action': 'create', + 'target_customer_id': None, + } + + +def serialize_import_row(row: ShippingCustomerImportRow) -> dict[str, Any]: + """序列化导入暂存行。""" + return { + 'id': row.id, + 'sheet_name': row.sheet_name, + 'row_no': row.row_no, + 'row_type': row.row_type, + 'legacy_customer_key': row.legacy_customer_key, + 'raw': row.raw_json or {}, + 'normalized': row.normalized_json or {}, + 'validation_status': row.validation_status, + 'errors': row.errors_json or [], + 'warnings': row.warnings_json or [], + 'suggested_action': row.suggested_action, + 'decision_action': row.decision_action, + 'target_customer_id': row.target_customer_id, + 'decision_note': row.decision_note, + 'result_customer_id': row.result_customer_id, + 'result_status': row.result_status, + 'result_message': row.result_message, + } + + +def serialize_import_batch(batch: ShippingCustomerImportBatch, *, include_rows: bool = True) -> dict[str, Any]: + """序列化导入批次及统计。""" + payload: dict[str, Any] = { + 'id': batch.id, + 'batch_no': batch.batch_no, + 'file_name': batch.file_name, + 'file_hash': batch.file_hash, + 'file_size': batch.file_size, + 'source_system': batch.source_system, + 'status': batch.status, + 'total_rows': batch.total_rows, + 'valid_rows': batch.valid_rows, + 'warning_rows': batch.warning_rows, + 'error_rows': batch.error_rows, + 'published_rows': batch.published_rows, + 'uploaded_by_id': batch.uploaded_by_id, + 'published_by_id': batch.published_by_id, + 'published_at': batch.published_at.isoformat() if batch.published_at else None, + 'created_at': batch.created_at.isoformat() if batch.created_at else None, + } + if include_rows: + payload['rows'] = [serialize_import_row(row) for row in batch.rows] + return payload + + +def create_import_batch(upload: Any, *, source_system: str, actor_id: int | None) -> dict[str, Any]: + """ + 上传并预检客户期初 Excel。 + + Args: + upload: Flask FileStorage,仅支持 .xlsx,最大 5 MB。 + source_system: 默认来源系统;行内可覆盖。 + actor_id: 上传管理员 ID。 + Returns: + 导入批次详情;同文件哈希重复上传返回原批次并标记 idempotent_replay。 + """ + filename = clean_text(getattr(upload, 'filename', '')) + if not filename.lower().endswith('.xlsx'): + raise ValidationError('Only .xlsx customer import files are supported', code='SHIPPING.CUSTOMER_IMPORT_FILE_TYPE_INVALID') + content = upload.read() if hasattr(upload, 'read') else b'' + if not content: + raise ValidationError('Customer import file is empty', code='SHIPPING.CUSTOMER_IMPORT_FILE_EMPTY') + if len(content) > MAX_IMPORT_BYTES: + raise ValidationError( + 'Customer import file is too large', + code='SHIPPING.CUSTOMER_IMPORT_FILE_TOO_LARGE', + details={'max_bytes': MAX_IMPORT_BYTES}, + ) + normalized_source = clean_text(source_system).upper() or 'INITIAL_EXCEL' + if len(normalized_source) > 64: + raise ValidationError( + 'Customer import source system is too long', + code='SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', + details={'field': 'source_system', 'max_length': 64}, + ) + file_hash = hashlib.sha256(content).hexdigest() + existing = db.session.query(ShippingCustomerImportBatch).filter_by( + file_hash=file_hash, + source_system=normalized_source, + ).first() + if existing: + result = serialize_import_batch(existing) + result['idempotent_replay'] = True + return result + try: + workbook = load_workbook(io.BytesIO(content), data_only=True, read_only=True) + except Exception as exc: + raise ValidationError( + 'Invalid customer import Excel file', + code='SHIPPING.CUSTOMER_IMPORT_FILE_INVALID', + details={'error_type': type(exc).__name__}, + ) from exc + try: + customer_rows = _sheet_rows(workbook, 'customers', CUSTOMER_HEADERS) + identifier_rows = _sheet_rows(workbook, 'identifiers', IDENTIFIER_HEADERS) + finally: + workbook.close() + batch = ShippingCustomerImportBatch( + batch_no=generate_import_batch_no(), + file_name=filename, + file_hash=file_hash, + file_size=len(content), + source_system=normalized_source, + uploaded_by_id=actor_id, + status='validated', + ) + db.session.add(batch) + staged: list[ShippingCustomerImportRow] = [] + try: + db.session.flush() + seen_keys: set[tuple[str, str]] = set() + order = 0 + for sheet_name, row_type, rows, validator in ( + ( + 'customers', + 'customer', + customer_rows, + lambda raw: _customer_row_validation(raw, default_source_system=normalized_source), + ), + ( + 'identifiers', + 'identifier', + identifier_rows, + lambda raw: _identifier_row_validation(raw, default_source_system=normalized_source), + ), + ): + for row_no, raw in rows: + order += 1 + result = validator(raw) + errors = list(result['errors']) + normalized = result['normalized'] + if row_type == 'customer': + key = (normalized.get('source_system') or '', normalized.get('legacy_customer_key') or '') + if key in seen_keys: + errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_DUPLICATE_KEY'}) + result['validation_status'] = 'error' + seen_keys.add(key) + staged.append(ShippingCustomerImportRow( + batch_id=batch.id, + sheet_name=sheet_name, + row_no=row_no, + row_order=order, + row_type=row_type, + legacy_customer_key=result['legacy_customer_key'], + raw_json={key: _json_safe_cell(value) for key, value in raw.items()}, + normalized_json=normalized, + validation_status=result['validation_status'], + errors_json=errors, + warnings_json=result['warnings'], + suggested_action=result['suggested_action'], + target_customer_id=result['target_customer_id'], + )) + + customer_sources_by_key: dict[str, set[str]] = {} + for row in staged: + if row.row_type != 'customer' or not row.legacy_customer_key or row.validation_status == 'error': + continue + customer_sources_by_key.setdefault(row.legacy_customer_key, set()).add( + clean_text((row.normalized_json or {}).get('source_system')).upper() + ) + for row in staged: + if row.row_type != 'identifier' or not row.legacy_customer_key: + continue + raw_source = clean_text((row.raw_json or {}).get('source_system')).upper() + candidate_sources = customer_sources_by_key.get(row.legacy_customer_key) or set() + if not raw_source and len(candidate_sources) == 1: + row.normalized_json = { + **(row.normalized_json or {}), + 'source_system': next(iter(candidate_sources)), + } + + customer_keys = { + ( + clean_text((row.normalized_json or {}).get('source_system')).upper(), + row.legacy_customer_key, + ) + for row in staged + if row.row_type == 'customer' and row.legacy_customer_key and row.validation_status != 'error' + } + for row in staged: + if row.row_type != 'identifier' or not row.legacy_customer_key: + continue + source_system = clean_text((row.normalized_json or {}).get('source_system')).upper() + if (source_system, row.legacy_customer_key) not in customer_keys: + existing_ref = db.session.query(ShippingCustomerExternalRef.id).filter_by( + source_system=source_system, + legacy_customer_key=row.legacy_customer_key, + ).first() + if not existing_ref: + row.errors_json = [ + *(row.errors_json or []), + {'code': 'SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING'}, + ] + row.validation_status = 'error' + + db.session.add_all(staged) + batch.total_rows = len(staged) + batch.valid_rows = sum(row.validation_status == 'valid' for row in staged) + batch.warning_rows = sum(row.validation_status == 'warning' for row in staged) + batch.error_rows = sum(row.validation_status == 'error' for row in staged) + db.session.commit() + except ValidationError: + db.session.rollback() + raise + except IntegrityError as exc: + db.session.rollback() + existing = db.session.query(ShippingCustomerImportBatch).filter_by( + file_hash=file_hash, + source_system=normalized_source, + ).first() + if existing is not None: + result = serialize_import_batch(existing) + result['idempotent_replay'] = True + return result + raise ConflictError( + 'Customer import upload conflict', + code='SHIPPING.CUSTOMER_IMPORT_UPLOAD_CONFLICT', + ) from exc + except Exception: + db.session.rollback() + raise + return serialize_import_batch(batch) + + +def get_import_batch(batch_id: int) -> dict[str, Any]: + """读取导入批次详情。""" + batch = db.session.get(ShippingCustomerImportBatch, batch_id) + if batch is None: + raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND') + return serialize_import_batch(batch) + + +def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]: + """保存警告行的新增、更新/合并或跳过决定。""" + row = db.session.get(ShippingCustomerImportRow, row_id) + if row is None: + raise NotFoundError('Customer import row not found', code='SHIPPING.CUSTOMER_IMPORT_ROW_NOT_FOUND') + if row.batch.status == 'published': + raise ConflictError('Published import rows cannot be changed', code='SHIPPING.CUSTOMER_IMPORT_ALREADY_PUBLISHED') + if row.validation_status == 'error': + raise ValidationError( + 'Rows with validation errors cannot be decided', + code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS', + details={'row_id': row.id}, + ) + action = clean_text(data.get('action')).lower() + if action not in ROW_DECISIONS: + raise ValidationError('Invalid import row decision', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID') + target_id = data.get('target_customer_id') + if row.row_type == 'identifier' and action not in {'create', 'skip'}: + raise ValidationError( + 'Identifier warning rows only support create or skip', + code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID', + ) + if row.row_type == 'customer' and action in {'update', 'merge'}: + try: + target_id = int(target_id) + except (TypeError, ValueError) as exc: + raise ValidationError('Target customer is required', code='SHIPPING.CUSTOMER_IMPORT_TARGET_REQUIRED') from exc + if db.session.get(ShippingCustomer, target_id) is None: + raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + else: + target_id = None + row.decision_action = action + row.target_customer_id = target_id + row.decision_note = clean_text(data.get('note')) or None + db.session.commit() + return serialize_import_row(row) + + +def _effective_action(row: ShippingCustomerImportRow) -> str: + """返回发布时实际动作;警告行必须显式决策。""" + if row.validation_status == 'error': + return '' + if row.validation_status == 'warning': + return clean_text(row.decision_action).lower() + return clean_text(row.decision_action or row.suggested_action).lower() + + +def _upsert_external_ref(customer_id: int, *, source_system: str, legacy_key: str) -> None: + """创建或校验客户外部来源键;禁止同一来源键静默改绑。""" + existing = db.session.query(ShippingCustomerExternalRef).filter_by( + source_system=source_system, + legacy_customer_key=legacy_key, + ).first() + if existing: + if existing.customer_id != customer_id: + raise ConflictError( + 'Customer external reference is already bound', + code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT', + ) + return + db.session.add(ShippingCustomerExternalRef( + customer_id=customer_id, + source_system=source_system, + legacy_customer_key=legacy_key, + )) + + +def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]: + """ + 单事务发布已预检的客户导入批次。 + + Raises: + ValidationError: 存在错误行或未决警告。 + ConflictError: 批次已发布或发布时唯一约束冲突。 + """ + batch = ( + db.session.query(ShippingCustomerImportBatch) + .filter(ShippingCustomerImportBatch.id == batch_id) + .with_for_update() + .one_or_none() + ) + if batch is None: + raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND') + if batch.status == 'published': + result = serialize_import_batch(batch) + result['idempotent_replay'] = True + return result + if any(row.validation_status == 'error' for row in batch.rows): + raise ValidationError( + 'Customer import contains blocking errors', + code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS', + details={'error_rows': batch.error_rows}, + ) + unresolved = [row.id for row in batch.rows if row.validation_status == 'warning' and not row.decision_action] + if unresolved: + raise ValidationError( + 'Customer import warnings require decisions', + code='SHIPPING.CUSTOMER_IMPORT_DECISIONS_REQUIRED', + details={'row_ids': unresolved}, + ) + customer_by_key: dict[tuple[str, str], ShippingCustomer] = {} + published = 0 + try: + # [STEP 1] 先发布客户行并建立外部来源键,供 identifiers Sheet 稳定关联。 + for row in [item for item in batch.rows if item.row_type == 'customer']: + action = _effective_action(row) + if action == 'skip': + row.result_status = 'skipped' + row.result_message = 'Skipped by administrator' + continue + data = row.normalized_json or {} + target: ShippingCustomer | None = None + if action in {'update', 'merge'}: + target = db.session.get(ShippingCustomer, row.target_customer_id) + if target is None: + raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if action == 'update': + target.standard_name = data['standard_name'] + target.short_code = data['short_code'] + target.status = data['status'] + target.remark = data.get('remark') or None + target.updated_by_id = actor_id + elif action == 'create': + target = ShippingCustomer( + standard_name=data['standard_name'], + short_code=data['short_code'], + status=data['status'], + remark=data.get('remark') or None, + created_by_id=actor_id, + updated_by_id=actor_id, + ) + db.session.add(target) + db.session.flush() + else: + raise ValidationError('Invalid import action', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID') + _upsert_external_ref( + target.id, + source_system=data['source_system'], + legacy_key=data['legacy_customer_key'], + ) + customer_by_key[(data['source_system'], data['legacy_customer_key'])] = target + row.result_customer_id = target.id + row.result_status = 'published' + row.result_message = action + published += 1 + + # [STEP 2] 标识行只绑定已发布/既有客户;导入标识默认 approved,保留 source=imported。 + for row in [item for item in batch.rows if item.row_type == 'identifier']: + action = _effective_action(row) + if action == 'skip': + row.result_status = 'skipped' + row.result_message = 'Skipped by administrator' + continue + data = row.normalized_json or {} + source_system = data.get('source_system') or batch.source_system + customer = customer_by_key.get((source_system, data.get('legacy_customer_key'))) + if customer is None: + ref = db.session.query(ShippingCustomerExternalRef).filter_by( + source_system=source_system, + legacy_customer_key=data.get('legacy_customer_key'), + ).first() + customer = db.session.get(ShippingCustomer, ref.customer_id) if ref else None + if customer is None: + raise ConflictError( + 'Identifier customer mapping is missing', + code='SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING', + ) + existing_identifier = db.session.query(ShippingCustomerIdentifier).filter_by( + customer_id=customer.id, + identifier_type=data['identifier_type'], + normalized_value=data['normalized_value'], + ).first() + if existing_identifier is None: + db.session.add(ShippingCustomerIdentifier( + customer_id=customer.id, + identifier_type=data['identifier_type'], + raw_value=data['identifier_value'], + normalized_value=data['normalized_value'], + auto_match_allowed=bool(data.get('auto_match_allowed')), + status='approved', + source='imported', + remark=data.get('remark') or None, + confirmed_by_id=actor_id, + confirmed_at=datetime.utcnow(), + )) + row.result_customer_id = customer.id + row.result_status = 'published' + row.result_message = 'identifier_created' if existing_identifier is None else 'identifier_exists' + published += 1 + batch.status = 'published' + batch.published_rows = published + batch.published_by_id = actor_id + batch.published_at = datetime.utcnow() + db.session.commit() + except AppError: + db.session.rollback() + raise + except (IntegrityError, ValueError) as exc: + db.session.rollback() + raise ConflictError( + 'Customer import publish conflict', + code='SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT', + ) from exc + except Exception: + db.session.rollback() + raise + return serialize_import_batch(batch) + + +def build_reconciliation_csv(batch_id: int) -> tuple[bytes, str]: + """从持久化导入行生成可重复下载的 UTF-8 BOM 对账 CSV。""" + batch = db.session.get(ShippingCustomerImportBatch, batch_id) + if batch is None: + raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND') + output = io.StringIO(newline='') + writer = csv.writer(output) + writer.writerow([ + 'sheet_name', 'row_no', 'legacy_customer_key', 'validation_status', 'decision_action', + 'result_status', 'result_customer_id', 'result_message', 'errors', 'warnings', + ]) + for row in batch.rows: + writer.writerow([ + row.sheet_name, + row.row_no, + row.legacy_customer_key or '', + row.validation_status, + row.decision_action or row.suggested_action or '', + row.result_status or '', + row.result_customer_id or '', + row.result_message or '', + ';'.join(str(item.get('code') or item) for item in (row.errors_json or [])), + ';'.join(str(item.get('code') or item) for item in (row.warnings_json or [])), + ]) + return ('\ufeff' + output.getvalue()).encode('utf-8'), f'{batch.batch_no}_reconciliation.csv' diff --git a/backend/app/services/admin/shipping_customer_service.py b/backend/app/services/admin/shipping_customer_service.py new file mode 100644 index 00000000..ea75743f --- /dev/null +++ b/backend/app/services/admin/shipping_customer_service.py @@ -0,0 +1,342 @@ +""" +services/admin/shipping_customer_service.py + +用途:管理货代标准客户与已审核识别证据。 +依赖:db、ShippingCustomer* 模型、customer_normalization、统一 AppError。 +逻辑:管理 API 委托本服务完成校验、唯一性检查、停用与序列化;不承载运行期客户裁决。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from sqlalchemy import asc, desc, func, or_ +from sqlalchemy.exc import IntegrityError + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier +from app.services.shipping_notice.customer_normalization import ( + clean_text, + is_public_email_domain, + normalize_identifier, + normalize_short_code, +) + +CUSTOMER_STATUSES = frozenset({'active', 'inactive'}) +IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'}) + + +def _strict_bool(value: Any, *, field: str) -> bool: + """只接受 JSON 布尔值,避免字符串 ``false`` 被 Python 判定为真。""" + if isinstance(value, bool): + return value + if value is None: + return False + raise ValidationError( + f'{field} must be a boolean', + code='VALIDATION.INVALID_PARAM', + details={'field': field}, + ) + + +def serialize_identifier(record: ShippingCustomerIdentifier) -> dict[str, Any]: + """序列化客户识别证据,供管理后台列表与详情共用。""" + return { + 'id': record.id, + 'customer_id': record.customer_id, + 'identifier_type': record.identifier_type, + 'raw_value': record.raw_value, + 'normalized_value': record.normalized_value, + 'auto_match_allowed': bool(record.auto_match_allowed), + 'status': record.status, + 'source': record.source, + 'remark': record.remark, + 'confirmed_by_id': record.confirmed_by_id, + 'confirmed_at': record.confirmed_at.isoformat() if record.confirmed_at else None, + 'created_at': record.created_at.isoformat() if record.created_at else None, + 'updated_at': record.updated_at.isoformat() if record.updated_at else None, + } + + +def serialize_customer( + record: ShippingCustomer, + *, + include_identifiers: bool = False, + case_count: int | None = None, + identifier_count: int | None = None, +) -> dict[str, Any]: + """ + 序列化标准客户,并可选附带识别证据和业务引用数量。 + + Args: + record: 标准客户 ORM 记录。 + include_identifiers: 是否附带识别证据明细。 + case_count: 列表查询预聚合的业务单数量;为空时现场查询。 + identifier_count: 列表查询预聚合的识别证据数量;为空时现场查询。 + Returns: + 管理端客户 JSON 字典。 + """ + payload: dict[str, Any] = { + 'id': record.id, + 'standard_name': record.standard_name, + 'short_code': record.short_code, + 'status': record.status, + 'remark': record.remark, + 'created_by_id': record.created_by_id, + 'updated_by_id': record.updated_by_id, + 'created_at': record.created_at.isoformat() if record.created_at else None, + 'updated_at': record.updated_at.isoformat() if record.updated_at else None, + 'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(), + 'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(), + } + if include_identifiers: + payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers] + return payload + + +def list_customers(params: dict[str, Any]) -> dict[str, Any]: + """ + 分页列出标准客户。 + + Args: + params: 支持 q/status/page/page_size/sort/order。 + Returns: + items、total、page、page_size、pages。 + """ + case_counts = ( + db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count')) + .group_by(ShippingCase.customer_id) + .subquery() + ) + identifier_counts = ( + db.session.query( + ShippingCustomerIdentifier.customer_id.label('customer_id'), + func.count(ShippingCustomerIdentifier.id).label('identifier_count'), + ) + .group_by(ShippingCustomerIdentifier.customer_id) + .subquery() + ) + query = ( + db.session.query( + ShippingCustomer, + func.coalesce(case_counts.c.case_count, 0), + func.coalesce(identifier_counts.c.identifier_count, 0), + ) + .outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id) + .outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id) + ) + keyword = clean_text(params.get('q')) + status = clean_text(params.get('status')).lower() + if keyword: + like = f'%{keyword}%' + query = query.filter(or_(ShippingCustomer.standard_name.ilike(like), ShippingCustomer.short_code.ilike(like))) + if status: + if status not in CUSTOMER_STATUSES: + raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID') + query = query.filter(ShippingCustomer.status == status) + try: + page = max(1, int(params.get('page') or 1)) + page_size = min(100, max(1, int(params.get('page_size') or 20))) + except (TypeError, ValueError) as exc: + raise ValidationError('Invalid pagination') from exc + sort_map = { + 'standard_name': ShippingCustomer.standard_name, + 'short_code': ShippingCustomer.short_code, + 'created_at': ShippingCustomer.created_at, + 'updated_at': ShippingCustomer.updated_at, + } + sort_col = sort_map.get(clean_text(params.get('sort')).lower(), ShippingCustomer.updated_at) + order = asc if clean_text(params.get('order')).lower() == 'asc' else desc + total = query.count() + items = query.order_by(order(sort_col), ShippingCustomer.id.desc()).offset((page - 1) * page_size).limit(page_size).all() + return { + 'items': [ + serialize_customer(customer, case_count=int(case_count), identifier_count=int(identifier_count)) + for customer, case_count, identifier_count in items + ], + 'total': total, + 'page': page, + 'page_size': page_size, + 'pages': max(1, (total + page_size - 1) // page_size), + } + + +def get_customer(customer_id: int) -> dict[str, Any]: + """读取客户详情;不存在时抛出统一 NotFoundError。""" + record = db.session.get(ShippingCustomer, customer_id) + if record is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + return serialize_customer(record, include_identifiers=True) + + +def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None: + """校验客户简码全局唯一。""" + query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code) + if exclude_customer_id is not None: + query = query.filter(ShippingCustomer.id != exclude_customer_id) + if query.first(): + raise ConflictError( + 'Customer short code already exists', + code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS', + details={'short_code': short_code}, + ) + + +def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 创建标准客户。 + + Args: + data: standard_name、short_code、status、remark。 + actor_id: 当前管理员 ID。 + Returns: + 新客户详情。 + """ + standard_name = clean_text(data.get('standard_name')) + if not standard_name: + raise ValidationError( + 'Customer standard name is required', + code='SHIPPING.CUSTOMER_NAME_REQUIRED', + details={'field': 'standard_name'}, + ) + short_code = normalize_short_code(data.get('short_code')) + _assert_short_code_available(short_code) + status = clean_text(data.get('status') or 'active').lower() + if status not in CUSTOMER_STATUSES: + raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID') + record = ShippingCustomer( + standard_name=standard_name, + short_code=short_code, + status=status, + remark=clean_text(data.get('remark')) or None, + created_by_id=actor_id, + updated_by_id=actor_id, + ) + db.session.add(record) + try: + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise ConflictError('Customer already exists', code='SHIPPING.CUSTOMER_CONFLICT') from exc + return serialize_customer(record, include_identifiers=True) + + +def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """更新标准客户;历史业务号使用快照,不受简码修改影响。""" + record = db.session.get(ShippingCustomer, customer_id) + if record is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if 'standard_name' in data: + name = clean_text(data.get('standard_name')) + if not name: + raise ValidationError('Customer standard name is required', code='SHIPPING.CUSTOMER_NAME_REQUIRED') + record.standard_name = name + if 'short_code' in data: + short_code = normalize_short_code(data.get('short_code')) + _assert_short_code_available(short_code, exclude_customer_id=customer_id) + record.short_code = short_code + if 'status' in data: + status = clean_text(data.get('status')).lower() + if status not in CUSTOMER_STATUSES: + raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID') + record.status = status + if 'remark' in data: + record.remark = clean_text(data.get('remark')) or None + record.updated_by_id = actor_id + try: + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise ConflictError('Customer update conflict', code='SHIPPING.CUSTOMER_CONFLICT') from exc + return serialize_customer(record, include_identifiers=True) + + +def deactivate_customer(customer_id: int, *, actor_id: int | None) -> dict[str, Any]: + """停用客户;不物理删除,以保留业务单和识别审计。""" + return update_customer(customer_id, {'status': 'inactive'}, actor_id=actor_id) + + +def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 新增客户识别证据。 + + 核心逻辑:公共邮箱域名不得开启自动匹配;approved 状态写入审核人和时间。 + """ + customer = db.session.get(ShippingCustomer, customer_id) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + identifier_type = clean_text(data.get('identifier_type')).lower() + raw_value = clean_text(data.get('raw_value') or data.get('identifier_value')) + normalized_value = normalize_identifier(identifier_type, raw_value) + status = clean_text(data.get('status') or 'pending').lower() + if status not in IDENTIFIER_STATUSES: + raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID') + auto_match_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed') + if identifier_type in {'domain', 'email'} and is_public_email_domain(normalized_value) and auto_match_allowed: + raise ValidationError( + 'Public email domains cannot be used for automatic matching', + code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN', + ) + if status != 'approved' and auto_match_allowed: + raise ValidationError( + 'Only approved identifiers can enable automatic matching', + code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED', + ) + record = ShippingCustomerIdentifier( + customer_id=customer.id, + identifier_type=identifier_type, + raw_value=raw_value, + normalized_value=normalized_value, + auto_match_allowed=auto_match_allowed, + status=status, + source=clean_text(data.get('source') or 'manual').lower(), + remark=clean_text(data.get('remark')) or None, + confirmed_by_id=actor_id if status == 'approved' else None, + confirmed_at=datetime.utcnow() if status == 'approved' else None, + ) + db.session.add(record) + try: + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise ConflictError( + 'Customer identifier already exists', + code='SHIPPING.CUSTOMER_IDENTIFIER_EXISTS', + ) from exc + return serialize_identifier(record) + + +def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """更新识别证据;先校验最终状态,再一次性修改 ORM,避免失败后残留脏状态。""" + record = db.session.get(ShippingCustomerIdentifier, identifier_id) + if record is None: + raise NotFoundError('Customer identifier not found', code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_FOUND') + next_status = record.status + if 'status' in data: + next_status = clean_text(data.get('status')).lower() + if next_status not in IDENTIFIER_STATUSES: + raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID') + next_allowed = record.auto_match_allowed if next_status == 'approved' else False + if 'auto_match_allowed' in data: + next_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed') + if record.identifier_type in {'domain', 'email'} and is_public_email_domain(record.normalized_value) and next_allowed: + raise ValidationError( + 'Public email domains cannot be used for automatic matching', + code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN', + ) + if next_status != 'approved' and next_allowed: + raise ValidationError( + 'Only approved identifiers can enable automatic matching', + code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED', + ) + record.status = next_status + record.auto_match_allowed = next_allowed + if next_status == 'approved' and record.confirmed_at is None: + record.confirmed_by_id = actor_id + record.confirmed_at = datetime.utcnow() + if 'remark' in data: + record.remark = clean_text(data.get('remark')) or None + db.session.commit() + return serialize_identifier(record) diff --git a/backend/app/services/agent_registry/handlers/base.py b/backend/app/services/agent_registry/handlers/base.py index 3e7bac8d..779c29cd 100644 --- a/backend/app/services/agent_registry/handlers/base.py +++ b/backend/app/services/agent_registry/handlers/base.py @@ -70,5 +70,5 @@ class AgentHandler: ctx: ChatStreamContext, event_data: dict[str, Any], ) -> Iterator[str]: - """上游 message_end/workflow_finished 后追加的 SSE 行。""" + """上游 error/message_end/workflow_finished 后执行领域收口并追加 SSE 行。""" return iter(()) diff --git a/backend/app/services/agent_registry/handlers/shipping_notice.py b/backend/app/services/agent_registry/handlers/shipping_notice.py index 9bbe725c..b8c8b9c8 100644 --- a/backend/app/services/agent_registry/handlers/shipping_notice.py +++ b/backend/app/services/agent_registry/handlers/shipping_notice.py @@ -1,9 +1,10 @@ """ backend/app/services/agent_registry/handlers/shipping_notice.py -用途:货代发货通知 Hybrid Handler — 聊天流 UI State 与上下文准备。 -依赖:shipping_notice.query_service、ui_state、agent_registry.handlers.registry。 -逻辑:SSE relay 调用 build_ui_state_event;不替代 Dify 正文生成。 +用途:货代发货通知 Hybrid Handler — 聊天流订单抽取生命周期、UI State 与上下文准备。 +依赖:shipping_notice.order_extraction/query_service、chat.log_service、ui_state、agent_registry.handlers.registry。 +逻辑:Dify 请求前登记并推送订单抽取状态,terminal/error 后收口、持久化结果并补发 Batch UI State; + 不替代 Dify 正文生成。 """ from __future__ import annotations @@ -38,41 +39,148 @@ class ShippingNoticeHandler(AgentHandler): """ 货代发货通知业务 Handler。 - 核心逻辑:按 adapter_hints / 请求 task_id、batch_no 构造 shipping_ui_state 事件供前端渲染步骤与按钮。 + 核心逻辑:订单抽取请求进入 Dify 前登记 request/intakes 并推送 extracting;终态时先落失败、 + 推送并持久化抽取结果,再按 adapter_hints / task_id / batch_no 构造 shipping_ui_state。 + 阶段约束:`open_existing` 终态必须能为前端提供恢复锚点;最小字段是 `task_no`,若已知批次则补 + `batch_no`,若已构造快照则补 `ui_state / batch_ui_state`,供实时消息与历史回放共用。 """ - def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None: + @staticmethod + def _shipping_hints(ctx: ChatStreamContext) -> dict[str, Any]: + """读取 shipping adapter_hints,非法或缺失时返回空字典。""" + hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {} + shipping_hints = hints.get('shipping_notice') + return shipping_hints if isinstance(shipping_hints, dict) else {} + + @classmethod + def _order_extraction_intake_nos(cls, ctx: ChatStreamContext) -> list[str]: + """仅在能力与契约均匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。""" + hints = cls._shipping_hints(ctx) + if ( + str(hints.get('capability') or '') != 'order_extraction' + or str(hints.get('contract_version') or '') != 'shipping-order-extraction-v1' + or not isinstance(hints.get('intake_nos'), list) + ): + return [] + return sorted({ + str(item or '').strip().upper() + for item in hints.get('intake_nos') or [] + if str(item or '').strip() + }) + + @staticmethod + def _workflow_failure_message(event_data: dict[str, Any]) -> str: + """从 Dify terminal/error 事件提取已友好化的错误文本,缺失时返回空字符串。""" + event_name = str(event_data.get('event') or '').strip() + data = event_data.get('data') if isinstance(event_data.get('data'), dict) else {} + failed = event_name == 'error' or ( + event_name == 'workflow_finished' + and str(data.get('status') or '').strip().lower() == 'failed' + ) + if not failed: + return '' + for value in ( + event_data.get('message'), + event_data.get('error'), + event_data.get('description'), + data.get('message'), + data.get('error'), + data.get('description'), + ): + text = str(value or '').strip() + if text: + return text + return '订单识别失败,请重新发送当前邮件。' + + def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext: + """ + 在订单抽取请求进入 Dify 前登记权威 extracting 状态。 + + 核心逻辑:仅消费平台 adapter_hints 中的固定能力契约,并把 HXOPS request_id 绑定到完整 Intake 集合; + 失败直接阻止上游调用,避免前端显示本地 extracting 而后端仍为 not_started。 + """ + intake_nos = self._order_extraction_intake_nos(ctx) + if not intake_nos: + return ctx + from app.services.shipping_notice.order_extraction import start_order_extraction + + start_order_extraction( + user_id=int(getattr(ctx.user, 'id', 0) or 0), + session_id=str(getattr(ctx.session, 'session_id', '') or ''), + intake_nos=intake_nos, + request_id=ctx.request_id, + ) + return ctx + + def build_ui_state_event( + self, + ctx: ChatStreamContext, + *, + resolve_order_extraction: bool = False, + ) -> dict[str, Any] | None: """ 构造 shipping_ui_state SSE 事件。 - 核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。 + 用途:为聊天页当前消息与历史回放提供任务/批次恢复锚点。 + 核心逻辑:优先显式 task_id,其次 batch 焦点任务;订单抽取终态可按 intake 反查新建批次或 + `open_existing` 命中的既有任务。`open_existing` 场景下即使没有新建批次,也必须至少返回 + `task_no`;失败时记录日志并返回 None。 """ if not _uses_shipping_ui_state_progress(ctx.agent): return None task_id = str(ctx.shipping_task_id or '').strip() batch_no = str(ctx.shipping_batch_no or '').strip() + shipping_hints = self._shipping_hints(ctx) if not task_id and not batch_no: - hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {} - shipping_hints = hints.get('shipping_notice') if isinstance(hints.get('shipping_notice'), dict) else {} task_id = str(shipping_hints.get('task_id') or '').strip() batch_no = str(shipping_hints.get('batch_no') or '').strip() - if not task_id and not batch_no: + intake_nos = self._order_extraction_intake_nos(ctx) + if not task_id and not batch_no and not (resolve_order_extraction and intake_nos): return None try: - from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref + from app.services.shipping_notice.query_service import ( + get_batch_by_no, + get_task_by_ref, + resolve_order_extraction_ui_target, + ) from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state task = get_task_by_ref(task_id) if task_id else None batch = get_batch_by_no(batch_no) if batch_no else None + resolved_from_order_extraction = False + if task is None and batch is None and resolve_order_extraction and intake_nos: + batch, task = resolve_order_extraction_ui_target( + user_id=int(getattr(ctx.user, 'id', 0) or 0), + conversation_id=str(getattr(ctx.session, 'session_id', '') or ''), + intake_nos=intake_nos, + ) + resolved_from_order_extraction = batch is not None or task is not None + session_id = str(getattr(ctx.session, 'session_id', '') or '') + if resolved_from_order_extraction and batch is not None: + batch_ui_state = build_batch_ui_state(batch) + focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {} + focus_ui_state = ( + batch_ui_state.get('focus_task_ui_state') + if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) + else None + ) + return { + 'event': 'shipping_ui_state', + 'conversation_id': session_id, + 'batch_no': batch.batch_no, + 'task_no': focus_task.get('task_no'), + 'batch_ui_state': batch_ui_state, + **({'ui_state': focus_ui_state} if focus_ui_state is not None else {}), + 'source': 'order_extraction', + } if task is None and batch is not None: focus_task_no = str(batch.current_focus_task_no or '').strip() if focus_task_no: candidate = get_task_by_ref(focus_task_no) if candidate is not None and candidate.batch_id == batch.id: task = candidate - session_id = str(getattr(ctx.session, 'session_id', '') or '') if task is not None: return { 'event': 'shipping_ui_state', @@ -80,13 +188,23 @@ class ShippingNoticeHandler(AgentHandler): 'task_no': task.task_no, 'batch_no': task.batch.batch_no if task.batch is not None else None, 'ui_state': build_task_ui_state(task), + **({'source': 'order_extraction'} if resolved_from_order_extraction else {}), } if batch is not None: + batch_ui_state = build_batch_ui_state(batch) + focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {} + focus_ui_state = ( + batch_ui_state.get('focus_task_ui_state') + if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) + else None + ) return { 'event': 'shipping_ui_state', 'conversation_id': session_id, 'batch_no': batch.batch_no, - 'batch_ui_state': build_batch_ui_state(batch), + 'task_no': focus_task.get('task_no'), + 'batch_ui_state': batch_ui_state, + **({'ui_state': focus_ui_state} if focus_ui_state is not None else {}), } except Exception: if current_app: @@ -98,7 +216,129 @@ class ShippingNoticeHandler(AgentHandler): ) return None + def build_order_extraction_state_event( + self, + ctx: ChatStreamContext, + ) -> dict[str, Any] | None: + """ + 构造当前请求的 shipping_order_extraction_state SSE 事件。 + + 核心逻辑:只为固定订单抽取能力契约读取权威 Intake 状态;身份围栏失败时记录日志并跳过, + 避免把旧请求或其他会话结果推送到当前消息。 + + Args: + ctx: 当前聊天流上下文,必须包含用户、会话、request_id 与 Intake 集合。 + + Returns: + 可直接格式化为 SSE 的事件字典;非订单抽取回合或读取失败时返回 None。 + """ + intake_nos = self._order_extraction_intake_nos(ctx) + if not intake_nos: + return None + try: + from app.services.shipping_notice.order_extraction import get_order_extraction_state + + state = get_order_extraction_state( + user_id=int(getattr(ctx.user, 'id', 0) or 0), + session_id=str(getattr(ctx.session, 'session_id', '') or ''), + intake_nos=intake_nos, + request_id=ctx.request_id, + ) + return { + 'event': 'shipping_order_extraction_state', + 'conversation_id': str(getattr(ctx.session, 'session_id', '') or ''), + **state, + } + except Exception: + if current_app: + current_app.logger.exception( + '[shipping-handler] build order extraction state failed request_id=%s intakes=%s', + ctx.request_id, + intake_nos, + ) + return None + + @staticmethod + def _build_history_recovery_payload_patch( + *, + state_event: dict[str, Any] | None, + ui_event: dict[str, Any] | None, + ) -> dict[str, Any]: + """ + 提取历史回放所需的最小恢复载荷。 + + 核心逻辑:抽取终态负责统计摘要,UI State 负责任务/批次锚点;两者都存在时合并为同一条 + ChatLog.payload patch,保证历史消息可直接恢复工作台。 + """ + payload_patch: dict[str, Any] = {} + if isinstance(state_event, dict) and state_event.get('terminal') is True: + payload_patch['shipping_order_extraction_state'] = { + key: value + for key, value in state_event.items() + if key not in {'event', 'conversation_id'} + } + if isinstance(ui_event, dict) and str(ui_event.get('event') or '') == 'shipping_ui_state': + task_no = str(ui_event.get('task_no') or '').strip() + if task_no: + payload_patch['task_no'] = task_no + if 'batch_no' in ui_event: + batch_no = str(ui_event.get('batch_no') or '').strip() + payload_patch['batch_no'] = batch_no or None + ui_state = ui_event.get('ui_state') + if isinstance(ui_state, dict): + payload_patch['shipping_ui_state'] = ui_state + batch_ui_state = ui_event.get('batch_ui_state') + if isinstance(batch_ui_state, dict): + payload_patch['shipping_batch_ui_state'] = batch_ui_state + return payload_patch + + def _persist_history_recovery_payload( + self, + ctx: ChatStreamContext, + event_data: dict[str, Any], + *, + state_event: dict[str, Any] | None = None, + ui_event: dict[str, Any] | None = None, + ) -> None: + """ + 把订单抽取终态与 UI 锚点合并到本轮已落库 ChatLog,供历史消息恢复。 + + 核心逻辑:使用上游终态附带的 chat_log_id 与当前身份做归属校验;缺少日志主键时保留实时 SSE, + 不创建额外聊天记录。阶段 1 要求 `open_existing` 至少补齐 `task_no`,有批次或快照时继续补齐 + `batch_no / shipping_ui_state / shipping_batch_ui_state`。 + + Args: + ctx: 当前聊天流上下文。 + event_data: Dify terminal/error 原始事件。 + state_event: 已构造的订单抽取状态事件。 + ui_event: 已构造的 shipping_ui_state 事件。 + """ + payload_patch = self._build_history_recovery_payload_patch( + state_event=state_event, + ui_event=ui_event, + ) + if not payload_patch: + return + try: + chat_log_id = int(event_data.get('chat_log_id') or 0) + except (TypeError, ValueError): + chat_log_id = 0 + if chat_log_id <= 0: + return + from app.services.chat.log_service import merge_chat_log_payload + + merge_chat_log_payload( + chat_log_id=chat_log_id, + user_id=int(getattr(ctx.user, 'id', 0) or 0), + agent_id=int(getattr(ctx.agent, 'id', 0) or 0), + session_id=str(getattr(ctx.session, 'session_id', '') or ''), + payload_patch=payload_patch, + ) + def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None: + """仅为 shipping_ui_state 构造去重键,其他领域事件保持独立生命周期。""" + if str(event.get('event') or '') != 'shipping_ui_state': + return None ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {} batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {} focus_state = ( @@ -115,9 +355,14 @@ class ShippingNoticeHandler(AgentHandler): }, ensure_ascii=False, sort_keys=True) def _format_sse(self, event: dict[str, Any]) -> str: + """把领域事件编码为单条 SSE data frame。""" return f"data: {json.dumps(event, ensure_ascii=False)}\n\n" def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]: + """上游调用前先推送订单抽取进行态,再补充已有任务 UI State。""" + extraction_event = self.build_order_extraction_state_event(ctx) + if extraction_event: + yield self._format_sse(extraction_event) event = self.build_ui_state_event(ctx) if event: yield self._format_sse(event) @@ -127,9 +372,46 @@ class ShippingNoticeHandler(AgentHandler): ctx: ChatStreamContext, event_data: dict[str, Any], ) -> Iterator[str]: + """上游终态后收口抽取状态,依次推送抽取事实和任务 UI State。""" event_name = str(event_data.get('event') or '').strip() - if event_name not in {'message_end', 'workflow_finished'}: + if event_name not in {'error', 'message_end', 'workflow_finished'}: return iter(()) - event = self.build_ui_state_event(ctx) + intake_nos = self._order_extraction_intake_nos(ctx) + if intake_nos: + from app.services.shipping_notice.order_extraction import ( + ORDER_EXTRACTION_INCOMPLETE_MESSAGE, + finalize_order_extraction_failure, + ) + + failure_message = self._workflow_failure_message(event_data) + try: + finalize_order_extraction_failure( + user_id=int(getattr(ctx.user, 'id', 0) or 0), + session_id=str(getattr(ctx.session, 'session_id', '') or ''), + intake_nos=intake_nos, + request_id=ctx.request_id, + error_message=failure_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE, + ) + except Exception: + from app import db + + db.session.rollback() + if current_app: + current_app.logger.exception( + '[shipping-handler] finalize order extraction failed request_id=%s intakes=%s', + ctx.request_id, + intake_nos, + ) + extraction_event = self.build_order_extraction_state_event(ctx) + event = self.build_ui_state_event(ctx, resolve_order_extraction=True) + if extraction_event or event: + self._persist_history_recovery_payload( + ctx, + event_data, + state_event=extraction_event, + ui_event=event, + ) + if extraction_event: + yield self._format_sse(extraction_event) if event: yield self._format_sse(event) diff --git a/backend/app/services/chat/executors/__init__.py b/backend/app/services/chat/executors/__init__.py index d6ea1ecc..83b84fd7 100644 --- a/backend/app/services/chat/executors/__init__.py +++ b/backend/app/services/chat/executors/__init__.py @@ -1,9 +1,9 @@ """ backend/app/services/chat/executors/__init__.py -用途:RUNTIME_PROVIDER_REGISTRY 与聊天 Executor 解析入口。 +用途:RUNTIME_PROVIDER_REGISTRY、聊天 Executor 解析及同步 Handler 前置准备入口。 依赖:dify_chat、hybrid、builtin executors;agent_registry.resolver。 -逻辑:chat.py completions 默认 Dify 路径调用 stream_chat_via_executor。 +逻辑:chat.py 先调用 stream_chat_via_executor 同步执行 prepare_stream,再下发 preface 并惰性迭代上游流。 """ from __future__ import annotations @@ -12,7 +12,11 @@ from typing import Iterator from app.core.errors import ValidationError from app.services.agent_registry.handlers.base import ChatStreamContext -from app.services.agent_registry.resolver import resolve_runtime_provider +from app.services.agent_registry.resolver import ( + resolve_handler, + resolve_handler_for_agent_code, + resolve_runtime_provider, +) from app.services.chat.executors.base import ChatExecutor from app.services.chat.executors.builtin import BuiltinChatExecutor from app.services.chat.executors.dify_chat import DifyChatExecutor @@ -61,10 +65,19 @@ def stream_chat_via_executor(ctx: ChatStreamContext) -> Iterator[str]: Args: ctx: ChatStreamContext。 + 核心逻辑:必须在返回惰性生成器前同步调用 Handler.prepare_stream,确保 chat.py 随后的 preface + 能读取到已登记的领域状态;Hybrid/Builtin 强制要求 Handler,Dify Chatflow 允许无 Handler。 + Returns: - 上游 SSE 行迭代器。 + 已完成 Handler 前置准备的上游 SSE 行迭代器。 """ executor = resolve_chat_executor(ctx.agent) + if executor.provider_key in {'hybrid', 'builtin'}: + handler = resolve_handler(ctx.agent) + else: + handler = resolve_handler_for_agent_code(ctx.agent) + if handler is not None: + ctx = handler.prepare_stream(ctx) return executor.stream(ctx) diff --git a/backend/app/services/chat/executors/builtin.py b/backend/app/services/chat/executors/builtin.py index 63aab279..5c95e7a7 100644 --- a/backend/app/services/chat/executors/builtin.py +++ b/backend/app/services/chat/executors/builtin.py @@ -3,7 +3,7 @@ backend/app/services/chat/executors/builtin.py 用途:runtime_provider=builtin 的聊天 Executor。 依赖:agent_registry.resolver.resolve_handler。 -逻辑:必须存在 Handler;由 Handler 驱动内置流(v1 未实现完整 builtin 流时显式报错)。 +逻辑:stream_chat_via_executor 已校验并准备 Handler;v1 未实现完整 builtin 流时显式报错。 """ from __future__ import annotations @@ -21,8 +21,8 @@ class BuiltinChatExecutor(ChatExecutor): provider_key = 'builtin' def stream(self, ctx: ChatStreamContext) -> Iterator[str]: + """返回尚未实现的明确错误,并保留 Handler key 便于诊断。""" handler = resolve_handler(ctx.agent) - ctx = handler.prepare_stream(ctx) raise AppError( code='AGENT.BUILTIN_NOT_IMPLEMENTED', message='runtime_provider=builtin 的聊天流尚未实现,请使用 hybrid 或 dify', diff --git a/backend/app/services/chat/executors/dify_chat.py b/backend/app/services/chat/executors/dify_chat.py index 253d3255..27ef9009 100644 --- a/backend/app/services/chat/executors/dify_chat.py +++ b/backend/app/services/chat/executors/dify_chat.py @@ -2,15 +2,14 @@ backend/app/services/chat/executors/dify_chat.py 用途:runtime_provider=dify 的 Chatflow 聊天 Executor。 -依赖:DifyService.stream_chat、executors.base、agent_registry.resolver。 -逻辑:Handler.prepare_stream → build_chat_dify_inputs → DifyService.stream_chat。 +依赖:DifyService.stream_chat、executors.base。 +逻辑:stream_chat_via_executor 已完成 Handler 前置准备;本文件构造 inputs 并惰性转发 Dify SSE。 """ from __future__ import annotations from typing import Iterator -from app.services.agent_registry.resolver import resolve_handler_for_agent_code from app.services.chat.executors.base import ( ChatExecutor, ChatStreamContext, @@ -25,9 +24,7 @@ class DifyChatExecutor(ChatExecutor): provider_key = 'dify' def stream(self, ctx: ChatStreamContext) -> Iterator[str]: - handler = resolve_handler_for_agent_code(ctx.agent) - if handler is not None: - ctx = handler.prepare_stream(ctx) + """使用已经完成 Handler 前置准备的上下文调用 Dify Chatflow。""" dify_inputs = build_dify_inputs_for_context(ctx) yield from DifyService.stream_chat( ctx.query, diff --git a/backend/app/services/chat/executors/hybrid.py b/backend/app/services/chat/executors/hybrid.py index a4bdbe45..cdb58db7 100644 --- a/backend/app/services/chat/executors/hybrid.py +++ b/backend/app/services/chat/executors/hybrid.py @@ -1,16 +1,15 @@ """ backend/app/services/chat/executors/hybrid.py -用途:runtime_provider=hybrid 的聊天 Executor(Handler 前置 + Dify 流)。 -依赖:resolve_handler、DifyChatExecutor。 -逻辑:resolve_handler 校验 → handler.prepare_stream → DifyChatExecutor.stream。 +用途:runtime_provider=hybrid 的聊天 Executor(强制 Handler + Dify 流)。 +依赖:DifyChatExecutor;Handler 校验与前置准备由 stream_chat_via_executor 统一完成。 +逻辑:接收已准备上下文并委托 DifyChatExecutor.stream。 """ from __future__ import annotations from typing import Iterator -from app.services.agent_registry.resolver import resolve_handler from app.services.chat.executors.base import ChatExecutor, ChatStreamContext from app.services.chat.executors.dify_chat import DifyChatExecutor @@ -24,6 +23,5 @@ class HybridChatExecutor(ChatExecutor): self._dify = DifyChatExecutor() def stream(self, ctx: ChatStreamContext) -> Iterator[str]: - handler = resolve_handler(ctx.agent) - ctx = handler.prepare_stream(ctx) + """把已完成 Handler 准备的 Hybrid 上下文委托给 Dify Chatflow。""" yield from self._dify.stream(ctx) diff --git a/backend/app/services/chat/log_service.py b/backend/app/services/chat/log_service.py index fb031c28..9b133068 100644 --- a/backend/app/services/chat/log_service.py +++ b/backend/app/services/chat/log_service.py @@ -1,9 +1,9 @@ """ backend/app/services/chat/log_service.py -用途:Chat Turn 与对话历史的 ChatLog 统一写入。 +用途:Chat Turn 与对话历史的 ChatLog 统一写入及结构化 payload 合并。 依赖:models.ChatLog、SQLAlchemy。 -逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;api/chat 历史路由可逐步迁入。 +逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;领域 Handler 可在上游终态后安全合并回放 payload。 """ from __future__ import annotations @@ -72,3 +72,61 @@ def save_turn_chat_log( current_app.logger.exception("[chat-turn] failed to save chat log: %s", exc) db.session.rollback() return None + + +def merge_chat_log_payload( + *, + chat_log_id: int, + user_id: int, + agent_id: int, + session_id: str, + payload_patch: dict[str, Any], +) -> bool: + """ + 在归属校验通过后幂等合并 ChatLog 结构化 payload。 + + 核心逻辑:锁定指定消息并同时校验用户、Agent、本地会话,随后以顶层键覆盖方式合并领域终态; + 该函数不修改正文,适合 SSE terminal 之后补写可回放的状态卡片数据。 + + Args: + chat_log_id: 已持久化的 ChatLog 主键,必须为正整数。 + user_id: 当前请求用户主键。 + agent_id: 当前请求 Agent 主键。 + session_id: 当前 HXOPS 本地会话号。 + payload_patch: 要合并的顶层结构化字段,不得为空。 + + Returns: + 找到且成功写入时返回 True;身份不匹配、参数为空或写入失败时返回 False。 + """ + if chat_log_id <= 0 or user_id <= 0 or agent_id <= 0 or not str(session_id or '').strip() or not payload_patch: + return False + try: + chat_log = ( + db.session.query(ChatLog) + .filter( + ChatLog.id == int(chat_log_id), + ChatLog.user_id == int(user_id), + ChatLog.agent_id == int(agent_id), + ChatLog.session_id == str(session_id).strip(), + ) + .with_for_update() + .one_or_none() + ) + if chat_log is None: + db.session.rollback() + return False + chat_log.payload = { + **(chat_log.payload if isinstance(chat_log.payload, dict) else {}), + **payload_patch, + } + db.session.commit() + return True + except Exception as exc: + if current_app: + current_app.logger.exception( + "[chat-log] failed to merge payload chat_log_id=%s: %s", + chat_log_id, + exc, + ) + db.session.rollback() + return False diff --git a/backend/app/services/chat/stream_relay.py b/backend/app/services/chat/stream_relay.py index 2619e8e1..b198a0e0 100644 --- a/backend/app/services/chat/stream_relay.py +++ b/backend/app/services/chat/stream_relay.py @@ -42,7 +42,7 @@ def iter_handler_terminal_sse( *, emitted_keys: set[str], ) -> Iterator[str]: - """上游终态事件后追加 Handler SSE(如 shipping_ui_state 刷新)。""" + """上游终态/error 事件后追加 Handler SSE(如订单抽取收口与 shipping_ui_state 刷新)。""" handler = resolve_handler_for_agent_code(ctx.agent) if handler is None: return diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 5f1787e3..324da6f0 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -862,7 +862,7 @@ class DifyService: base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE url = DifyService._build_chat_messages_url(base_url) normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id) - visible_query = str(display_query or query or '').strip() + visible_query = str(query if display_query is None else display_query).strip() headers = { 'Authorization': f'Bearer {agent.dify_api_key}', @@ -1128,19 +1128,20 @@ class DifyService: if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer: if current_app: current_app.logger.warning( - "[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently", + "[chat-stream] read timeout after answer request_id=%s attempt=%s; emit synthetic terminal", request_id, attempt, ) - persist_stream_chat( - { - 'event': 'message_end', - 'conversation_id': normalized_conversation_id, - 'answer': ''.join(full_answer).strip(), - 'metadata': {}, - }, - 'message_end', - ) + # [STEP 3] 已有正文时用合成 message_end 正常收口;persist 会把 chat_log_id 回写到同一事件, + # 领域 Handler 仍能在网络超时后完成状态持久化,而前端不会把本轮误判为永久处理中。 + timeout_end_event = { + 'event': 'message_end', + 'conversation_id': normalized_conversation_id, + 'answer': ''.join(full_answer).strip(), + 'metadata': {}, + } + persist_stream_chat(timeout_end_event, 'message_end') + yield f"data: {json.dumps(timeout_end_event, ensure_ascii=False)}\n\n" break if not is_timeout and attempt < max_retries: time.sleep(attempt * 2) @@ -1154,17 +1155,16 @@ class DifyService: message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。" else: message = str(e) - persist_stream_chat( - { - 'event': 'error', - 'conversation_id': normalized_conversation_id, - 'answer': f"[Error: {message}]", - 'metadata': {}, - }, - 'error', - ) - error_msg = json.dumps({'event': 'error', 'message': message}) - yield f"data: {error_msg}\n\n" + # [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。 + error_event = { + 'event': 'error', + 'conversation_id': normalized_conversation_id, + 'answer': f"[Error: {message}]", + 'message': message, + 'metadata': {}, + } + persist_stream_chat(error_event, 'error') + yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n" @staticmethod def _log_chat( diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 14cb49ba..7bb6abd5 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -40,7 +40,7 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]: "label": source.get("display_name") or source.get("source_code"), "value": source.get("source_code"), "description": ( - f"{source.get('source_type')} · " + f"{source.get('connector_type')} · " f"{source.get('site_id') or '-'} · " f"{source.get('warehouse_id')}" ), diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py index fbdb6a82..80cd80b7 100644 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -2,8 +2,8 @@ backend/app/services/shipping_notice/batch_from_intakes.py 用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。 -依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency、 - attachment_integrity。 +依赖:batch_from_notices、customer_auto_resolution、intake_service、intake_parse_workflow、batch_create_idempotency、 + attachment_integrity、open_existing_reservation_backfill。 逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。 幂等以 intake.create_idempotency_key 为准(覆盖混合批次 / 纯 open_existing); 批次 create_idempotency_key + process_summary.request_intake_nos 为兼容回退。 @@ -45,7 +45,11 @@ from app.services.shipping_notice.duplicate_detection import ( from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary from app.services.shipping_notice.intake_parse_workflow import candidate_to_notice_item, intake_to_notice_item from app.services.shipping_notice.intake_service import mark_intakes_consumed +from app.services.shipping_notice.open_existing_reservation_backfill import ( + backfill_exact_file_open_existing_reservations, +) from app.services.shipping_notice.tool_common import log_task_event +from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer def _batch_intake_nos(batch_id: int) -> set[str]: @@ -667,9 +671,21 @@ def create_shipping_batch_from_candidates( message='强制新建必须填写原因', ) if resolution == 'open_existing': - target = db.session.query(ShippingTask).filter_by(task_no=target_no, user_id=int(user_id)).first() + target = ( + db.session.query(ShippingTask) + .filter_by(task_no=target_no, user_id=int(user_id)) + .with_for_update() + .first() + ) if target is None: raise ConflictError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在') + backfill_exact_file_open_existing_reservations( + task=target, + candidate=candidate, + candidate_summary=summary, + duplicate_status=str(fresh.get('status') or ''), + duplicate_matches=matches, + ) candidate.consumed_task_id = int(target.id) candidate.updated_at = now opened.append({'candidate_no': candidate.candidate_no, 'task_no': target.task_no, 'batch_no': None}) @@ -705,6 +721,7 @@ def create_shipping_batch_from_candidates( raise ConflictError(code='SHIPPING.BATCH_CREATE_INCOMPLETE', message='候选任务关联不完整') candidate.consumed_task_id = int(task.id) candidate.updated_at = now + try_auto_confirm_task_customer(task) _attach_request_intake_summary( batch_obj, request_intake_nos=intake_nos, diff --git a/backend/app/services/shipping_notice/business_case_service.py b/backend/app/services/shipping_notice/business_case_service.py new file mode 100644 index 00000000..3e4e38d8 --- /dev/null +++ b/backend/app/services/shipping_notice/business_case_service.py @@ -0,0 +1,88 @@ +""" +services/shipping_notice/business_case_service.py + +用途:为新建货代任务创建或继承业务单聚合。 +依赖:db、ShippingCase、ShippingTask、uuid/datetime。 +逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单,必要时为历史父任务补建。 +""" + +from __future__ import annotations + +import uuid +from datetime import datetime + +from app import db +from app.core.errors import ConflictError +from app.models import ShippingCase, ShippingTask + + +def generate_shipping_case_no() -> str: + """生成内部业务单聚合编号;仅用于系统关联,不对外替代 business_no。""" + return f"SC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + + +def create_shipping_case(*, created_by_id: int | None = None) -> ShippingCase: + """ + 创建未绑定客户、未编号的业务单聚合。 + + Args: + created_by_id: 创建任务的用户 ID,可为空。 + Returns: + 尚未提交事务的 ShippingCase。 + """ + case = ShippingCase( + case_no=generate_shipping_case_no(), + created_by_id=created_by_id, + numbering_status='pending', + status='open', + ) + db.session.add(case) + db.session.flush() + return case + + +def resolve_shipping_case_for_new_task( + *, + supersedes_task_id: int | None = None, + duplicate_resolution_type: str | None = None, + created_by_id: int | None = None, +) -> ShippingCase: + """ + 为即将创建的任务解析业务单归属。 + + 核心逻辑:revision 继承父任务业务单;历史父任务未关联时在同一事务补建; + normal/force_create 均创建独立业务单,保证强制新建重新占用未来流水。 + + Args: + supersedes_task_id: 修订目标任务主键,仅 revision 使用。 + duplicate_resolution_type: normal/revision/force_create。 + created_by_id: 新任务创建人。 + Returns: + 新任务应关联的 ShippingCase。 + Raises: + ConflictError: revision 缺少或找不到父任务。 + """ + resolution_type = str(duplicate_resolution_type or 'normal').strip().lower() + if resolution_type != 'revision': + return create_shipping_case(created_by_id=created_by_id) + + if not supersedes_task_id: + raise ConflictError( + '修订任务缺少父任务', + code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', + ) + parent = db.session.get(ShippingTask, int(supersedes_task_id)) + if parent is None: + raise ConflictError( + '修订目标任务不存在', + code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', + details={'supersedes_task_id': supersedes_task_id}, + ) + if parent.shipping_case is not None: + return parent.shipping_case + + case = create_shipping_case(created_by_id=parent.user_id or created_by_id) + parent.shipping_case = case + db.session.flush() + return case + diff --git a/backend/app/services/shipping_notice/business_fingerprint.py b/backend/app/services/shipping_notice/business_fingerprint.py index be69ab3c..8ce12bcc 100644 --- a/backend/app/services/shipping_notice/business_fingerprint.py +++ b/backend/app/services/shipping_notice/business_fingerprint.py @@ -3,7 +3,8 @@ backend/app/services/shipping_notice/business_fingerprint.py 用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。 依赖:po_number / reservation_id 标准化函数。 -逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;算法版本 shipping-v1。 +逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用; + 身份算法版本 shipping-v1,内容算法版本 shipping-content-v3。 """ from __future__ import annotations @@ -17,7 +18,7 @@ from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.reservation_id import validated_reservation_id FINGERPRINT_VERSION = 'shipping-v1' -CONTENT_FINGERPRINT_VERSION = 'shipping-content-v2' +CONTENT_FINGERPRINT_VERSION = 'shipping-content-v3' def _norm_text(value: Any) -> str: @@ -205,7 +206,6 @@ def build_content_fingerprint(business_summary: dict[str, Any] | None) -> dict[s _norm_text(line.get('source_type')), _norm_text(line.get('customer_sku')), _norm_text(line.get('vendor_part_number')), - _norm_text(line.get('hub_code')), ] if any(values): parts.append('|'.join(values)) diff --git a/backend/app/services/shipping_notice/business_numbering_service.py b/backend/app/services/shipping_notice/business_numbering_service.py new file mode 100644 index 00000000..ea853062 --- /dev/null +++ b/backend/app/services/shipping_notice/business_numbering_service.py @@ -0,0 +1,170 @@ +""" +services/shipping_notice/business_numbering_service.py + +用途:为已确认客户的货代业务单分配不可变业务编号。 +依赖:ShippingCase/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。 +逻辑:锁定业务单后按客户与上海业务日期原子递增流水;编号写入业务单快照,事务由调用方提交。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from sqlalchemy import update + +from app import db +from app.core.errors import ConflictError +from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer +from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE + +BUSINESS_TYPE = "shipping_notice" +NUMBERING_RULE_VERSION = "shipping-customer-date-seq-v1" +SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") +MAX_DAILY_SEQUENCE = 99 + + +def shanghai_business_date(moment: datetime | None = None) -> date: + """ + 计算编号使用的上海业务日期。 + + Args: + moment: 可选时刻;有时区则转换到上海,无时区按 UTC 兼容处理。 + Returns: + Asia/Shanghai 口径的日期。 + """ + if moment is None: + return datetime.now(SHANGHAI_TZ).date() + if moment.tzinfo is None: + moment = moment.replace(tzinfo=ZoneInfo("UTC")) + return moment.astimezone(SHANGHAI_TZ).date() + + +def format_business_no(short_code: str, business_date: date, sequence_value: int) -> str: + """ + 按固定规则格式化业务编号。 + + Args: + short_code: 2-6 位大写客户简码。 + business_date: 上海业务日期。 + sequence_value: 当日客户流水,范围 1-99。 + Returns: + 无分隔符编号,例如 WYC26071501。 + """ + return f"{short_code}{business_date.strftime('%y%m%d')}{sequence_value:02d}" + + +def _next_sequence_value(customer_id: int, business_date: date) -> int: + """ + 原子取得客户当日下一流水。 + + 核心逻辑:PostgreSQL 使用 INSERT ON CONFLICT DO UPDATE RETURNING;测试 SQLite 使用条件 UPDATE, + 两条路径都只允许 1-99,避免“查询最大值 + 1”的竞态。 + """ + bind = db.session.get_bind() + dialect_name = bind.dialect.name + if dialect_name == "postgresql": + from sqlalchemy.dialects.postgresql import insert + + stmt = insert(ShippingBusinessSequence).values( + business_type=BUSINESS_TYPE, + customer_id=customer_id, + business_date=business_date, + current_value=1, + ) + stmt = stmt.on_conflict_do_update( + index_elements=["business_type", "customer_id", "business_date"], + set_={"current_value": ShippingBusinessSequence.current_value + 1}, + where=ShippingBusinessSequence.current_value < MAX_DAILY_SEQUENCE, + ).returning(ShippingBusinessSequence.current_value) + value = db.session.execute(stmt).scalar_one_or_none() + else: + stmt = ( + update(ShippingBusinessSequence) + .where( + ShippingBusinessSequence.business_type == BUSINESS_TYPE, + ShippingBusinessSequence.customer_id == customer_id, + ShippingBusinessSequence.business_date == business_date, + ShippingBusinessSequence.current_value < MAX_DAILY_SEQUENCE, + ) + .values(current_value=ShippingBusinessSequence.current_value + 1) + .returning(ShippingBusinessSequence.current_value) + ) + value = db.session.execute(stmt).scalar_one_or_none() + if value is None: + existing = db.session.query(ShippingBusinessSequence.id).filter_by( + business_type=BUSINESS_TYPE, + customer_id=customer_id, + business_date=business_date, + ).first() + if existing is None: + sequence = ShippingBusinessSequence( + business_type=BUSINESS_TYPE, + customer_id=customer_id, + business_date=business_date, + current_value=1, + ) + db.session.add(sequence) + db.session.flush() + value = 1 + + if value is None or int(value) > MAX_DAILY_SEQUENCE: + raise ConflictError( + "Customer daily business number capacity exhausted", + code="SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED", + details={ + "customer_id": customer_id, + "business_date": business_date.isoformat(), + "max_sequence": MAX_DAILY_SEQUENCE, + }, + ) + return int(value) + + +def assign_business_number(case: ShippingCase, *, moment: datetime | None = None) -> str: + """ + 为业务单幂等分配业务编号,调用方负责同事务提交。 + + 核心逻辑:已有编号直接返回;否则校验启用客户与简码快照,取得上海日期流水并写入不可变编号字段。 + + Args: + case: 已加锁且已绑定标准客户的业务单。 + moment: 可选测试时刻。 + Returns: + 分配或已存在的业务编号。 + Raises: + ConflictError: 客户无效、简码缺失或当日两位流水耗尽。 + """ + if case.business_no: + return str(case.business_no) + if case.customer_id is None: + raise ConflictError( + "Shipping case customer must be confirmed before numbering", + code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED", + ) + customer = db.session.get(ShippingCustomer, int(case.customer_id)) + if customer is None or customer.status != "active": + raise ConflictError( + "Active customer is required before numbering", + code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID", + ) + + short_code = str(customer.short_code or "").strip().upper() + if not SHORT_CODE_RE.fullmatch(short_code): + raise ConflictError( + "Customer short code is invalid for business numbering", + code="SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID", + details={"customer_id": customer.id, "short_code": short_code}, + ) + business_date = shanghai_business_date(moment) + sequence_value = _next_sequence_value(customer.id, business_date) + business_no = format_business_no(short_code, business_date, sequence_value) + case.customer_name_snapshot = customer.standard_name + case.customer_short_code_snapshot = short_code + case.business_date = business_date + case.sequence_value = sequence_value + case.numbering_rule_version = NUMBERING_RULE_VERSION + case.numbering_status = "assigned" + case.business_no = business_no + db.session.flush() + return business_no diff --git a/backend/app/services/shipping_notice/candidate_validation.py b/backend/app/services/shipping_notice/candidate_validation.py index c630fac6..5b531fec 100644 --- a/backend/app/services/shipping_notice/candidate_validation.py +++ b/backend/app/services/shipping_notice/candidate_validation.py @@ -16,15 +16,15 @@ from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.reservation_id import validated_reservation_id BUILD_REQUIRED_FIELDS = ('sku', 'qty') -PROCESS_FIELDS = ('reservation_id', 'hub_code', 'source_type') +PROCESS_FIELDS = ('reservation_id',) def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[str, Any]: """ 评估规则/LLM订单结果是否达到自动建单最低条件,同时保留不完整内容供自然对话修订。 - 核心逻辑:SKU + 正数 Qty 是建单硬条件;Reservation/Hub/Source Type 属于流程字段, - 缺失或格式异常时允许创建 Task,但必须进入后续字段补充门禁。 + 核心逻辑:SKU + 正数 Qty 是建单硬条件;Reservation ID 是唯一流程门禁字段。 + 行级 source_type 仅保留为可选库存源路由线索,缺失时不阻断建单或后续流程。 Args: summary: 单个订单的业务摘要。 diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index 0c3a4a67..bfe90155 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -27,6 +27,7 @@ CP_UPLOAD_REQ = "upload_req" CP_MAP_OK = "map_ok" CP_PARSE_OK = "parse_ok" CP_PARSE_REVIEW = "parse_review" +CP_CUSTOMER_REVIEW = "customer_review" CP_TASK_EXISTS = "task_exists" CP_RSV_REQ = "rsv_req" CP_UPLOAD_FAILED = "upload_failed" diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py new file mode 100644 index 00000000..7783b019 --- /dev/null +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -0,0 +1,425 @@ +""" +services/shipping_notice/customer_auto_resolution.py + +用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。 +依赖:ShippingCustomerIdentifier/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。 +逻辑:Candidate 建单后仅以已审核强证据自动确认;管理员纠错时保留原号作废并创建替代业务单。 +""" + +from __future__ import annotations + +import hashlib +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingCase, + ShippingCustomer, + ShippingCustomerIdentifier, + ShippingCustomerShadowResolution, + ShippingNoticeCandidate, + ShippingTask, + ShippingTaskEvent, +) +from app.services.shipping_notice.customer_identity_gate import confirm_task_customer +from app.services.shipping_notice.customer_normalization import is_public_email_domain +from app.services.shipping_notice.tool_common import cfg_bool +from app.services.shipping_notice.business_case_service import generate_shipping_case_no +from app.services.shipping_notice.business_numbering_service import assign_business_number + +AUTO_RESOLUTION_VERSION = "customer-auto-v1" +AUTO_IDENTIFIER_TYPES = frozenset({"email", "domain", "template_fingerprint"}) +CUSTOMER_AUDIT_EVENT_TYPES = ( + "customer_auto_resolution_evaluated", + "customer_auto_confirmed", + "customer_correction_applied", + "customer_historical_backfilled", +) + + +def auto_customer_resolution_enabled() -> bool: + """读取自动客户确认总开关;默认关闭以支持安全降级。""" + return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False) + + +def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool: + """判断识别证据是否达到自动确认门槛。""" + if identifier.status != "approved" or not identifier.auto_match_allowed: + return False + if identifier.identifier_type not in AUTO_IDENTIFIER_TYPES: + return False + if identifier.identifier_type == "domain" and is_public_email_domain(identifier.normalized_value): + return False + return True + + +def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]: + """ + 使用任务来源 Candidate 的影子证据执行受控自动裁决。 + + Args: + task: 已创建但客户仍 pending 的任务。 + Returns: + status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。 + """ + if not auto_customer_resolution_enabled(): + return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} + if task.source_candidate_id is None: + return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} + shadow = db.session.query(ShippingCustomerShadowResolution).filter_by( + candidate_id=int(task.source_candidate_id), + ).first() + if shadow is None: + candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id)) + if candidate is not None: + from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution + + shadow = refresh_candidate_shadow_resolution(candidate) + if shadow is None: + return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} + + matched: dict[int, list[dict[str, Any]]] = {} + for evidence in shadow.evidence_json or []: + if not isinstance(evidence, dict): + continue + kind = str(evidence.get("type") or "").strip() + normalized = str(evidence.get("normalized_value") or "").strip() + if kind not in AUTO_IDENTIFIER_TYPES or not normalized: + continue + identifiers = db.session.query(ShippingCustomerIdentifier).filter_by( + identifier_type=kind, + normalized_value=normalized, + ).all() + for identifier in identifiers: + if not _eligible_identifier(identifier): + continue + customer = db.session.get(ShippingCustomer, int(identifier.customer_id)) + if customer is None or customer.status != "active": + continue + matched.setdefault(customer.id, []).append({ + "identifier_id": identifier.id, + "identifier_type": kind, + "normalized_value": normalized, + }) + if len(matched) != 1: + return { + "status": "ambiguous" if matched else "unmatched", + "rule_version": AUTO_RESOLUTION_VERSION, + "customer_id": None, + "evidence": [item for rows in matched.values() for item in rows], + "candidate_customer_ids": sorted(matched), + } + customer_id = next(iter(matched)) + return { + "status": "unique_strong_match", + "rule_version": AUTO_RESOLUTION_VERSION, + "customer_id": customer_id, + "evidence": matched[customer_id], + } + + +def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]: + """ + 尝试自动确认并生成业务编号;未达门槛时保持 customer_review。 + + 核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。 + """ + if task.customer_resolution_status == "confirmed": + return {"status": "already_confirmed", "customer_id": task.shipping_case.customer_id if task.shipping_case else None} + decision = resolve_auto_customer_from_shadow(task) + db.session.add(ShippingTaskEvent( + task_id=task.id, + event_type="customer_auto_resolution_evaluated", + detail_json=decision, + )) + if decision.get("customer_id") is None: + db.session.flush() + return decision + + updated = confirm_task_customer( + task, + customer_id=int(decision["customer_id"]), + actor_id=None, + resolution_method="auto_rule", + commit=False, + ) + db.session.add(ShippingTaskEvent( + task_id=updated.id, + event_type="customer_auto_confirmed", + detail_json={ + **decision, + "business_no": updated.shipping_case.business_no if updated.shipping_case else None, + }, + )) + db.session.flush() + return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no} + + +def backfill_historical_task_customer( + task: ShippingTask, + *, + customer_id: int, + actor_id: int | None, +) -> dict[str, Any]: + """ + 为历史无业务单任务回填标准客户,但默认不生成历史业务编号。 + + Args: + task: shipping_case_id 为空且 task_no 为历史技术号的任务。 + customer_id: 管理员确认的标准客户 ID。 + actor_id: 管理员审计 ID。 + Returns: + 回填后的 task_no、customer_id、business_no(None)。 + """ + customer = db.session.get(ShippingCustomer, int(customer_id)) + if customer is None or customer.status != "active": + raise ValueError("active customer is required") + if task.shipping_case_id is not None: + raise ValueError("historical backfill only supports tasks without a shipping case") + case = ShippingCase( + case_no=generate_shipping_case_no(), + customer_id=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + numbering_status="historical_unnumbered", + status="open", + created_by_id=actor_id, + ) + db.session.add(case) + db.session.flush() + task.shipping_case_id = case.id + task.customer_resolution_status = "confirmed" + task.customer_resolution_method = "historical_backfill" + task.customer_confirmed_by = actor_id + task.customer_confirmed_at = datetime.utcnow() + db.session.add(ShippingTaskEvent( + task_id=task.id, + event_type="customer_historical_backfilled", + detail_json={"customer_id": customer.id, "business_no": None}, + )) + db.session.commit() + return {"task_no": task.task_no, "customer_id": customer.id, "business_no": None} + + +def correct_numbered_task_customer( + task: ShippingTask, + *, + customer_id: int, + reason: str, + actor_id: int | None, +) -> dict[str, Any]: + """ + 更正已编号业务单的标准客户,同时保留原号作废与替代关系。 + + 核心逻辑:锁定原业务单并校验未上传 → 创建替代业务单和新号 → 迁移整条任务版本链 → + 清理当前版本的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 + + Args: + task: 原业务号或技术号定位到的当前任务版本。 + customer_id: 管理员确认的正确启用客户 ID。 + reason: 必填纠错原因,写入审计事件。 + actor_id: 管理员审计 ID。 + Returns: + 原号、新号、替代业务单和受影响任务信息。 + Raises: + ValidationError: 缺少原因、客户无效或客户未变化。 + ConflictError: 业务单未编号、已上传或已被替代。 + """ + correction_reason = str(reason or "").strip() + if not correction_reason: + raise ValidationError( + "Customer correction reason is required", + code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED", + ) + if task.shipping_case_id is None: + raise ConflictError( + "Numbered shipping case is required for customer correction", + code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", + ) + + original_case = ( + db.session.query(ShippingCase) + .filter(ShippingCase.id == int(task.shipping_case_id)) + .with_for_update() + .one_or_none() + ) + if original_case is None: + raise NotFoundError("Shipping case not found", code="SHIPPING.CASE_NOT_FOUND") + if not original_case.business_no: + raise ConflictError( + "Numbered shipping case is required for customer correction", + code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", + ) + existing_replacement = db.session.query(ShippingCase.id).filter_by( + replaces_case_id=original_case.id, + ).first() + if existing_replacement is not None or original_case.status == "voided": + raise ConflictError( + "Shipping case has already been replaced", + code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED", + ) + + customer = db.session.get(ShippingCustomer, int(customer_id)) + if customer is None: + raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND") + if customer.status != "active": + raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE") + if original_case.customer_id == customer.id: + raise ValidationError( + "Corrected customer must differ from the current customer", + code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED", + ) + + versions = ( + db.session.query(ShippingTask) + .filter_by(shipping_case_id=original_case.id) + .order_by(ShippingTask.document_version.asc(), ShippingTask.id.asc()) + .with_for_update() + .all() + ) + if not versions: + raise ConflictError( + "Shipping case has no task versions", + code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING", + ) + if any( + version.process_status == "uploaded" + or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"} + for version in versions + ): + raise ConflictError( + "Uploaded shipping cases require an external cancellation workflow before correction", + code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED", + ) + + old_business_no = str(original_case.business_no) + replacement = ShippingCase( + case_no=generate_shipping_case_no(), + customer_id=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + numbering_status="pending", + status="open", + replaces_case_id=original_case.id, + created_by_id=actor_id, + ) + db.session.add(replacement) + db.session.flush() + new_business_no = assign_business_number(replacement) + + original_case.status = "voided" + original_case.numbering_status = "voided" + now = datetime.utcnow() + customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() + latest = max(versions, key=lambda item: (int(item.document_version or 1), int(item.id))) + for version in versions: + version.shipping_case_id = replacement.id + version.customer_resolution_status = "confirmed" + version.customer_resolution_method = "admin_correction" + version.customer_identity_fingerprint = customer_fingerprint + version.customer_confirmed_by = actor_id + version.customer_confirmed_at = now + db.session.add(ShippingTaskEvent( + task_id=version.id, + event_type="customer_correction_applied", + detail_json={ + "old_case_id": original_case.id, + "new_case_id": replacement.id, + "old_business_no": old_business_no, + "new_business_no": new_business_no, + "old_customer_id": original_case.customer_id, + "new_customer_id": customer.id, + "reason": correction_reason, + "actor_id": actor_id, + }, + )) + + # 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。 + latest.inventory_source_code = None + latest.inventory_connector_type = None + latest.inventory_site_id = None + latest.inventory_warehouse_id = None + latest.inventory_source_status = None + latest.inventory_source_method = None + latest.inventory_source_confirmed_by = None + latest.inventory_source_confirmed_at = None + latest.inventory_source_config_version = None + latest.inventory_routing_fingerprint = None + latest.inventory_rpa_consumed_run_no = None + latest.inventory_snapshot_id = None + latest.inventory_lines_json = None + latest.match_status = None + latest.shortage_json = None + latest.line_results_json = None + latest.export_file_path = None + latest.export_file_name = None + latest.freight_ref_no = None + latest.upload_status = None + latest.upload_mode = None + latest.upload_attempt = 0 + latest.upload_started_at = None + latest.upload_finished_at = None + latest.upload_error_code = None + latest.upload_error_message = None + latest.upload_receipt_json = None + latest.idempotency_key = None + latest.process_status = "parsed" + latest.current_step = None + latest.review_status = None + latest.pending_human_reason = None + latest.error_message = None + db.session.commit() + return { + "task_no": latest.task_no, + "old_case_id": original_case.id, + "new_case_id": replacement.id, + "old_business_no": old_business_no, + "new_business_no": new_business_no, + "customer_id": customer.id, + "affected_task_count": len(versions), + } + + +def get_auto_resolution_metrics() -> dict[str, Any]: + """汇总自动裁决、纠错和回填事件,供管理员监控、查询与降级判断。""" + evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by( + event_type="customer_auto_resolution_evaluated", + ).distinct().count() + confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by( + event_type="customer_auto_confirmed", + ).distinct().count() + corrected = db.session.query(ShippingTaskEvent.task_id).filter_by( + event_type="customer_correction_applied", + ).distinct().count() + backfilled = db.session.query(ShippingTaskEvent.task_id).filter_by( + event_type="customer_historical_backfilled", + ).distinct().count() + recent_events = ( + db.session.query(ShippingTaskEvent, ShippingTask.task_no) + .join(ShippingTask, ShippingTask.id == ShippingTaskEvent.task_id) + .filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES)) + .order_by(ShippingTaskEvent.id.desc()) + .limit(100) + .all() + ) + return { + "enabled": auto_customer_resolution_enabled(), + "rule_version": AUTO_RESOLUTION_VERSION, + "evaluated_count": evaluated, + "auto_confirmed_count": confirmed, + "corrected_task_count": corrected, + "historical_backfilled_count": backfilled, + "auto_confirmation_rate": (confirmed / evaluated) if evaluated else None, + "recent_events": [ + { + "id": event.id, + "task_no": task_no, + "event_type": event.event_type, + "detail": event.detail_json or {}, + "created_at": event.created_at.isoformat() if event.created_at else None, + } + for event, task_no in recent_events + ], + } diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py new file mode 100644 index 00000000..72318e5f --- /dev/null +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -0,0 +1,231 @@ +""" +backend/app/services/shipping_notice/customer_identity_gate.py + +用途:货代任务标准客户确认、业务编号生成、候选查询与统一下游硬门禁。 +依赖:ShippingTask/Case/Customer/Event、business_numbering_service、统一 AppError、customer_normalization。 +逻辑:业务用户只能选择已启用标准客户;确认与业务编号在同一事务完成,并同步业务单全部任务版本。 +""" + +from __future__ import annotations + +import hashlib +from datetime import datetime +from typing import Any + +from sqlalchemy import or_ + +from app import db +from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError +from app.models import ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent +from app.services.shipping_notice.customer_normalization import clean_text +from app.services.shipping_notice.business_numbering_service import assign_business_number + +CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' + + +def customer_identity_is_confirmed(task: ShippingTask) -> bool: + """判断任务是否通过客户 Gate;无业务单历史任务兼容放行。""" + if task.shipping_case_id is None: + return True + case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id)) + if case is None or case.customer_id is None: + return False + customer = db.session.get(ShippingCustomer, int(case.customer_id)) + return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed') + + +def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None: + """ + 标准客户硬门禁;新业务单未确认时阻断库存、RPA、匹配、Excel 与上传。 + + Args: + task: 当前发货任务;历史无业务单任务兼容放行。 + operation: 触发门禁的操作名,写入错误详情。 + Raises: + AppError: 客户尚未确认、客户已停用或业务单关联无效。 + """ + if customer_identity_is_confirmed(task): + return + case = task.shipping_case or ( + db.session.get(ShippingCase, int(task.shipping_case_id)) if task.shipping_case_id else None + ) + raise AppError( + code=CUSTOMER_GATE_ERROR_CODE, + message='标准客户尚未确认,无法继续后续流程', + http_status=409, + details={ + 'operation': operation, + 'task_no': task.task_no, + 'shipping_case_id': task.shipping_case_id, + 'customer_resolution_status': task.customer_resolution_status or 'pending', + 'customer_id': case.customer_id if case else None, + }, + ) + + +def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str, Any]]: + """列出启用标准客户,供业务用户人工确认;不暴露识别证据和管理字段。""" + customer_query = db.session.query(ShippingCustomer).filter_by(status='active') + keyword = clean_text(query) + if keyword: + like = f'%{keyword}%' + customer_query = customer_query.filter( + or_(ShippingCustomer.standard_name.ilike(like), ShippingCustomer.short_code.ilike(like)) + ) + rows = customer_query.order_by(ShippingCustomer.standard_name.asc(), ShippingCustomer.id.asc()).limit( + max(1, min(int(limit or 100), 200)) + ).all() + return [{'id': row.id, 'standard_name': row.standard_name, 'short_code': row.short_code} for row in rows] + + +def confirm_task_customer( + task: ShippingTask, + *, + customer_id: int, + actor_id: int | None, + resolution_method: str = 'manual', + commit: bool = True, +) -> ShippingTask: + """ + 人工确认任务所属标准客户,并同步共享业务单下所有任务版本。 + + 核心逻辑:锁定业务单 → 校验启用客户 → 原子分配业务号 → 同步 revision 任务确认状态和事件。 + 客户确认与编号同事务提交,任何一步失败都不留下半确认状态。 + + Args: + task: 待确认客户的任务。 + customer_id: 启用标准客户主键。 + actor_id: 人工操作人;自动规则可为空。 + resolution_method: manual/auto_rule 等审计方法。 + commit: 是否提交事务;批次编排传 False 由外层统一提交。 + """ + if task.shipping_case_id is None: + raise ConflictError( + 'Legacy tasks without a shipping case cannot confirm customer in this workflow', + code='SHIPPING.CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED', + ) + case = ( + db.session.query(ShippingCase) + .filter(ShippingCase.id == int(task.shipping_case_id)) + .with_for_update() + .one_or_none() + ) + if case is None: + raise NotFoundError('Shipping case not found', code='SHIPPING.CASE_NOT_FOUND') + customer = db.session.get(ShippingCustomer, int(customer_id)) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if customer.status != 'active': + raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') + if case.business_no and case.customer_id not in {None, customer.id}: + raise ConflictError( + 'Numbered shipping case customer cannot be changed silently', + code='SHIPPING.CUSTOMER_NUMBERED_CASE_LOCKED', + ) + + now = datetime.utcnow() + previous_customer_id = case.customer_id + number_was_assigned = bool(case.business_no) + case.customer_id = customer.id + case.customer_name_snapshot = customer.standard_name + case.customer_short_code_snapshot = customer.short_code + business_no = assign_business_number(case) + fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest() + tasks = db.session.query(ShippingTask).filter_by(shipping_case_id=case.id).all() + for version in tasks: + version.customer_resolution_status = 'confirmed' + version.customer_resolution_method = resolution_method + version.customer_identity_fingerprint = fingerprint + version.customer_confirmed_by = actor_id + version.customer_confirmed_at = now + db.session.add(ShippingTaskEvent( + task_id=version.id, + event_type='customer_confirmed', + detail_json={ + 'customer_id': customer.id, + 'standard_name': customer.standard_name, + 'short_code': customer.short_code, + 'previous_customer_id': previous_customer_id, + 'method': resolution_method, + 'business_no': business_no, + }, + )) + if not number_was_assigned: + db.session.add(ShippingTaskEvent( + task_id=version.id, + event_type='business_number_assigned', + detail_json={ + 'business_no': business_no, + 'business_date': case.business_date.isoformat() if case.business_date else None, + 'sequence_value': case.sequence_value, + 'numbering_rule_version': case.numbering_rule_version, + }, + )) + if commit: + db.session.commit() + return db.session.get(ShippingTask, int(task.id)) + db.session.flush() + return task + + +def customer_gate_tool_response(task: ShippingTask, *, operation: str) -> dict[str, Any] | None: + """Tool 公共入口将客户 Gate 转为 needs_human 响应,未阻断时返回 None。""" + if customer_identity_is_confirmed(task): + return None + from app.services.shipping_notice.query_service import serialize_task_for_tool + from app.services.shipping_notice.tool_response import tool_response + + return tool_response( + status='needs_human', + task=task, + message='标准客户尚未确认,请先选择正式客户后再继续。', + data=serialize_task_for_tool(task), + human_options=['confirm_customer'], + checkpoint='customer_review', + stop_agent_turn=True, + forbidden_next_tools=[ + 'ensure_inventory', 'parse_inventory', 'match_inventory', + 'generate_shipment_excel', 'upload_to_freight', + ], + ) + + +def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]: + """ + Tool 入口确认标准客户。 + 【AI 触发时机】:用户在 customer_review 检查点明确选择标准客户后调用。 + + Args: + payload: 须含 task_id/customer_id,可含 user_id 作为审计人。 + Returns: + Tool 标准响应;data.business_no 返回正式业务编号。 + """ + from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool + from app.services.shipping_notice.tool_response import tool_response + + task = resolve_task_from_payload(payload) + if task is None: + return tool_response(status='failed', message='未找到任务编号') + try: + customer_id = int(payload.get('customer_id')) + except (TypeError, ValueError): + return tool_response( + status='needs_human', + task=task, + message='请选择标准客户。', + data=serialize_task_for_tool(task), + human_options=['confirm_customer'], + checkpoint='customer_review', + stop_agent_turn=True, + ) + updated = confirm_task_customer( + task, + customer_id=customer_id, + actor_id=int(payload.get('user_id')) if payload.get('user_id') is not None else None, + ) + return tool_response( + status='ok', + task=updated, + message='标准客户已确认,可以继续库存与履约流程。', + data=serialize_task_for_tool(updated), + ) diff --git a/backend/app/services/shipping_notice/customer_normalization.py b/backend/app/services/shipping_notice/customer_normalization.py new file mode 100644 index 00000000..63eec73c --- /dev/null +++ b/backend/app/services/shipping_notice/customer_normalization.py @@ -0,0 +1,132 @@ +""" +services/shipping_notice/customer_normalization.py + +用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验。 +依赖:re、unicodedata 标准库。 +逻辑:管理后台导入与运行期客户裁决共用,避免同一证据在不同入口产生不同匹配键。 +""" + +from __future__ import annotations + +import re +import unicodedata +from typing import Any + +from app.core.errors import ValidationError + +SHORT_CODE_RE = re.compile(r'^[A-Z]{2,6}$') +EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$') +PUBLIC_EMAIL_DOMAINS = frozenset({ + '126.com', + '163.com', + 'gmail.com', + 'hotmail.com', + 'icloud.com', + 'live.com', + 'outlook.com', + 'qq.com', + 'yahoo.com', +}) +IDENTIFIER_TYPES = frozenset({'name_alias', 'email', 'domain', 'template_fingerprint', 'address', 'contact'}) + + +def clean_text(value: Any) -> str: + """将任意输入规范为去首尾空白、合并内部空白的展示文本。""" + text = unicodedata.normalize('NFKC', str(value or '')).strip() + return re.sub(r'\s+', ' ', text) + + +def normalize_customer_name(value: Any) -> str: + """生成不区分大小写和常见标点的客户名称匹配键。""" + text = clean_text(value).upper() + return re.sub(r'[\s\-_,.,。()()]+', '', text) + + +def normalize_short_code(value: Any) -> str: + """ + 校验并返回客户简码。 + + Args: + value: 管理员输入的客户简码。 + Returns: + 2-6 位大写英文字母。 + Raises: + ValidationError: 简码为空或格式不合法。 + """ + code = clean_text(value).upper() + if not SHORT_CODE_RE.fullmatch(code): + raise ValidationError( + 'Customer short code must contain 2-6 uppercase letters', + code='SHIPPING.CUSTOMER_SHORT_CODE_INVALID', + details={'field': 'short_code'}, + ) + return code + + +def normalize_email(value: Any) -> str: + """校验并返回小写完整邮箱地址。""" + email = clean_text(value).lower() + if not EMAIL_RE.fullmatch(email): + raise ValidationError( + 'Invalid customer email', + code='SHIPPING.CUSTOMER_EMAIL_INVALID', + details={'field': 'identifier_value'}, + ) + return email + + +def normalize_domain(value: Any) -> str: + """移除协议、路径与前导 www,返回小写邮箱/网站域名。""" + domain = clean_text(value).lower() + domain = re.sub(r'^https?://', '', domain).split('/', 1)[0].split('@')[-1].strip('.') + if not domain or '.' not in domain or re.search(r'[^a-z0-9.-]', domain): + raise ValidationError( + 'Invalid customer domain', + code='SHIPPING.CUSTOMER_DOMAIN_INVALID', + details={'field': 'identifier_value'}, + ) + return domain + + +def is_public_email_domain(value: Any) -> bool: + """判断域名是否属于不可用于客户自动确认的公共邮箱。""" + try: + return normalize_domain(value) in PUBLIC_EMAIL_DOMAINS + except ValidationError: + return False + + +def normalize_identifier(identifier_type: Any, value: Any) -> str: + """ + 按证据类型生成稳定匹配键。 + + Args: + identifier_type: name_alias/email/domain/template_fingerprint/address/contact。 + value: 原始识别证据。 + Returns: + 标准化匹配值。 + Raises: + ValidationError: 类型或值不合法。 + """ + kind = clean_text(identifier_type).lower() + if kind not in IDENTIFIER_TYPES: + raise ValidationError( + 'Unsupported customer identifier type', + code='SHIPPING.CUSTOMER_IDENTIFIER_TYPE_INVALID', + details={'identifier_type': kind}, + ) + if kind == 'email': + return normalize_email(value) + if kind == 'domain': + return normalize_domain(value) + if kind == 'name_alias': + normalized = normalize_customer_name(value) + else: + normalized = clean_text(value).upper() + if not normalized: + raise ValidationError( + 'Customer identifier value is required', + code='SHIPPING.CUSTOMER_IDENTIFIER_VALUE_REQUIRED', + details={'field': 'identifier_value'}, + ) + return normalized diff --git a/backend/app/services/shipping_notice/customer_shadow_resolution.py b/backend/app/services/shipping_notice/customer_shadow_resolution.py new file mode 100644 index 00000000..a4a76b8c --- /dev/null +++ b/backend/app/services/shipping_notice/customer_shadow_resolution.py @@ -0,0 +1,274 @@ +""" +backend/app/services/shipping_notice/customer_shadow_resolution.py + +用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。 +依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。 +逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingTask 或业务编号。 +""" + +from __future__ import annotations + +from collections import defaultdict +from datetime import datetime +from email.utils import parseaddr +import logging +from typing import Any + +from sqlalchemy import func + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + ShippingCustomer, + ShippingCustomerIdentifier, + ShippingCustomerShadowResolution, + ShippingNoticeCandidate, + ShippingNoticeIntake, +) +from app.services.shipping_notice.customer_normalization import ( + is_public_email_domain, + normalize_customer_name, + normalize_domain, + normalize_email, + normalize_identifier, +) + +RESOLUTION_VERSION = 'shadow-v1' +EVIDENCE_WEIGHTS = {'email': 100.0, 'domain': 80.0, 'name_alias': 70.0, 'standard_name': 60.0} +logger = logging.getLogger(__name__) + + +def _extract_evidence(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake) -> list[dict[str, Any]]: + """从业务摘要和邮件元数据提取可审计证据,不把解析客户码当稳定客户键。""" + structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {} + summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {} + intake_structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} + email_meta = intake_structured.get('email') if isinstance(intake_structured.get('email'), dict) else {} + evidence: list[dict[str, Any]] = [] + customer_name = str(summary.get('customer_name') or '').strip() + if customer_name: + evidence.append({'type': 'name_alias', 'raw_value': customer_name, 'normalized_value': normalize_customer_name(customer_name)}) + template_fingerprint = str( + structured.get('template_fingerprint') + or intake_structured.get('template_fingerprint') + or '' + ).strip() + if template_fingerprint: + evidence.append({ + 'type': 'template_fingerprint', + 'raw_value': template_fingerprint, + 'normalized_value': normalize_identifier('template_fingerprint', template_fingerprint), + }) + sender = parseaddr(str(email_meta.get('from') or ''))[1].strip().lower() + if sender: + try: + normalized_email = normalize_email(sender) + evidence.append({'type': 'email', 'raw_value': sender, 'normalized_value': normalized_email}) + domain = normalize_domain(normalized_email) + if not is_public_email_domain(domain): + evidence.append({'type': 'domain', 'raw_value': domain, 'normalized_value': domain}) + except ValidationError: + pass + return evidence + + +def _rank_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]: + """仅用启用客户和 approved 标识聚合确定性分数,返回稳定排序候选。""" + scores: dict[int, float] = defaultdict(float) + reasons: dict[int, list[dict[str, Any]]] = defaultdict(list) + active_customers = db.session.query(ShippingCustomer).filter_by(status='active').all() + active_ids = {int(item.id) for item in active_customers} + by_name: dict[str, list[ShippingCustomer]] = defaultdict(list) + for customer in active_customers: + by_name[normalize_customer_name(customer.standard_name)].append(customer) + for item in evidence: + kind = str(item.get('type') or '') + normalized = str(item.get('normalized_value') or '') + if kind == 'name_alias' and normalized in by_name: + for customer in by_name[normalized]: + scores[customer.id] += EVIDENCE_WEIGHTS['standard_name'] + reasons[customer.id].append({'type': 'standard_name', 'value': normalized}) + identifiers = db.session.query(ShippingCustomerIdentifier).filter_by( + identifier_type=kind, + normalized_value=normalized, + status='approved', + ).all() + for identifier in identifiers: + if int(identifier.customer_id) not in active_ids: + continue + scores[identifier.customer_id] += EVIDENCE_WEIGHTS.get(kind, 0.0) + reasons[identifier.customer_id].append({'type': kind, 'identifier_id': identifier.id, 'value': normalized}) + customers = {item.id: item for item in active_customers} + return sorted( + [ + { + 'customer_id': customer_id, + 'standard_name': customers[customer_id].standard_name, + 'short_code': customers[customer_id].short_code, + 'score': score, + 'reasons': reasons[customer_id], + } + for customer_id, score in scores.items() + ], + key=lambda item: (-float(item['score']), int(item['customer_id'])), + ) + + +def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> ShippingCustomerShadowResolution: + """幂等刷新 Candidate 影子识别;只写审计结果,不执行客户绑定或自动确认。""" + intake = db.session.get(ShippingNoticeIntake, int(candidate.intake_id)) + if intake is None: + raise NotFoundError('Shipping intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND') + evidence = _extract_evidence(candidate, intake) + matches = _rank_matches(evidence) + top_score = float(matches[0]['score']) if matches else None + tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else [] + status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous' + row = db.session.query(ShippingCustomerShadowResolution).filter_by(candidate_id=int(candidate.id)).first() + if row is None: + row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id)) + db.session.add(row) + row.intake_id = int(candidate.intake_id) + row.resolution_version = RESOLUTION_VERSION + row.status = status + row.evidence_json = evidence + row.candidate_matches_json = matches + row.top_customer_id = int(matches[0]['customer_id']) if status == 'unique_candidate' else None + row.top_score = top_score + row.updated_at = datetime.utcnow() + db.session.flush() + return row + + +def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidate) -> None: + """用 SAVEPOINT 隔离影子识别异常;任何失败均不得中断 Candidate 主流程。""" + try: + with db.session.begin_nested(): + refresh_candidate_shadow_resolution(candidate) + except Exception as exc: + logger.warning( + 'Customer shadow resolution failed candidate_id=%s error_type=%s', + candidate.id, + type(exc).__name__, + ) + try: + with db.session.begin_nested(): + row = db.session.query(ShippingCustomerShadowResolution).filter_by( + candidate_id=int(candidate.id), + ).first() + if row is None: + row = ShippingCustomerShadowResolution( + candidate_id=int(candidate.id), + intake_id=int(candidate.intake_id), + ) + db.session.add(row) + row.resolution_version = RESOLUTION_VERSION + row.status = 'failed' + row.evidence_json = [] + row.candidate_matches_json = [] + row.top_customer_id = None + row.top_score = None + row.updated_at = datetime.utcnow() + db.session.flush() + except Exception: + logger.warning( + 'Customer shadow failure audit could not be persisted candidate_id=%s', + candidate.id, + exc_info=True, + ) + + +def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: int | None) -> dict[str, Any]: + """管理员为历史样本写入标准客户真值标签,供准确率计算,不触发业务绑定。""" + row = db.session.get(ShippingCustomerShadowResolution, resolution_id) + customer = db.session.get(ShippingCustomer, customer_id) + if row is None: + raise NotFoundError('Shadow resolution not found', code='SHIPPING.CUSTOMER_SHADOW_NOT_FOUND') + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + row.manual_customer_id = customer.id + row.labeled_by_id = actor_id + row.labeled_at = datetime.utcnow() + db.session.commit() + return serialize_shadow_resolution(row) + + +def serialize_shadow_resolution( + row: ShippingCustomerShadowResolution, + *, + candidate: ShippingNoticeCandidate | None = None, + intake: ShippingNoticeIntake | None = None, + manual_customer: ShippingCustomer | None = None, +) -> dict[str, Any]: + """序列化影子识别结果;报告可传入批量预加载对象以避免 N+1。""" + candidate = candidate or db.session.get(ShippingNoticeCandidate, int(row.candidate_id)) + intake = intake or db.session.get(ShippingNoticeIntake, int(row.intake_id)) + if manual_customer is None and row.manual_customer_id is not None: + manual_customer = db.session.get(ShippingCustomer, int(row.manual_customer_id)) + return { + 'id': row.id, + 'candidate_id': row.candidate_id, + 'intake_id': row.intake_id, + 'candidate_no': candidate.candidate_no if candidate else None, + 'intake_no': intake.intake_no if intake else None, + 'resolution_version': row.resolution_version, + 'status': row.status, + 'evidence': row.evidence_json or [], + 'matches': row.candidate_matches_json or [], + 'top_customer_id': row.top_customer_id, + 'top_score': row.top_score, + 'manual_customer_id': row.manual_customer_id, + 'manual_customer_name': manual_customer.standard_name if manual_customer else None, + 'manual_customer_short_code': manual_customer.short_code if manual_customer else None, + 'is_correct': row.top_customer_id == row.manual_customer_id if row.manual_customer_id is not None else None, + 'labeled_at': row.labeled_at.isoformat() if row.labeled_at else None, + } + + +def get_shadow_quality_report(*, limit: int = 100) -> dict[str, Any]: + """返回影子识别分布和最近样本;准确率只以已人工标注样本为分母。""" + query = db.session.query(ShippingCustomerShadowResolution) + total = query.count() + status_counts = dict( + query.with_entities(ShippingCustomerShadowResolution.status, func.count()) + .group_by(ShippingCustomerShadowResolution.status) + .all() + ) + labeled = query.filter(ShippingCustomerShadowResolution.manual_customer_id.isnot(None)).all() + correct = sum(item.top_customer_id == item.manual_customer_id for item in labeled) + rows = query.order_by(ShippingCustomerShadowResolution.updated_at.desc()).limit(max(1, min(limit, 500))).all() + candidate_ids = [int(item.candidate_id) for item in rows] + intake_ids = [int(item.intake_id) for item in rows] + manual_customer_ids = [int(item.manual_customer_id) for item in rows if item.manual_customer_id is not None] + candidates = { + item.id: item + for item in db.session.query(ShippingNoticeCandidate).filter(ShippingNoticeCandidate.id.in_(candidate_ids)).all() + } if candidate_ids else {} + intakes = { + item.id: item + for item in db.session.query(ShippingNoticeIntake).filter(ShippingNoticeIntake.id.in_(intake_ids)).all() + } if intake_ids else {} + manual_customers = { + item.id: item + for item in db.session.query(ShippingCustomer).filter(ShippingCustomer.id.in_(manual_customer_ids)).all() + } if manual_customer_ids else {} + from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics + + auto_metrics = get_auto_resolution_metrics() + return { + 'total': total, + 'status_counts': status_counts, + 'labeled_count': len(labeled), + 'correct_count': correct, + 'accuracy': (correct / len(labeled)) if labeled else None, + 'auto_bound_count': auto_metrics['auto_confirmed_count'], + 'items': [ + serialize_shadow_resolution( + item, + candidate=candidates.get(item.candidate_id), + intake=intakes.get(item.intake_id), + manual_customer=manual_customers.get(item.manual_customer_id), + ) + for item in rows + ], + } diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index f320c736..0999cddc 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -2,7 +2,7 @@ backend/app/services/shipping_notice/document_candidate_persist.py 用途:阶段二——EML 附件派生 FileAsset、ShippingNoticeDocument / Candidate 幂等落库。 -依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、eml_parse。 +依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、客户影子识别、eml_parse。 逻辑:由 intake_parse_workflow.run_intake_parse 在文本落库成功后调用;重试按 (parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。 Document↔派生资产的引用计数仅在 asset_id 变更时 +1/-1; @@ -270,6 +270,11 @@ def _upsert_candidate( row.duplicate_resolved_at = None row.updated_at = datetime.utcnow() db.session.flush() + from app.services.shipping_notice.customer_shadow_resolution import ( + refresh_candidate_shadow_resolution_safely, + ) + + refresh_candidate_shadow_resolution_safely(row) return row diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 6cfbc55f..a8a89022 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -169,6 +169,7 @@ def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None: def _fill_pvmi_template(task: ShippingTask, path: Path) -> None: + """将业务号作为货代主引用写入 PVMI 模板,技术任务号仍用于系统追踪和文件名。""" wb = load_workbook(filename=str(path)) header_ws = wb[HEADER_SHEET] detail_ws = wb[DETAIL_SHEET] @@ -186,7 +187,8 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None: header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task) header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task) - header_ws.cell(DATA_START_ROW, 7).value = task.task_no + business_ref = task.shipping_case.business_no if task.shipping_case and task.shipping_case.business_no else task.task_no + header_ws.cell(DATA_START_ROW, 7).value = business_ref notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)] if not notice_lines: @@ -198,7 +200,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None: qty = line.get("qty") amount = line.get("amount") - detail_ws.cell(row_idx, 1).value = task.task_no + detail_ws.cell(row_idx, 1).value = business_ref detail_ws.cell(row_idx, 2).value = line_no detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line) detail_ws.cell(row_idx, 5).value = qty if qty is not None else "" @@ -224,6 +226,7 @@ def _row_values(task: ShippingTask, line: dict | None) -> list: def _fill_legacy_template(task: ShippingTask, path: Path) -> None: + """填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。""" wb = load_workbook(filename=str(path)) ws = wb.active lines = task.lines_json or [None] @@ -235,6 +238,7 @@ def _fill_legacy_template(task: ShippingTask, path: Path) -> None: def _fill_blank_workbook(task: ShippingTask, path: Path) -> None: + """生成无模板工作簿;技术任务号继续保留在导出文件名与系统记录中。""" wb = Workbook() ws = wb.active ws.title = "Shipment" diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index de3fe10f..a7e6e470 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -2,7 +2,7 @@ services/shipping_notice/fulfillment_workflow.py 用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。 -依赖:match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、tool_common、tool_response。 +依赖:customer_identity_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、tool_common、tool_response。 逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match。 """ @@ -40,6 +40,7 @@ from app.services.shipping_notice.rpa_attempts import ( upload_rpa_attempts, ) from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress from app.services.shipping_notice.tool_response import tool_response @@ -207,6 +208,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + customer_gate = customer_gate_tool_response(task, operation='match_inventory') + if customer_gate is not None: + return customer_gate + # [STEP 1] 先确认字段对齐与库存快照是否已经就绪。 # 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。 if awaiting_inventory_mapping_confirm(task): @@ -374,6 +379,10 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + customer_gate = customer_gate_tool_response(task, operation='generate_excel') + if customer_gate is not None: + return customer_gate + if not is_inventory_source_stable(task): return tool_response( status="failed", @@ -460,6 +469,10 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + customer_gate = customer_gate_tool_response(task, operation='upload_to_freight') + if customer_gate is not None: + return customer_gate + if not is_inventory_source_stable(task): return tool_response( status="failed", diff --git a/backend/app/services/shipping_notice/intake_business_parser.py b/backend/app/services/shipping_notice/intake_business_parser.py index fdecc945..9a405b8f 100644 --- a/backend/app/services/shipping_notice/intake_business_parser.py +++ b/backend/app/services/shipping_notice/intake_business_parser.py @@ -71,7 +71,6 @@ def parse_intake_business_summary( 'source_type': str(line.get('source_type') or '').strip() or None, 'customer_sku': str(line.get('customer_sku') or '').strip() or None, 'vendor_part_number': str(line.get('vendor_part_number') or '').strip() or None, - 'hub_code': str(line.get('hub_code') or '').strip() or None, } for line in lines if isinstance(line, dict) diff --git a/backend/app/services/shipping_notice/intake_service.py b/backend/app/services/shipping_notice/intake_service.py index dd4b51f4..37247fff 100644 --- a/backend/app/services/shipping_notice/intake_service.py +++ b/backend/app/services/shipping_notice/intake_service.py @@ -2,8 +2,8 @@ backend/app/services/shipping_notice/intake_service.py 用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。 -依赖:file_assets.service、intake_parse_workflow、jobs.queue、models、duplicate_detection、 - attachment_integrity。 +依赖:file_assets.service、intake_parse_workflow、order_extraction、jobs.queue、models、 + duplicate_detection、attachment_integrity。 逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行; 创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE; cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径); @@ -54,6 +54,30 @@ def _intake_ttl_hours() -> int: return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1) +def _expire_order_extractions_for_read( + *, + user_id: int, + intake_nos: list[str] | None = None, + conversation_id: str | None = None, +) -> int: + """ + 在 Intake 读取入口惰性回收订单识别超时状态。 + + 核心逻辑:委托 order_extraction 使用数据库快照和配置超时值完成带锁收口; + 读取接口无需依赖进程内定时器,服务重启后仍可恢复失败终态。 + + Returns: + 本次由 extracting 收口为 failed 的 Intake 数量。 + """ + from app.services.shipping_notice.order_extraction import expire_stale_order_extractions + + return expire_stale_order_extractions( + user_id=user_id, + intake_nos=intake_nos, + conversation_id=conversation_id, + ) + + def generate_intake_no() -> str: """生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。""" return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" @@ -230,6 +254,7 @@ def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake: def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]: """查询单个接入记录详情(含资产摘要与附件全文)。""" + _expire_order_extractions_for_read(user_id=user_id, intake_nos=[intake_no]) intake = get_intake_for_user(intake_no, user_id) asset = db.session.get(FileAsset, intake.asset_id) if not asset: @@ -387,6 +412,8 @@ def create_shipping_notice_intake( def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]: """列出会话下未消费的活跃接入记录,供页面恢复。""" + conv = str(conversation_id or '').strip() + _expire_order_extractions_for_read(user_id=user_id, conversation_id=conv or None) query = db.session.query(ShippingNoticeIntake, FileAsset).join( FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id ).filter( @@ -394,7 +421,6 @@ def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})), ShippingNoticeIntake.consumed_at.is_(None), ) - conv = str(conversation_id or '').strip() if conv: query = query.filter(ShippingNoticeIntake.conversation_id == conv) rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all() @@ -406,6 +432,7 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()] if not normalized: return [] + _expire_order_extractions_for_read(user_id=user_id, intake_nos=normalized) rows = ( db.session.query(ShippingNoticeIntake, FileAsset) .join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id) diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index f52bfbe0..87cdd8e9 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -232,7 +232,7 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship share_mode="task_only", line_count=0, source_code=source_code, - source_type=str(task.inventory_source_type or "").strip() or None, + source_type=str(task.inventory_connector_type or "").strip() or None, site_id=site_id, warehouse_id=warehouse_id, source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(), diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 67ae31b8..15b57610 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -2,7 +2,7 @@ services/shipping_notice/inventory_rpa_workflow.py 用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。 -依赖:rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、tool_common、state_machine、tool_response。 +依赖:customer_identity_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、tool_common、state_machine、tool_response。 逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory。 """ @@ -55,6 +55,10 @@ from app.services.shipping_notice.inventory_source_gate import ( task_needs_parse_review, ) from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source +from app.services.shipping_notice.customer_identity_gate import ( + assert_customer_identity_gate, + customer_gate_tool_response, +) from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source from app.services.shipping_notice.query_service import ( resolve_task_from_payload, @@ -157,7 +161,7 @@ def _try_reuse_inventory_snapshot( task, snapshot, reason="reuse_latest", - audit_payload={"mode": mode, "source_type": rpa_source.get("source_type")}, + audit_payload={"mode": mode, "connector_type": rpa_source.get("connector_type")}, ) if not link: return None @@ -695,8 +699,9 @@ def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) -> def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None: - """校验库存源门禁(skipped/failed/success 共用)。""" + """校验客户与库存源门禁(skipped/failed/success 共用)。""" try: + assert_customer_identity_gate(task, operation='rpa_inventory_callback') assert_inventory_source_gate(task, operation="rpa_inventory_callback") except AppError as exc: return tool_response( @@ -924,7 +929,7 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: "inventory_source_confirmed", { "source_code": task.inventory_source_code, - "source_type": task.inventory_source_type, + "connector_type": task.inventory_connector_type, "site_id": task.inventory_site_id, "warehouse_id": task.inventory_warehouse_id, "confirmed_by": confirmed_by or "integration_tool", @@ -989,6 +994,10 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response manual_retry_round = mode == "retry_rpa" + customer_gate = customer_gate_tool_response(task, operation='ensure_inventory_via_rpa') + if customer_gate is not None: + return customer_gate + # [STEP 0] 库存源须在订单解析阶段已确定;RPA 只读取独立字段。 try: assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa") diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index b189c217..ee60dc82 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -351,7 +351,7 @@ def create_inventory_snapshot_from_rpa( source_config_version=get_inventory_sources_config_version(), identity_status="pending" if success else "unknown", source_code=source_code or None, - source_type=str(source.get("source_type") or "").strip() or None, + source_type=str(source.get("connector_type") or "").strip() or None, snapshot_status=snapshot_status, exported_at=exported_at, expires_at=snapshot_expires_at(exported_at) if success else None, diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index 022e5ac2..682cd81f 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -61,13 +61,13 @@ def is_inventory_source_stable(task: ShippingTask) -> bool: code = str(task.inventory_source_code or "").strip().upper() if not code: return False - source_type = str(task.inventory_source_type or "").strip() - if not source_type: + connector_type = str(task.inventory_connector_type or "").strip() + if not connector_type: return False source = get_inventory_source(code) if not source: return False - if source_type != str(source.get("source_type") or "").strip(): + if connector_type != str(source.get("connector_type") or "").strip(): return False site_id = str(task.inventory_site_id or "").strip().upper() @@ -135,7 +135,7 @@ def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudic status=str(task.inventory_source_status or "").strip(), method=str(task.inventory_source_method or "").strip() or None, source_code=str(task.inventory_source_code or "").strip().upper() or None, - source_type=str(task.inventory_source_type or "").strip() or None, + connector_type=str(task.inventory_connector_type or "").strip() or None, site_id=str(task.inventory_site_id or "").strip().upper() or None, warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None, config_version=str(task.inventory_source_config_version or "").strip() or None, @@ -166,7 +166,7 @@ def apply_inventory_source_adjudication( if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: task.inventory_source_code = adjudication.source_code - task.inventory_source_type = adjudication.source_type + task.inventory_connector_type = adjudication.connector_type task.inventory_site_id = adjudication.site_id task.inventory_warehouse_id = adjudication.warehouse_id or None if adjudication.status == "user_confirmed" and confirmed_by_user_id: @@ -174,7 +174,7 @@ def apply_inventory_source_adjudication( task.inventory_source_confirmed_at = datetime.utcnow() elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES: task.inventory_source_code = None - task.inventory_source_type = None + task.inventory_connector_type = None task.inventory_site_id = None task.inventory_warehouse_id = None payload = dict(task.step_payload_json or {}) @@ -233,7 +233,7 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource status="user_confirmed", method="user_confirmed", source_code=adjudication.source_code, - source_type=adjudication.source_type, + connector_type=adjudication.connector_type, site_id=adjudication.site_id, warehouse_id=adjudication.warehouse_id, config_version=adjudication.config_version, diff --git a/backend/app/services/shipping_notice/inventory_source_identity.py b/backend/app/services/shipping_notice/inventory_source_identity.py index 2118f79b..34677086 100644 --- a/backend/app/services/shipping_notice/inventory_source_identity.py +++ b/backend/app/services/shipping_notice/inventory_source_identity.py @@ -31,7 +31,7 @@ class ResolvedInventoryIdentity: """稳定库存源四元组中的站点/库位解析结果。""" source_code: str - source_type: str + connector_type: str site_id: str warehouse_id: str @@ -84,7 +84,7 @@ def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) ok=True, identity=ResolvedInventoryIdentity( source_code=str(source.get("source_code") or "").strip().upper(), - source_type=str(source.get("source_type") or "").strip(), + connector_type=str(source.get("connector_type") or "").strip(), site_id=site_id, warehouse_id=matched[0], ), @@ -107,11 +107,11 @@ def resolve_inventory_source_identity( 核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。 """ source_code = str(source.get("source_code") or "").strip().upper() - source_type = str(source.get("source_type") or "").strip() - if not source_code or not source_type: + connector_type = str(source.get("connector_type") or "").strip() + if not source_code or not connector_type: return InventoryIdentityResolution(ok=False, reason="source_incomplete") - if source_type == "crane_footprint": + if connector_type == "crane_footprint": return _resolve_crane_warehouse_id(source, context) site_id = str(source.get("site_id") or "").strip().upper() @@ -122,7 +122,7 @@ def resolve_inventory_source_identity( ok=True, identity=ResolvedInventoryIdentity( source_code=source_code, - source_type=source_type, + connector_type=connector_type, site_id=site_id, warehouse_id=warehouse_id, ), @@ -145,8 +145,8 @@ def identity_matches_config( return False if cfg_site and task_site != cfg_site: return False - source_type = str(source.get("source_type") or "").strip() - if source_type == "crane_footprint": + connector_type = str(source.get("connector_type") or "").strip() + if connector_type == "crane_footprint": if context is None: return False resolution = resolve_inventory_source_identity(source, context) diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/inventory_source_rules.py index b6bff0b6..bb862aa4 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/inventory_source_rules.py @@ -2,8 +2,8 @@ services/shipping_notice/inventory_source_rules.py 用途:根据发货通知路由线索对库存源做确定性裁决。 -依赖:inventory_sources、ShippingTask 独立字段与 step_payload_json。 -逻辑:Dify/LLM 只提供路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。 +依赖:inventory_sources、ShippingTask 目的地字段、订单行 source_type 与 step_payload_json。 +逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。 """ from __future__ import annotations @@ -33,7 +33,7 @@ class InventorySourceAdjudication: status: str method: str | None = None source_code: str | None = None - source_type: str | None = None + connector_type: str | None = None site_id: str | None = None warehouse_id: str | None = None config_version: str | None = None @@ -103,7 +103,14 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None: def extract_destination_candidates(task: ShippingTask) -> list[str]: """ 从任务解析结果提取目的地/港口/仓库候选。 - 【AI 触发时机】:订单解析后由裁决服务调用,Dify 输出与后端字段都作为候选证据。 + 【AI 触发时机】:订单解析后由裁决服务调用,Dify 行级 source_type 与目的地字段都作为候选证据。 + + 核心逻辑:只读取 orders[].lines[].source_type,禁止使用 Task.source_type; + Task.source_type 表示 PDF/manual 等接入来源,不是库存源路由证据。 + Args: + task: 待裁决库存源的发货任务。 + Returns: + 去重并标准化后的 match_aliases 候选。 """ candidates: list[str] = [] payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} @@ -121,6 +128,7 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]: _extract_destination_object(candidates, line.get("destination")) for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"): _append_candidate(candidates, line.get(key)) + _append_candidate(candidates, line.get("source_type")) return candidates @@ -147,7 +155,7 @@ def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: st "display_name": source.get("display_name"), "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), - "source_type": source.get("source_type"), + "connector_type": source.get("connector_type"), "match_score": score, "matched_by": matched_by, } @@ -304,7 +312,7 @@ def _stable_from_source( status="resolved", method=method, source_code=identity.source_code, - source_type=identity.source_type, + connector_type=identity.connector_type, site_id=identity.site_id, warehouse_id=identity.warehouse_id, config_version=config_version, @@ -328,8 +336,8 @@ def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudicati for source in list_inventory_sources(): if _source_field_excluded(source, context): continue - source_type = str(source.get("source_type") or "").strip() - if source_type == "dsv360" and ( + connector_type = str(source.get("connector_type") or "").strip() + if connector_type == "dsv360" and ( not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip() ): @@ -440,7 +448,7 @@ def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> In conflicts=["source_code_not_found"], reason="source_code_not_found", ) - if str(source.get("source_type") or "").strip() == "dsv360" and ( + if str(source.get("connector_type") or "").strip() == "dsv360" and ( not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip() ): return InventorySourceAdjudication( @@ -471,7 +479,7 @@ def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> In status="user_confirmed", method="user_confirmed", source_code=identity.source_code, - source_type=identity.source_type, + connector_type=identity.connector_type, site_id=identity.site_id, warehouse_id=identity.warehouse_id, config_version=get_inventory_sources_config_version(), @@ -520,7 +528,7 @@ def save_task_rpa_inventory_source( status="user_confirmed", method="user_confirmed", source_code=identity.source_code, - source_type=identity.source_type, + connector_type=identity.connector_type, site_id=identity.site_id, warehouse_id=identity.warehouse_id, config_version=get_inventory_sources_config_version(), diff --git a/backend/app/services/shipping_notice/inventory_sources.py b/backend/app/services/shipping_notice/inventory_sources.py index 15a5297f..fa3ef7ef 100644 --- a/backend/app/services/shipping_notice/inventory_sources.py +++ b/backend/app/services/shipping_notice/inventory_sources.py @@ -16,7 +16,7 @@ from typing import Any import yaml from flask import current_app -_VALID_SOURCE_TYPES = { +_VALID_CONNECTOR_TYPES = { "dsv360": "dsv360", "crane_footprint": "crane_footprint", } @@ -31,7 +31,7 @@ def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]: match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} return { "source_code": source.get("source_code"), - "source_type": source.get("source_type"), + "connector_type": source.get("connector_type"), "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "warehouse_resolution": source.get("warehouse_resolution"), @@ -127,13 +127,13 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]: """ navigation = dict(source.get("navigation") or {}) query: dict[str, Any] = {} - source_type = str(source.get("source_type") or "").strip().lower() + connector_type = str(source.get("connector_type") or "").strip().lower() - if source_type == "dsv360": + if connector_type == "dsv360": for key in ("program_group", "program_label", "report_group", "report_name"): if navigation.get(key): query[key] = navigation[key] - elif source_type == "crane_footprint": + elif connector_type == "crane_footprint": if navigation.get("report_name"): query["report_name"] = navigation["report_name"] query["project_code"] = navigation.get("project_code") @@ -188,18 +188,20 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, raise InventorySourceConfigError(f"duplicate source_code: {source_code}") seen_codes.add(source_code) - source_type = str(raw.get("source_type") or "").strip().lower() - if source_type not in _VALID_SOURCE_TYPES: - raise InventorySourceConfigError(f"{source_code}: source_type must be dsv360 or crane_footprint") + connector_type = str(raw.get("connector_type") or "").strip().lower() + if connector_type not in _VALID_CONNECTOR_TYPES: + raise InventorySourceConfigError( + f"{source_code}: connector_type must be dsv360 or crane_footprint" + ) warehouse_id = str(raw.get("warehouse_id") or "").strip().upper() site_id = str(raw.get("site_id") or "").strip().upper() - if source_type == "dsv360": + if connector_type == "dsv360": if not site_id: raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360") if not warehouse_id: raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360") - elif source_type == "crane_footprint": + elif connector_type == "crane_footprint": if not site_id: raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint") aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()] @@ -234,7 +236,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, normalized = { "source_code": source_code, - "source_type": _VALID_SOURCE_TYPES[source_type], + "connector_type": _VALID_CONNECTOR_TYPES[connector_type], "site_id": site_id, "display_name": str(raw.get("display_name") or source_code).strip(), "enabled": bool(raw.get("enabled", True)), @@ -249,7 +251,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, if str(alias).strip() ], } - if source_type == "crane_footprint": + if connector_type == "crane_footprint": normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower() normalized["allowed_warehouse_ids"] = allowed_warehouse_ids match_cfg = raw.get("match") @@ -261,7 +263,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, "warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()], "aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()], } - if source_type == "crane_footprint" and raw.get("export"): + if connector_type == "crane_footprint" and raw.get("export"): normalized["export"] = dict(raw.get("export") or {}) normalized["query"] = _build_legacy_query(normalized) return normalized @@ -421,8 +423,8 @@ def merge_runtime_inventory_identity( query = dict(merged.get("query") or {}) query["warehouse_code"] = warehouse merged["query"] = query - source_type = str(merged.get("source_type") or "").strip() - if source_type == "crane_footprint": + connector_type = str(merged.get("connector_type") or "").strip() + if connector_type == "crane_footprint": navigation = dict(merged.get("navigation") or {}) navigation["project_code"] = warehouse merged["navigation"] = navigation diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 207ea47e..629cf3ba 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -2,7 +2,7 @@ services/shipping_notice/inventory_workflow.py 用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。 -依赖:inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine。 +依赖:customer_identity_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine。 逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain。 """ @@ -60,6 +60,7 @@ from app.services.shipping_notice.query_service import ( ) from app.services.shipping_notice.i18n import resolve_lang, t from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress @@ -126,6 +127,9 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: 库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。 核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。 """ + customer_gate = customer_gate_tool_response(task, operation=operation) + if customer_gate is not None: + return customer_gate if is_inventory_source_stable(task): return None try: @@ -590,6 +594,10 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) + customer_gate = customer_gate_tool_response(task, operation='ensure_inventory') + if customer_gate is not None: + return customer_gate + if not is_inventory_source_stable(task): try: assert_inventory_source_gate(task, operation="ensure_inventory") diff --git a/backend/app/services/shipping_notice/notice_line_constants.py b/backend/app/services/shipping_notice/notice_line_constants.py index 938efc26..fbd9b6d5 100644 --- a/backend/app/services/shipping_notice/notice_line_constants.py +++ b/backend/app/services/shipping_notice/notice_line_constants.py @@ -24,7 +24,6 @@ NOTICE_LINE_FIELDS = ( "allocation_id", "source_type", "customer_sku", - "hub_code", ) # 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格) @@ -126,10 +125,11 @@ NOTICE_COLUMN_MAP: dict[str, str] = { "Allocation ID": "allocation_id", "source type": "source_type", "Source Type": "source_type", - "Hub Code": "hub_code", - "Hub": "hub_code", - "HUB": "hub_code", - "hub_code": "hub_code", + # Hub Code 与 Source Type 在当前业务中是同一库存路由线索,统一归入 source_type。 + "Hub Code": "source_type", + "Hub": "source_type", + "HUB": "source_type", + "hub_code": "source_type", # 单位 "单位": "uom", "UOM": "uom", @@ -162,7 +162,6 @@ NOTICE_FIELD_LABELS = { "allocation_id": "Allocation ID", "source_type": "库存来源提示", "customer_sku": "客户料号 / HHPN", - "hub_code": "Hub Code / 枢纽代码", } HEADER_SKIP_TOKENS = { diff --git a/backend/app/services/shipping_notice/notice_line_table.py b/backend/app/services/shipping_notice/notice_line_table.py index 624f141f..0dfe59b7 100644 --- a/backend/app/services/shipping_notice/notice_line_table.py +++ b/backend/app/services/shipping_notice/notice_line_table.py @@ -27,15 +27,6 @@ from app.services.shipping_notice.reservation_id import ( ) -def _derive_hub_code(source_type: Any) -> str: - """避免循环依赖,在表格解析层从 VMI/DBS source type 提取 Hub Code。""" - import re - - text = re.sub(r"\s+", " ", str(source_type or "").strip().upper()) - match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text) - return match.group(1) if match else "" - - def parse_notice_row( row: list[Any] | tuple[Any, ...], columns: dict[str, int | None], @@ -138,17 +129,13 @@ def parse_notice_row( if vendor_part_number: parsed["vendor_part_number"] = vendor_part_number - for field in ("po_number", "allocation_id", "source_type", "customer_sku", "hub_code"): + for field in ("po_number", "allocation_id", "source_type", "customer_sku"): idx = columns.get(field) if idx is None: continue value = str(cell(row, idx) or "").strip() if value: parsed[field] = value - if not parsed.get("hub_code"): - hub_code = _derive_hub_code(parsed.get("source_type")) - if hub_code: - parsed["hub_code"] = hub_code if "amount" not in parsed and "unit_price" in parsed: computed = round(parsed["unit_price"] * qty, 4) diff --git a/backend/app/services/shipping_notice/notice_lines.py b/backend/app/services/shipping_notice/notice_lines.py index 69c81c7f..272db291 100644 --- a/backend/app/services/shipping_notice/notice_lines.py +++ b/backend/app/services/shipping_notice/notice_lines.py @@ -8,7 +8,6 @@ services/shipping_notice/notice_lines.py from __future__ import annotations -import re from typing import Any from app.services.shipping_notice.notice_line_constants import ( @@ -46,13 +45,6 @@ _map_notice_header = map_notice_header _parse_number = parse_number -def derive_hub_code(source_type: Any) -> str: - """从已知库存来源提示中派生 Hub Code,如 VMI-FRA01→FRA01、DBS DUB→DUB。""" - text = re.sub(r"\s+", " ", str(source_type or "").strip().upper()) - match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text) - return match.group(1) if match else "" - - def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: """ 标准化单条发货通知订单行。 @@ -153,20 +145,23 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: optional_aliases = { "po_number": ("po_number", "poNumber", "PO", "PO Number"), "allocation_id": ("allocation_id", "allocationId", "Allocation ID"), - "source_type": ("source_type", "sourceType", "Source Type"), + "source_type": ( + "source_type", + "sourceType", + "Source Type", + "hub_code", + "hubCode", + "Hub Code", + "Hub", + "HUB", + ), "customer_sku": ("customer_sku", "customerSku", "allocated_hhpn", "Allocated HHPN"), - "hub_code": ("hub_code", "hubCode", "Hub Code", "Hub", "HUB"), } for field, aliases in optional_aliases.items(): value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "") if value: line[field] = value - if not line.get("hub_code"): - hub_code = derive_hub_code(line.get("source_type")) - if hub_code: - line["hub_code"] = hub_code - remark = str(raw.get("remark") or raw.get("note") or "").strip() if remark: line["remark"] = remark @@ -466,7 +461,6 @@ __all__ = [ "enrich_notice_with_document_currency", "enrich_notice_with_document_required_date", "enrich_notice_with_document_reservation", - "derive_hub_code", "adjudicate_notice_lines", "normalize_notice_line", "normalize_notice_lines", diff --git a/backend/app/services/shipping_notice/open_existing_reservation_backfill.py b/backend/app/services/shipping_notice/open_existing_reservation_backfill.py new file mode 100644 index 00000000..e715df15 --- /dev/null +++ b/backend/app/services/shipping_notice/open_existing_reservation_backfill.py @@ -0,0 +1,216 @@ +""" +backend/app/services/shipping_notice/open_existing_reservation_backfill.py + +用途:在 exact_file/open_existing 场景下,将最新订单 Candidate 的合法 Reservation ID 安全回填旧任务。 +依赖:ShippingNoticeCandidate/ShippingTask、po_number、reservation_id、state_machine、tool_common。 +逻辑:batch_from_intakes 在消费 open_existing Candidate 前调用;本模块只处理尚未进入库存链的 rsv_req 任务, + 按 PO + SKU + Qty 唯一匹配空值订单行,重算 Reservation 门禁并写入任务审计。 +""" + +from __future__ import annotations + +from collections import Counter +from decimal import Decimal, InvalidOperation +from typing import Any + +from app.models import ShippingNoticeCandidate, ShippingTask +from app.services.shipping_notice.constants import PH_RSV_REQ +from app.services.shipping_notice.po_number import normalize_po_number +from app.services.shipping_notice.reservation_id import ( + is_valid_reservation_id, + validated_reservation_id, +) +from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition +from app.services.shipping_notice.tool_common import log_task_event + + +def _normalized_qty(value: Any) -> str: + """ + 将订单数量转换为稳定比较值。 + + Args: + value: Candidate 或 Task 订单行中的数量。 + Returns: + 去除无意义小数尾零后的十进制字符串;非法值返回空字符串。 + """ + try: + quantity = Decimal(str(value).strip()) + except (InvalidOperation, ValueError): + return "" + if quantity <= 0: + return "" + return format(quantity.normalize(), "f") + + +def _line_match_key(line: dict[str, Any]) -> tuple[str, str] | None: + """ + 生成 SKU + Qty 唯一匹配键。 + + Args: + line: 已标准化或历史任务订单行。 + Returns: + 大写 SKU 与规范数量组成的键;缺少任一字段时返回 None。 + """ + sku = str(line.get("sku") or "").strip().upper() + quantity = _normalized_qty(line.get("qty") if line.get("qty") is not None else line.get("quantity")) + return (sku, quantity) if sku and quantity else None + + +def _target_is_safe(task: ShippingTask) -> bool: + """ + 判断旧任务是否仍允许补充 Reservation。 + + 核心逻辑:只允许 pending_review + rsv_req,且库存、匹配、导出任一真相均未产生。 + Args: + task: exact_file 命中的旧任务。 + Returns: + 是否允许执行只补空值的回填。 + """ + return ( + str(task.process_status or "").strip() == "pending_review" + and str(task.pending_human_reason or "").strip() == PH_RSV_REQ + and not task.inventory_lines_json + and not task.inventory_snapshot_id + and not str(task.match_status or "").strip() + and not task.line_results_json + and not str(task.export_file_path or "").strip() + and not str(task.export_file_name or "").strip() + ) + + +def _reservation_gate_issues(lines: list[dict[str, Any]]) -> list[dict[str, Any]]: + """ + 重算订单行 Reservation ID 门禁。 + + Args: + lines: 回填后的旧任务订单行。 + Returns: + 缺失或格式非法的 Reservation 行级问题。 + """ + issues: list[dict[str, Any]] = [] + for index, line in enumerate(lines): + raw_value = str(line.get("reservation_id") or "").strip() + if is_valid_reservation_id(raw_value): + continue + issues.append( + { + "line_index": index, + "sku": str(line.get("sku") or "").strip(), + "field": "reservation_id", + "reason": "invalid_format" if raw_value else "missing", + "severity": "blocking", + "raw_value": raw_value, + } + ) + return issues + + +def backfill_exact_file_open_existing_reservations( + *, + task: ShippingTask, + candidate: ShippingNoticeCandidate, + candidate_summary: dict[str, Any], + duplicate_status: str, + duplicate_matches: list[dict[str, Any]], +) -> bool: + """ + 从 exact_file Candidate 安全补齐 open_existing 旧任务的 Reservation ID。 + + 核心逻辑:要求重复目标唯一、旧任务尚处 rsv_req 且未进入下游;PO 必须一致, + SKU + Qty 在新旧两侧都唯一且旧值为空时才回填。成功后仅重算 Reservation 门禁, + 即使门禁清除也继续停留在 parse_review,等待人工确认。 + Args: + task: open_existing 指向的旧任务。 + candidate: 当前最新订单 Candidate,用于审计定位。 + candidate_summary: 已通过 Candidate 校验的业务摘要。 + duplicate_status: 本次实时重复检测状态,必须为 exact_file。 + duplicate_matches: 本次实时重复目标列表,必须唯一命中当前 task。 + Returns: + 是否至少安全回填一条订单行。 + """ + matched_task_nos = { + str(item.get("task_no") or "").strip().upper() + for item in duplicate_matches + if str(item.get("task_no") or "").strip() + } + if ( + str(duplicate_status or "").strip() != "exact_file" + or matched_task_nos != {str(task.task_no or "").strip().upper()} + or not _target_is_safe(task) + ): + return False + + candidate_po = normalize_po_number(candidate_summary.get("po_number")) + task_po = normalize_po_number(task.po_number) + if not candidate_po or not task_po or candidate_po != task_po: + return False + + target_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)] + candidate_lines = [ + dict(item) + for item in (candidate_summary.get("lines") or []) + if isinstance(item, dict) + ] + target_keys = [_line_match_key(line) for line in target_lines] + candidate_keys = [_line_match_key(line) for line in candidate_lines] + target_counts = Counter(key for key in target_keys if key is not None) + candidate_counts = Counter(key for key in candidate_keys if key is not None) + + updated_indexes: list[int] = [] + reservation_by_key: dict[tuple[str, str], str] = {} + for line, key in zip(candidate_lines, candidate_keys, strict=True): + reservation_id = validated_reservation_id(line.get("reservation_id")) + if ( + key is not None + and reservation_id + and candidate_counts[key] == 1 + and target_counts[key] == 1 + ): + reservation_by_key[key] = reservation_id + + for index, (line, key) in enumerate(zip(target_lines, target_keys, strict=True)): + if key not in reservation_by_key or str(line.get("reservation_id") or "").strip(): + continue + line["reservation_id"] = reservation_by_key[key] + updated_indexes.append(index) + + if not updated_indexes: + return False + + # [STEP 1] 回填只写空 Reservation,不改变 PO/SKU/Qty 或库存源路由线索。 + task.lines_json = target_lines + issues = _reservation_gate_issues(target_lines) + step_payload = dict(task.step_payload_json or {}) + step_payload["parse_validation"] = { + "status": "needs_review" if issues else "ready", + "issues": issues, + "contract_version": "shipping-line-v1", + "resolution_source": "exact_file_candidate_backfill", + } + if issues: + step_payload["process_field_gate"] = { + "status": "needs_enrichment", + "missing_fields": ["reservation_id"], + "issues": issues, + "contract_version": "shipping-order-extraction-v1", + } + apply_task_transition(task, TaskTransition.RSV_REQUIRED) + else: + step_payload.pop("process_field_gate", None) + apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) + task.error_message = None + task.step_payload_json = step_payload + + # [STEP 2] 保留人工复核,并记录可追溯的 Candidate 与订单行索引。 + log_task_event( + task, + "reservation_backfilled_from_exact_file_candidate", + { + "candidate_no": candidate.candidate_no, + "duplicate_status": duplicate_status, + "updated_line_indexes": updated_indexes, + "remaining_issue_count": len(issues), + "review_preserved": True, + }, + ) + return True diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py index cecffb4a..29cb667d 100644 --- a/backend/app/services/shipping_notice/openapi_spec.py +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -72,7 +72,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: if not server.endswith("/api/shipping-notice"): server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice" - task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234") + task_id = _str_prop("发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501") batch_id = _str_prop("发货批次编号(batch id),如 SB-20260617-ABCD1234") runtime_context = _str_prop( "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改" @@ -89,7 +89,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。" "推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;" "模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。" - "submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source" + "submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source、confirm_customer" " 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。" "若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。" "如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响," @@ -159,8 +159,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "sku": _str_prop("SKU/料号"), "qty": {"type": "number", "exclusiveMinimum": 0}, "reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"), - "hub_code": _str_prop("可为空,缺失时 Task 停在补字段门禁"), - "source_type": _str_prop("可为空,缺失时 Task 停在补字段门禁"), + "source_type": _str_prop( + "可选订单路由线索;仅在原文有可靠证据时填写," + "不代表任务通知来源或已确认的库存连接器类型" + ), }, "additionalProperties": True, }, @@ -190,7 +192,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: required=["agent_runtime_context", "input_snapshot_hash", "schema_version", "orders"], description=( "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标," - "且无阻断冲突/修订决策时自动建单;Reservation ID、Hub Code、Source Type 允许缺失。" + "且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失," + "订单行 Source Type 是可选路由线索。" + "响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、" + "non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。" ), ), "/tools/parse_notice": _post_op( @@ -230,7 +235,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "line_index": _int_prop("行下标,从 0 开始"), "patch": { "type": "object", - "description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/hub_code/source_type", + "description": ( + "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type;" + "source_type 仅作为可选订单路由线索" + ), "additionalProperties": True, }, "comment": _str_prop("修改备注(可选)"), @@ -291,12 +299,25 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: }, required=["task_id", "source_code"], description=( - "库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id," + "库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id," "且 routing_fingerprint 与当前配置版本一致。" "Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。" "若返回 needs_human,说明身份未完整解析或需先完成解析确认。" ), ), + "/tools/confirm_customer": _post_op( + "confirm_customer", + "在客户人工检查点确认标准客户(仅提交 customer_id)", + { + "task_id": task_id, + "customer_id": _int_prop("用户从 HXOPS 标准客户列表中明确选择的客户 ID"), + }, + required=["task_id", "customer_id"], + description=( + "仅在 customer_review 检查点且用户已经明确选择标准客户后调用。" + "禁止根据邮件中的不稳定客户名称自行猜测 customer_id;客户确认成功后由 HXOPS 决定后续流程。" + ), + ), "/tools/submit_decision": _post_op( "submit_decision", "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。", @@ -332,13 +353,13 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: ), "/tools/get_task_status": _post_op( "get_task_status", - "查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构", + "查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构", { "task_id": task_id, "conversation_id": _str_prop("Dify 会话 ID"), }, description=( - "返回 inventory_source_code、inventory_source_type、inventory_site_id、" + "返回 inventory_source_code、inventory_connector_type、inventory_site_id、" "inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|" "user_confirmed|invalid|conflicted)、inventory_source_method、" "inventory_source_config_version、inventory_routing_fingerprint、" diff --git a/backend/app/services/shipping_notice/order_candidate_builder.py b/backend/app/services/shipping_notice/order_candidate_builder.py index 8a9eac1b..2765668c 100644 --- a/backend/app/services/shipping_notice/order_candidate_builder.py +++ b/backend/app/services/shipping_notice/order_candidate_builder.py @@ -17,7 +17,7 @@ from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.reservation_id import validated_reservation_id _PO_IN_FILENAME = re.compile(r"(? str: diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 4369e523..6304ee3e 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -1,17 +1,18 @@ """ backend/app/services/shipping_notice/order_extraction.py -用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重与自动建单。 +用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重、自动建单与失败收口。 依赖:agent_runtime_context、ChatSession、ShippingNoticeIntake/Document/Candidate、batch_from_intakes。 -逻辑:点击发送后 Dify 先读取不可变输入快照,再提交结构化订单;HXOPS 以会话用户为权限边界, - 逐订单落 Candidate,高置信度 SKU/Qty 订单自动消费建 Task,其余保留供自然对话修订。 +逻辑:聊天请求进入 Dify 前先登记本轮抽取身份,Dify 再读取不可变输入快照并提交结构化订单; + HXOPS 逐订单落 Candidate,高置信度 SKU/Qty 订单自动消费建 Task,其余保留供自然对话修订; + Dify 终态或状态读取负责把未提交和超时请求收口为失败。 """ from __future__ import annotations import hashlib import json -from datetime import datetime +from datetime import datetime, timedelta, timezone from typing import Any from flask import current_app @@ -20,6 +21,7 @@ from sqlalchemy.orm.attributes import flag_modified from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.models import ( + Agent, ChatSession, FileAsset, ShippingNoticeCandidate, @@ -50,6 +52,9 @@ _CONTEXT_PATHS = [ 'refs.contract_version', 'refs.intake_nos', ] +ORDER_EXTRACTION_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED' +ORDER_EXTRACTION_INCOMPLETE_MESSAGE = '订单识别流程未提交有效结果,请重新发送当前邮件。' +ORDER_EXTRACTION_TIMEOUT_MESSAGE = '订单识别超时,请重新发送当前邮件。' def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, list[str], str]: @@ -64,7 +69,18 @@ def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, l raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单抽取契约版本不匹配') session_id = str(values.get('platform.session_id') or '').strip() - session = ChatSession.query.filter_by(session_id=session_id).first() + request_id = str(values.get('platform.request_id') or '').strip() + if not session_id or not request_id: + raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单抽取请求缺少会话或请求标识') + session = ( + db.session.query(ChatSession) + .join(Agent, Agent.id == ChatSession.agent_id) + .filter( + ChatSession.session_id == session_id, + Agent.agent_code == 'shipping_notice', + ) + .first() + ) if session is None: raise NotFoundError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='聊天会话不存在') try: @@ -76,7 +92,7 @@ def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, l intake_nos = sorted({str(item or '').strip().upper() for item in raw_nos if str(item or '').strip()}) if not intake_nos: raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='未提供待解析 Intake') - return session, intake_nos, str(values.get('platform.request_id') or '').strip() + return session, intake_nos, request_id def _load_intakes( @@ -145,6 +161,428 @@ def _snapshot_hash(intakes: list[ShippingNoticeIntake], documents: list[Shipping return hashlib.sha256(raw.encode('utf-8')).hexdigest() +def _normalized_intake_nos(intake_nos: list[str]) -> list[str]: + """规范化并稳定排序 Intake 编号,供请求登记、失败收口和超时回收复用。""" + return sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()}) + + +def _order_extraction_snapshot(intake: ShippingNoticeIntake) -> dict[str, Any]: + """读取 Intake 当前抽取快照;旧数据或非法结构统一视为空快照。""" + structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} + snapshot = structured.get('order_extraction_snapshot') + return snapshot if isinstance(snapshot, dict) else {} + + +def _parse_snapshot_time(value: Any) -> datetime | None: + """将抽取快照时间转换为无时区 UTC,兼容 ISO `Z` 与带时区格式。""" + text = str(value or '').strip() + if not text: + return None + try: + parsed = datetime.fromisoformat(text.replace('Z', '+00:00')) + except ValueError: + return None + if parsed.tzinfo is not None: + parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None) + return parsed + + +def _set_documents_extraction_state( + *, + intake_ids: list[int], + status: str, + error_code: str | None, + error_message: str | None, + now: datetime, + only_extracting: bool, +) -> None: + """ + 同步本轮 Intake 下 Document 的订单抽取状态。 + + Args: + intake_ids: 已通过用户、会话与请求身份校验的 Intake 主键。 + status: 目标状态。 + error_code: 失败错误码;开始抽取时传 None。 + error_message: 用户可见错误说明;开始抽取时传 None。 + now: 本次状态更新时间。 + only_extracting: True 时只收口仍在 extracting 的 Document,禁止覆盖成功终态。 + """ + if not intake_ids: + return + query = db.session.query(ShippingNoticeDocument).filter( + ShippingNoticeDocument.intake_id.in_(intake_ids) + ) + if only_extracting: + query = query.filter(ShippingNoticeDocument.order_extraction_status == 'extracting') + for document in query.with_for_update().all(): + document.order_extraction_status = status + document.order_extraction_source = 'dify_chatflow' + document.order_extraction_version = EXTRACTION_CONTRACT_VERSION + document.order_extraction_error_code = error_code + document.order_extraction_error_message = error_message + document.updated_at = now + + +def start_order_extraction( + *, + user_id: int, + session_id: str, + intake_nos: list[str], + request_id: str, +) -> int: + """ + 在请求进入 Dify 前登记权威订单抽取状态。 + + 核心逻辑:锁定当前用户和会话的完整 Intake 集合;同一 request 重入不刷新超时起点, + 新 request 则覆盖旧快照身份,使旧 terminal 无法把新一轮抽取收口为失败。 + + Args: + user_id: 当前聊天用户主键。 + session_id: HXOPS 本地会话号,必须与 Intake 绑定会话一致。 + intake_nos: 本轮完整 Intake 编号集合。 + request_id: 本轮 HXOPS 请求号,不得为空。 + + Returns: + 本轮进入 extracting 的 Intake 数量;同一请求重复登记仍返回完整数量。 + + Raises: + ValidationError: 请求身份或 Intake 集合为空。 + NotFoundError: Intake 集合不完整。 + ConflictError: Intake 尚未预处理完成、已消费或绑定其他会话。 + """ + normalized = _normalized_intake_nos(intake_nos) + session_value = str(session_id or '').strip() + request_value = str(request_id or '').strip() + if not normalized or not session_value or not request_value: + raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单识别请求上下文不完整') + + intakes = ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.intake_no.in_(normalized), + ) + .order_by(ShippingNoticeIntake.id.asc()) + .with_for_update() + .all() + ) + if {row.intake_no for row in intakes} != set(normalized): + db.session.rollback() + raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在') + now = datetime.utcnow() + intake_ids: list[int] = [] + for intake in intakes: + if intake.parse_status != 'parsed' or intake.consumed_at is not None: + db.session.rollback() + raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理') + if intake.conversation_id and intake.conversation_id != session_value: + db.session.rollback() + raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话') + intake.conversation_id = session_value + previous = _order_extraction_snapshot(intake) + same_request = ( + intake.order_extraction_status == 'extracting' + and str(previous.get('request_id') or '') == request_value + and str(previous.get('session_id') or '') == session_value + ) + structured = dict(intake.structured_result_json or {}) + next_snapshot = dict(previous) if same_request else {} + structured['order_extraction_snapshot'] = { + **next_snapshot, + 'request_id': request_value, + 'session_id': session_value, + 'created_at': previous.get('created_at') if same_request and previous.get('created_at') else now.isoformat(), + } + intake.structured_result_json = structured + flag_modified(intake, 'structured_result_json') + intake.order_extraction_status = 'extracting' + intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION + intake.order_extraction_error_code = None + intake.order_extraction_error_message = None + intake.updated_at = now + intake_ids.append(int(intake.id)) + _set_documents_extraction_state( + intake_ids=intake_ids, + status='extracting', + error_code=None, + error_message=None, + now=now, + only_extracting=False, + ) + db.session.commit() + return len(intakes) + + +def finalize_order_extraction_failure( + *, + user_id: int, + session_id: str, + intake_nos: list[str], + request_id: str, + error_code: str = ORDER_EXTRACTION_FAILED_CODE, + error_message: str = ORDER_EXTRACTION_INCOMPLETE_MESSAGE, +) -> int: + """ + 将当前请求仍未提交的订单抽取幂等收口为失败。 + + 核心逻辑:先验证用户、会话与完整 Intake 集合,再逐条匹配快照 request/session; + 只允许 extracting 转 failed,因此成功结果、部分完成结果和新请求均不会被旧 terminal 覆盖。 + + Args: + user_id: 当前聊天用户主键。 + session_id: 当前 HXOPS 会话号。 + intake_nos: 当前请求携带的完整 Intake 集合。 + request_id: 当前 HXOPS 请求号。 + error_code: 稳定业务错误码,最长 64 字符。 + error_message: 用户可见错误说明,不得包含密钥或堆栈。 + + Returns: + 实际由 extracting 更新为 failed 的 Intake 数量;重复调用或旧请求返回 0。 + """ + normalized = _normalized_intake_nos(intake_nos) + session_value = str(session_id or '').strip() + request_value = str(request_id or '').strip() + if not normalized or not session_value or not request_value: + return 0 + intakes = ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.intake_no.in_(normalized), + ) + .order_by(ShippingNoticeIntake.id.asc()) + .with_for_update() + .all() + ) + if {row.intake_no for row in intakes} != set(normalized): + db.session.rollback() + return 0 + now = datetime.utcnow() + code = str(error_code or ORDER_EXTRACTION_FAILED_CODE).strip()[:64] + message = str(error_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE).strip()[:2000] + failed_ids: list[int] = [] + for intake in intakes: + snapshot = _order_extraction_snapshot(intake) + if ( + intake.order_extraction_status != 'extracting' + or intake.conversation_id != session_value + or str(snapshot.get('request_id') or '') != request_value + or str(snapshot.get('session_id') or '') != session_value + ): + continue + intake.order_extraction_status = 'failed' + intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION + intake.order_extraction_error_code = code + intake.order_extraction_error_message = message + intake.updated_at = now + failed_ids.append(int(intake.id)) + _set_documents_extraction_state( + intake_ids=failed_ids, + status='failed', + error_code=code, + error_message=message, + now=now, + only_extracting=True, + ) + db.session.commit() + return len(failed_ids) + + +def expire_stale_order_extractions( + *, + user_id: int, + intake_nos: list[str] | None = None, + conversation_id: str | None = None, + timeout_seconds: int | None = None, + now: datetime | None = None, +) -> int: + """ + 在 Intake 状态读取时惰性回收超时订单抽取。 + + 核心逻辑:锁定当前用户仍为 extracting 的记录,优先使用快照 created_at,旧数据回退 updated_at; + 只更新超时记录及其仍在 extracting 的 Documents,不依赖进程内定时器。 + + Args: + user_id: 当前用户主键。 + intake_nos: 可选 Intake 范围;批量状态接口应传入请求集合。 + conversation_id: 可选会话范围;会话恢复接口应传入当前会话。 + timeout_seconds: 可选覆盖值,默认读取应用配置,最小为 1 秒。 + now: 测试使用的 UTC 当前时间;生产不传。 + + Returns: + 实际回收为 failed 的 Intake 数量。 + """ + configured = timeout_seconds + if configured is None: + configured = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS') or 300) + timeout = max(int(configured), 1) + current_time = now or datetime.utcnow() + if current_time.tzinfo is not None: + current_time = current_time.astimezone(timezone.utc).replace(tzinfo=None) + query = db.session.query(ShippingNoticeIntake).filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.order_extraction_status == 'extracting', + ) + normalized = _normalized_intake_nos(intake_nos or []) + if intake_nos is not None: + if not normalized: + return 0 + query = query.filter(ShippingNoticeIntake.intake_no.in_(normalized)) + conversation_value = str(conversation_id or '').strip() + if conversation_value: + query = query.filter(ShippingNoticeIntake.conversation_id == conversation_value) + + expired_ids: list[int] = [] + for intake in query.order_by(ShippingNoticeIntake.id.asc()).with_for_update().all(): + snapshot = _order_extraction_snapshot(intake) + started_at = _parse_snapshot_time(snapshot.get('created_at')) or intake.updated_at + if started_at is None or current_time - started_at < timedelta(seconds=timeout): + continue + intake.order_extraction_status = 'failed' + intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION + intake.order_extraction_error_code = ORDER_EXTRACTION_FAILED_CODE + intake.order_extraction_error_message = ORDER_EXTRACTION_TIMEOUT_MESSAGE + intake.updated_at = current_time + expired_ids.append(int(intake.id)) + _set_documents_extraction_state( + intake_ids=expired_ids, + status='failed', + error_code=ORDER_EXTRACTION_FAILED_CODE, + error_message=ORDER_EXTRACTION_TIMEOUT_MESSAGE, + now=current_time, + only_extracting=True, + ) + # 查询使用 FOR UPDATE;即使没有超时记录也提交只读事务,避免状态接口序列化期间继续持锁。 + db.session.commit() + return len(expired_ids) + + +def get_order_extraction_state( + *, + user_id: int, + session_id: str, + intake_nos: list[str], + request_id: str, +) -> dict[str, Any]: + """ + 读取当前订单抽取请求可用于聊天展示的权威聚合状态。 + + 核心逻辑:按用户、会话、完整 Intake 集合和 snapshot request_id 做四重围栏; + 处理中只返回不确定进度,终态从已持久化的 submission.result 读取真实建单计数。 + + Args: + user_id: 当前聊天用户主键。 + session_id: HXOPS 本地会话号。 + intake_nos: 本轮完整 Intake 编号集合。 + request_id: 本轮 HXOPS 请求号。 + + Returns: + 包含 status、phase、message、真实结果计数、batch_no 与 terminal 的状态字典。 + + Raises: + ValidationError: 请求身份不完整。 + NotFoundError: Intake 集合不存在或不完整。 + ConflictError: Intake 不属于当前会话或已被更新请求取代。 + """ + normalized = _normalized_intake_nos(intake_nos) + session_value = str(session_id or '').strip() + request_value = str(request_id or '').strip() + if int(user_id or 0) <= 0 or not normalized or not session_value or not request_value: + raise ValidationError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', + message='订单识别请求上下文不完整', + ) + + intakes = ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.intake_no.in_(normalized), + ) + .order_by(ShippingNoticeIntake.id.asc()) + .all() + ) + if {row.intake_no for row in intakes} != set(normalized): + raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在') + + for intake in intakes: + snapshot = _order_extraction_snapshot(intake) + if ( + intake.conversation_id != session_value + or str(snapshot.get('session_id') or '') != session_value + or str(snapshot.get('request_id') or '') != request_value + ): + raise ConflictError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', + message='订单识别请求已失效或已被更新请求取代', + ) + + statuses = {str(row.order_extraction_status or '').strip() for row in intakes} + if 'extracting' in statuses: + status = 'extracting' + elif statuses == {'failed'}: + status = 'failed' + elif 'partially_completed' in statuses or 'failed' in statuses: + status = 'partially_completed' + elif statuses == {'completed'}: + status = 'completed' + else: + raise ConflictError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', + message='订单识别尚未进入可展示状态', + ) + + result: dict[str, Any] = {} + for intake in intakes: + structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {} + submission = structured.get('order_extraction_submission') + if not isinstance(submission, dict) or str(submission.get('request_id') or '') != request_value: + continue + candidate = submission.get('result') + if isinstance(candidate, dict): + result = candidate + break + + if status == 'extracting': + message = '正在识别邮件及附件中的订单' + phase = 'llm_extraction' + elif status == 'failed': + message = next( + ( + str(row.order_extraction_error_message or '').strip() + for row in intakes + if str(row.order_extraction_error_message or '').strip() + ), + '订单识别失败,请重新发送当前邮件。', + ) + phase = 'failed' + else: + message = str(result.get('message') or '').strip() + if not message: + message = '部分订单已处理,仍需补充或确认。' if status == 'partially_completed' else '订单识别完成。' + phase = 'result_persisted' + + def _count(key: str) -> int: + """将 Tool 结果计数约束为非负整数,异常值按 0 展示。""" + try: + return max(int(result.get(key) or 0), 0) + except (TypeError, ValueError): + return 0 + + return { + 'status': status, + 'phase': phase, + 'message': message, + 'created_count': _count('created_count'), + 'opened_existing_count': _count('opened_existing_count'), + 'pending_count': _count('pending_count'), + 'non_shipping_count': _count('non_shipping_count'), + 'created_with_missing_fields_count': _count('created_with_missing_fields_count'), + 'batch_no': str(result.get('batch_no') or '').strip() or None, + 'terminal': status != 'extracting', + } + + def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]: """ 返回现有 Chatflow 完整理解邮件所需的 Intake/Document 上下文。 @@ -160,6 +598,21 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]: """ session, intake_nos, request_id = _runtime_identity(payload.get('agent_runtime_context')) intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True) + for intake in intakes: + previous_snapshot = _order_extraction_snapshot(intake) + if ( + intake.order_extraction_status == 'extracting' + and previous_snapshot.get('request_id') + and ( + str(previous_snapshot.get('request_id') or '') != request_id + or str(previous_snapshot.get('session_id') or '') != session.session_id + ) + ): + db.session.rollback() + raise ConflictError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', + message='已有更新的订单识别请求正在处理,当前旧请求已失效', + ) documents = _load_documents(intakes, lock=False) if not documents: raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', message='未找到可供订单抽取的邮件正文或附件') @@ -193,11 +646,19 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]: now = datetime.utcnow() for intake in intakes: structured = dict(intake.structured_result_json or {}) + previous_snapshot = _order_extraction_snapshot(intake) structured['order_extraction_snapshot'] = { + **previous_snapshot, 'hash': snapshot, 'request_id': request_id, 'session_id': session.session_id, - 'created_at': now.isoformat(), + 'created_at': ( + previous_snapshot.get('created_at') + if str(previous_snapshot.get('request_id') or '') == request_id + and str(previous_snapshot.get('session_id') or '') == session.session_id + and previous_snapshot.get('created_at') + else now.isoformat() + ), } intake.structured_result_json = structured flag_modified(intake, 'structured_result_json') @@ -206,6 +667,14 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]: intake.order_extraction_error_code = None intake.order_extraction_error_message = None intake.updated_at = now + _set_documents_extraction_state( + intake_ids=[int(row.id) for row in intakes], + status='extracting', + error_code=None, + error_message=None, + now=now, + only_extracting=False, + ) db.session.commit() return { 'status': 'ok', @@ -221,7 +690,9 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]: 'schema_version': EXTRACTION_CONTRACT_VERSION, 'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'], 'auto_create_required_line_fields': ['sku', 'qty'], - 'allowed_missing_process_fields': ['reservation_id', 'hub_code', 'source_type'], + 'required_process_line_fields': ['reservation_id'], + 'optional_routing_line_fields': ['source_type'], + 'allowed_missing_process_fields': ['reservation_id'], }, } @@ -265,6 +736,39 @@ def _evidence_has_sku_qty(order: dict[str, Any]) -> bool: return any('sku' in field for field in fields) and any('qty' in field or 'quantity' in field for field in fields) +def _build_submission_message( + *, + created_count: int, + opened_existing_count: int, + pending_count: int, + non_shipping_count: int, + created_with_missing_fields_count: int, +) -> str: + """按持久化结果生成确定性摘要,禁止把 Candidate 数量描述为已建任务数量。""" + if not created_count and not opened_existing_count and not pending_count: + if non_shipping_count: + return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。' + return '未识别到发货订单,本次未创建任务。' + + parts: list[str] = [] + if created_count: + parts.append(f'已创建 {created_count} 个发货任务') + if opened_existing_count: + parts.append(f'已打开 {opened_existing_count} 个已有任务') + if pending_count: + prefix = '另有' if parts else '有' + parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突') + if non_shipping_count: + parts.append(f'已忽略 {non_shipping_count} 项非发货内容') + message = ';'.join(parts) + '。' + if created_with_missing_fields_count: + message += ( + f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,' + '可通过自然对话补充。' + ) + return message + + def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: """ 提交 Chatflow 的 orders[],执行后端强校验、订单级判重与自动建单。 @@ -290,6 +794,16 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='订单数量超过限制') intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True, allow_consumed=True) + if any( + str(_order_extraction_snapshot(intake).get('request_id') or '') != request_id + or str(_order_extraction_snapshot(intake).get('session_id') or '') != session.session_id + for intake in intakes + ): + db.session.rollback() + raise ConflictError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', + message='订单识别请求已被更新请求替代,请重新读取上下文', + ) documents = _load_documents(intakes, lock=True) current_snapshot = _snapshot_hash(intakes, documents) supplied_snapshot = str(payload.get('input_snapshot_hash') or '').strip().lower() @@ -303,6 +817,12 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: replay_results = [] break stored_result = submission.get('result') + submission_request_id = submission.get('request_id') + if not submission_request_id and isinstance(stored_result, dict): + submission_request_id = stored_result.get('request_id') + if str(submission_request_id or '') != request_id: + replay_results = [] + break if isinstance(stored_result, dict): replay_results.append(stored_result) if len(replay_results) == len(intakes): @@ -324,11 +844,13 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: field_threshold = float(current_app.config.get('SHIPPING_NOTICE_ORDER_FIELD_CONFIDENCE') or 0.90) auto_candidates: list[ShippingNoticeCandidate] = [] pending: list[dict[str, Any]] = [] + non_shipping: list[dict[str, Any]] = [] duplicate_results_by_intake: dict[int, list[dict[str, Any]]] = {} active_keys_by_intake: dict[int, set[str]] = {int(row.id): set() for row in intakes} pending_by_intake: dict[int, list[dict[str, Any]]] = {int(row.id): [] for row in intakes} document_candidate_keys: dict[int, list[str]] = {int(row.id): [] for row in documents} 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( @@ -356,6 +878,28 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: pending_item = {'order_index': index, 'source_intake_no': intake_no, 'reasons': ['primary_document_not_found']} pending.append(pending_item) pending_by_intake[int(intake.id)].append(pending_item) + for owned_document in owned_docs: + document_has_pending[int(owned_document.id)] = True + continue + + classification_confidence = _float(raw_order.get('classification_confidence')) + classification = str(raw_order.get('classification') or '').strip().lower() + conflicts = [item for item in (raw_order.get('conflicts') or []) if isinstance(item, dict)] + blocking_conflicts = [item for item in conflicts if str(item.get('severity') or 'blocking') == 'blocking'] + if ( + classification == 'non_shipping_request' + and classification_confidence >= class_threshold + and not blocking_conflicts + ): + # [STEP 1A] 明确的非发货内容只保留提交审计,不生成无法被消费的待处理 Candidate。 + non_shipping_item = { + 'order_index': index, + 'source_intake_no': intake_no, + 'primary_document_id': int(document.id), + 'classification_confidence': classification_confidence, + } + non_shipping.append(non_shipping_item) + document_non_shipping_indexes[int(document.id)].append(index) continue summary = dict(raw_order) @@ -368,13 +912,9 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: summary.pop('primary_document_id', None) assessment = assess_candidate_business_summary(summary) normalized = assessment['normalized_summary'] - classification_confidence = _float(raw_order.get('classification_confidence')) field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {} sku_conf = _float(field_confidence.get('sku')) qty_conf = _float(field_confidence.get('qty')) - classification = str(raw_order.get('classification') or '').strip().lower() - conflicts = [item for item in (raw_order.get('conflicts') or []) if isinstance(item, dict)] - blocking_conflicts = [item for item in conflicts if str(item.get('severity') or 'blocking') == 'blocking'] reasons: list[str] = [] if classification != 'shipping_request': reasons.append('not_shipping_request') @@ -481,18 +1021,26 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: pending.append(pending_item) pending_by_intake[int(intake.id)].append(pending_item) - # [STEP 2] 聚合 Document 结果,避免同一附件多订单时后一个 Candidate 覆盖前一个审计记录。 + # [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。 + has_unassigned_pending = any(not item.get('source_intake_no') for item in pending) for document in documents: keys = document_candidate_keys[int(document.id)] - document.order_extraction_status = 'partially_completed' if document_has_pending[int(document.id)] else 'completed' + document.order_extraction_status = ( + 'partially_completed' + if document_has_pending[int(document.id)] or has_unassigned_pending + else 'completed' + ) document.order_extraction_source = 'dify_chatflow' document.order_extraction_version = EXTRACTION_CONTRACT_VERSION - document.order_extraction_result_json = {'request_id': request_id, 'candidate_keys': keys} + document.order_extraction_result_json = { + 'request_id': request_id, + 'candidate_keys': keys, + 'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)], + } document.order_extraction_error_code = None document.order_extraction_error_message = None # [STEP 3] 清理同一抽取版本中消失、且尚未消费的旧 Candidate。 - has_unassigned_pending = any(not item.get('source_intake_no') for item in pending) for intake in intakes: active_keys = active_keys_by_intake[int(intake.id)] stale = db.session.query(ShippingNoticeCandidate).filter( @@ -531,7 +1079,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: create_idempotency_key=idem, ) else: - # [STEP 4] 没有待处理订单且 LLM 明确返回 0 单时,本次 Intake 已完成但不会产生 Batch/Task。 + # [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。 if not pending: now = datetime.utcnow() for intake in intakes: @@ -543,21 +1091,42 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: create_data = (create_result or {}).get('data') create_data = create_data if isinstance(create_data, dict) else {} + created = list(create_data.get('tasks') or []) + opened_existing = list( + (create_result or {}).get('opened_existing') + or create_data.get('opened_existing') + or [] + ) + created_count = len(created) + opened_existing_count = len(opened_existing) + created_with_missing_fields_count = sum( + 1 + for candidate in auto_candidates + if candidate.duplicate_resolution != 'open_existing' and candidate.missing_fields_json + ) + # 下层响应缺失任务明细属于契约异常;摘要只能陈述已持久化并返回的 Task,不能回退到 Candidate 数。 + created_with_missing_fields_count = min(created_with_missing_fields_count, created_count) result = { 'status': 'ok', 'request_id': request_id, 'batch_no': create_result.get('batch_no') if create_result else None, - 'created': list(create_data.get('tasks') or []), - 'opened_existing': list( - (create_result or {}).get('opened_existing') - or create_data.get('opened_existing') - or [] - ), + 'created': created, + 'opened_existing': opened_existing, 'pending_orders': pending, - 'auto_created_count': len(auto_candidate_nos), + 'non_shipping_orders': non_shipping, + 'created_count': created_count, + 'opened_existing_count': opened_existing_count, 'pending_count': len(pending), - 'message': ( - f"已自动处理 {len(auto_candidate_nos)} 份发货订单,另有 {len(pending)} 份需要补充或确认。" + 'non_shipping_count': len(non_shipping), + 'created_with_missing_fields_count': created_with_missing_fields_count, + # 兼容旧 Dify 节点;新节点应改读 created_count。 + 'auto_created_count': created_count, + 'message': _build_submission_message( + created_count=created_count, + opened_existing_count=opened_existing_count, + pending_count=len(pending), + non_shipping_count=len(non_shipping), + created_with_missing_fields_count=created_with_missing_fields_count, ), } # [STEP 5] 保存 Tool 级幂等回放结果,防止 Dify 网络重试重复建单。 @@ -566,6 +1135,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: structured['order_extraction_submission'] = { 'input_snapshot_hash': current_snapshot, 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'request_id': request_id, 'result': result, 'submitted_at': datetime.utcnow().isoformat(), } diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index db783bd9..802ed489 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -2,7 +2,7 @@ services/shipping_notice/progress_workflow.py 用途:承接发货通知任务的自动推进流程,包括解析确认检查、库存准备、字段映射确认与履约侧串联。 -依赖:tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。 +依赖:customer_identity_gate、tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。 逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。 """ @@ -37,6 +37,7 @@ from app.services.shipping_notice.query_service import resolve_task_from_payload from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled, set_task_step_progress from app.services.shipping_notice.tool_response import tool_response +from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: @@ -108,6 +109,10 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: stop_agent_turn=True, ) + customer_gate = customer_gate_tool_response(task, operation='auto_progress') + if customer_gate is not None: + return customer_gate + if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task): adjudication = ensure_inventory_source_review_state(task) db.session.commit() diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 4a0b3f98..e71b7e18 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -2,7 +2,7 @@ services/shipping_notice/query_service.py 用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。 -依赖:models.ShippingBatch、ShippingTask、ShippingTaskEvent。 +依赖:models.ShippingBatch、ShippingCase、ShippingTask、ShippingTaskEvent。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉; SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*。 @@ -18,11 +18,18 @@ from typing import Any from sqlalchemy import asc, desc from app import db -from app.models import ShippingBatch, ShippingTask +from app.models import ( + ShippingBatch, + ShippingCase, + ShippingNoticeCandidate, + ShippingNoticeIntake, + ShippingTask, +) EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" _TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE) +_BUSINESS_NO_RE = re.compile(r"(? list[ShippingTask]: def get_task_by_ref(task_ref: str) -> ShippingTask | None: - """按 task_no 或数字主键查找任务(Tool API / 内部引用解析)。""" + """按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。""" value = str(task_ref or "").strip() if not value: return None task = ShippingTask.query.filter_by(task_no=value).first() if task: return task + case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first() + if case is not None: + visited: set[int] = set() + while case.id not in visited: + visited.add(int(case.id)) + replacement = ( + db.session.query(ShippingCase) + .filter_by(replaces_case_id=case.id) + .order_by(ShippingCase.id.desc()) + .first() + ) + if replacement is None: + break + case = replacement + return ( + db.session.query(ShippingTask) + .filter_by(shipping_case_id=case.id) + .order_by(ShippingTask.document_version.desc(), ShippingTask.id.desc()) + .first() + ) if value.isdigit(): return db.session.get(ShippingTask, int(value)) return None @@ -81,6 +108,71 @@ def get_batch_by_no(batch_no: str) -> ShippingBatch | None: return ShippingBatch.query.filter_by(batch_no=value).first() +def resolve_order_extraction_ui_target( + *, + user_id: int, + conversation_id: str, + intake_nos: list[str], +) -> tuple[ShippingBatch | None, ShippingTask | None]: + """ + 按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。 + + 核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时, + 再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。 + + Args: + user_id: 当前聊天用户 ID。 + conversation_id: 当前 HXOPS ChatSession.session_id。 + intake_nos: 本轮 agent_runtime_context.refs.intake_nos。 + Returns: + `(batch, task)`;新建批次时 batch 非空,只有 open_existing 时 task 非空。 + """ + normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()}) + session_id = str(conversation_id or '').strip() + if not normalized or not session_id: + return None, None + + intakes = ( + db.session.query(ShippingNoticeIntake) + .filter( + ShippingNoticeIntake.user_id == int(user_id), + ShippingNoticeIntake.conversation_id == session_id, + ShippingNoticeIntake.intake_no.in_(normalized), + ) + .order_by(ShippingNoticeIntake.id.asc()) + .all() + ) + if {item.intake_no for item in intakes} != set(normalized): + return None, None + + batch_ids = [int(item.consumed_batch_id) for item in intakes if item.consumed_batch_id is not None] + if batch_ids: + batch = ( + db.session.query(ShippingBatch) + .filter( + ShippingBatch.id.in_(batch_ids), + ShippingBatch.user_id == int(user_id), + ShippingBatch.conversation_id == session_id, + ) + .order_by(ShippingBatch.created_at.desc(), ShippingBatch.id.desc()) + .first() + ) + if batch is not None: + return batch, None + + task = ( + db.session.query(ShippingTask) + .join(ShippingNoticeCandidate, ShippingNoticeCandidate.consumed_task_id == ShippingTask.id) + .filter( + ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]), + ShippingTask.user_id == int(user_id), + ) + .order_by(ShippingNoticeCandidate.id.asc(), ShippingTask.id.asc()) + .first() + ) + return None, task + + def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None: """查找属于指定批次的任务;批次不存在或任务不在批次内时返回 None。""" batch = get_batch_by_no(batch_no) @@ -197,8 +289,9 @@ def compute_conversation_workspace_summary(batches: list[ShippingBatch]) -> dict def extract_task_no_from_text(text: str) -> str | None: - """从自然语言文本中提取 SN- 任务编号。""" - match = _TASK_NO_RE.search(str(text or "")) + """从自然语言文本中提取 SN 技术号或客户业务号。""" + raw = str(text or "") + match = _TASK_NO_RE.search(raw) or _BUSINESS_NO_RE.search(raw) return match.group(0).upper() if match else None @@ -253,6 +346,9 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]: step_payload = task.step_payload_json or {} payload: dict[str, Any] = { "task_no": task.task_no, + "shipping_case_id": task.shipping_case_id, + "case_no": task.shipping_case.case_no if task.shipping_case else None, + "business_no": task.shipping_case.business_no if task.shipping_case else None, "process_status": task.process_status, "current_step": task.current_step, "review_status": task.review_status, @@ -260,6 +356,11 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]: "pending_human_reason": task.pending_human_reason, "customer_name": task.customer_name, "customer_code": task.customer_code, + "customer_resolution_status": task.customer_resolution_status, + "customer_resolution_method": task.customer_resolution_method, + "customer_id": task.shipping_case.customer_id if task.shipping_case else None, + "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, + "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, "ship_to": task.ship_to, "po_number": task.po_number, "required_date": task.required_date, @@ -343,6 +444,9 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, data = { "id": task.id, "task_no": task.task_no, + "shipping_case_id": task.shipping_case_id, + "case_no": task.shipping_case.case_no if task.shipping_case else None, + "business_no": task.shipping_case.business_no if task.shipping_case else None, "batch_no": _task_batch_no(task), "source_type": task.source_type, "source_file_name": task.source_file_name, @@ -350,6 +454,11 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, "batch_index": task.batch_index, "batch_total": task.batch_total, "customer_name": task.customer_name, + "customer_resolution_status": task.customer_resolution_status, + "customer_resolution_method": task.customer_resolution_method, + "customer_id": task.shipping_case.customer_id if task.shipping_case else None, + "customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None, + "customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None, "current_step": task.current_step, "process_status": task.process_status, "review_status": task.review_status, @@ -371,7 +480,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, "destination_country": task.destination_country, "warehouse_hint": task.warehouse_hint, "inventory_source_code": task.inventory_source_code, - "inventory_source_type": task.inventory_source_type, + "inventory_connector_type": task.inventory_connector_type, "inventory_site_id": task.inventory_site_id, "inventory_warehouse_id": task.inventory_warehouse_id, "inventory_source_status": task.inventory_source_status, diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index 187e8d4a..b6a7c482 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -131,7 +131,7 @@ def write_inventory_export_batch_trigger( continue inventory_sources.append({ "source_code": source.get("source_code"), - "source_type": source.get("source_type"), + "connector_type": source.get("connector_type"), "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "entry_url": source.get("entry_url"), diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 2d98ffc2..73384730 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -24,6 +24,7 @@ from app.services.shipping_notice.constants import ( CP_EXPORT_GENERATED, CP_INVENTORY_PENDING, CP_INVENTORY_SOURCE_REVIEW, + CP_CUSTOMER_REVIEW, CP_MAP_INFER, CP_PARSE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED, @@ -75,6 +76,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = { "rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"}, "retry_rpa": {"label": "重新获取库存", "message": "重新获取库存", "variant": "secondary"}, "confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"}, + "confirm_customer": {"label": "确认客户", "message": "选择并确认标准客户", "variant": "primary"}, "retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"}, "refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"}, "upload_inventory_file": { @@ -110,6 +112,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = { # checkpoint id → default human option ids (HTTP / Dify before task reload) CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = { CP_PARSE_REVIEW: ("confirm", "reject", "reparse"), + CP_CUSTOMER_REVIEW: ("confirm_customer",), CP_ALIGN_REVIEW: ( "confirm_inventory_mapping", "correct_inventory_mapping", @@ -275,8 +278,32 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: if task.process_status == "rejected" or task.review_status == "rejected": return TaskUiState(checkpoint=CP_REJECTED, human_options=[]) - # [STEP 2] RPA 库存耗尽与解析后待库存 — 正向流程中的「下一步」节点。 - if task.pending_human_reason == PH_RPA_EXHAUSTED: + # [STEP 2] 先完成订单解析复核,再暴露客户确认节点。 + reason = task.pending_human_reason + if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ: + return TaskUiState( + checkpoint=CP_RSV_REQ, + human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]), + ) + if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW: + return TaskUiState( + checkpoint=CP_PARSE_REVIEW, + human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]), + ) + if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: + return TaskUiState( + checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, + human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]), + ) + + if task.shipping_case_id is not None and task.customer_resolution_status != "confirmed": + return TaskUiState( + checkpoint=CP_CUSTOMER_REVIEW, + human_options=list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]), + ) + + # [STEP 3] 客户确认后,才进入库存和履约节点。 + if reason == PH_RPA_EXHAUSTED: return TaskUiState( checkpoint=CP_UPLOAD_REQ, human_options=upload_req_options_for_task(task), @@ -306,7 +333,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]), ) - # [STEP 3] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。 + # [STEP 4] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。 if task.process_status == "matched": if task.export_file_path: return TaskUiState( @@ -318,8 +345,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]), ) - # [STEP 4] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。 - reason = task.pending_human_reason + # [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。 if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW: return TaskUiState( checkpoint=CP_ALIGN_REVIEW, @@ -330,11 +356,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: checkpoint=CP_MAP_INFER, human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]), ) - if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ: - return TaskUiState( - checkpoint=CP_RSV_REQ, - human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]), - ) if reason == PH_INV_UNAVAIL: return TaskUiState( checkpoint=CP_UPLOAD_REQ, @@ -350,16 +371,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: checkpoint=RS_SHORTAGE_REVIEW, human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]), ) - if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW: - return TaskUiState( - checkpoint=CP_PARSE_REVIEW, - human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]), - ) - if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: - return TaskUiState( - checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, - human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]), - ) if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed": return TaskUiState( checkpoint=CP_UPLOAD_FAILED, diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index be4d7780..b180e9a4 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -67,6 +67,7 @@ from app.services.shipping_notice.batch_create_idempotency import ( handle_batch_create_integrity_error, normalize_create_idempotency_key, ) +from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task from app.services.shipping_notice.tool_common import ( auto_progress_enabled, defer_parse_to_dify_enabled, @@ -83,7 +84,6 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({ "quantity", "required_date", "uom", - "hub_code", "source_type", }) @@ -167,22 +167,17 @@ def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]: return missing -def _missing_process_field_issues( - lines: list[Any], - *, - require_order_extraction_routing: bool, -) -> list[dict[str, Any]]: +def _missing_process_field_issues(lines: list[Any]) -> list[dict[str, Any]]: """ 检查 Task 进入库存链前必须补齐的订单行流程字段。 - 核心逻辑:所有入口继续检查 Reservation ID;仅本期完整订单抽取契约额外检查 Source Type 与 Hub Code, - 避免把新协议强行扩散到历史手工 parse_notice 调用。 + 核心逻辑:所有入口只检查 Reservation ID;行级 Source Type 是可选库存源路由线索, + Hub Code 不属于新订单抽取契约,也不参与流程门禁。 Args: lines: 已标准化的订单行。 - require_order_extraction_routing: 是否启用 v1 订单抽取的 Source Type/Hub Code 门禁。 Returns: - 每个缺失字段对应的结构化 issue,包含行号、SKU、field 与原因。 + 每个缺失或格式非法 Reservation ID 对应的结构化 issue。 """ issues: list[dict[str, Any]] = [] for index, line in enumerate(lines): @@ -190,29 +185,16 @@ def _missing_process_field_issues( continue sku = str(line.get('sku') or '').strip() raw_reservation = str(line.get('reservation_id') or '').strip() - field_values = { - 'reservation_id': raw_reservation if is_valid_reservation_id(raw_reservation) else None, - } - if require_order_extraction_routing: - field_values.update({ - 'source_type': str(line.get('source_type') or '').strip() or None, - 'hub_code': str(line.get('hub_code') or '').strip() or None, - }) - for field, value in field_values.items(): - if value: - continue - issues.append({ - 'line_index': index, - 'sku': sku, - 'field': field, - 'reason': ( - 'invalid_format' - if field == 'reservation_id' and raw_reservation - else 'missing' - ), - 'severity': 'blocking', - 'raw_value': str(line.get(field) or '').strip(), - }) + if is_valid_reservation_id(raw_reservation): + continue + issues.append({ + 'line_index': index, + 'sku': sku, + 'field': 'reservation_id', + 'reason': 'invalid_format' if raw_reservation else 'missing', + 'severity': 'blocking', + 'raw_value': raw_reservation, + }) return issues @@ -416,8 +398,15 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: if not isinstance(item, dict): continue content_hash = str(item.get("source_content_hash") or "").strip().lower() or None + resolution_type = str(item.get("duplicate_resolution_type") or "normal").strip() or "normal" + shipping_case = resolve_shipping_case_for_new_task( + supersedes_task_id=item.get("supersedes_task_id"), + duplicate_resolution_type=resolution_type, + created_by_id=payload.get("user_id"), + ) task = ShippingTask( task_no=generate_task_no(), + shipping_case_id=shipping_case.id, batch_id=batch.id, user_id=payload.get("user_id"), conversation_id=str(payload.get("conversation_id") or "").strip() or None, @@ -436,10 +425,16 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]: supersedes_task_id=item.get("supersedes_task_id"), duplicate_source_task_id=item.get("duplicate_source_task_id"), duplicate_override_reason=str(item.get("duplicate_override_reason") or "").strip() or None, - duplicate_resolution_type=str(item.get("duplicate_resolution_type") or "normal").strip() or "normal", + duplicate_resolution_type=resolution_type, batch_index=idx, batch_total=total, raw_content=str(item.get("raw_text") or "").strip() or None, + customer_resolution_status=( + 'confirmed' if shipping_case.customer_id is not None else 'pending' + ), + customer_resolution_method=( + 'inherited' if shipping_case.customer_id is not None else None + ), process_status="created", ) db.session.add(task) @@ -582,8 +577,10 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: batch = _create_single_task_batch(payload) db.session.flush() + shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id")) task = ShippingTask( task_no=generate_task_no(), + shipping_case_id=shipping_case.id, batch_id=batch.id, user_id=payload.get("user_id"), conversation_id=str(payload.get("conversation_id") or "").strip() or None, @@ -591,6 +588,12 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: batch_index=1, batch_total=1, raw_content=str(payload.get("raw_content") or "").strip() or None, + customer_resolution_status=( + 'confirmed' if shipping_case.customer_id is not None else 'pending' + ), + customer_resolution_method=( + 'inherited' if shipping_case.customer_id is not None else None + ), process_status="created", ) db.session.add(task) @@ -640,8 +643,10 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: ): batch = _create_single_task_batch(payload) db.session.flush() + shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id")) new_task = ShippingTask( task_no=generate_task_no(), + shipping_case_id=shipping_case.id, batch_id=batch.id, user_id=payload.get("user_id"), conversation_id=conv_id or None, @@ -649,6 +654,12 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: batch_index=1, batch_total=1, raw_content=None, + customer_resolution_status=( + 'confirmed' if shipping_case.customer_id is not None else 'pending' + ), + customer_resolution_method=( + 'inherited' if shipping_case.customer_id is not None else None + ), process_status="created", ) db.session.add(new_task) @@ -739,24 +750,12 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: } # [STEP 3] 流程字段是后续库存匹配硬前置;允许 Task 创建,但缺失时停在字段补充门禁。 - require_order_extraction_routing = ( - isinstance(structured, dict) - and structured.get('_order_extraction_contract') == 'shipping-order-extraction-v1' - ) - process_field_issues = _missing_process_field_issues( - lines, - require_order_extraction_routing=require_order_extraction_routing, - ) + process_field_issues = _missing_process_field_issues(lines) if process_field_issues: - missing_reservation = [item for item in process_field_issues if item.get('field') == 'reservation_id'] - missing_fields = sorted({str(item.get('field') or '') for item in process_field_issues if item.get('field')}) - only_reservation_missing = missing_fields == ['reservation_id'] + missing_reservation = list(process_field_issues) + missing_fields = ['reservation_id'] apply_task_transition(task, TaskTransition.RSV_REQUIRED) - task.error_message = ( - "解析失败:未识别到 Reservation ID / COM ID(预定单号)" - if only_reservation_missing - else f"订单已创建,但缺少后续处理必需字段:{', '.join(missing_fields)}" - ) + task.error_message = "解析失败:未识别到 Reservation ID / COM ID(预定单号)" step_payload = dict(task.step_payload_json or {}) step_payload['process_field_gate'] = { 'status': 'needs_enrichment', @@ -774,7 +773,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: progress_percent=100, current=max(0, len(lines) - len({int(item['line_index']) for item in process_field_issues})), total=len(lines), - detail="可直接通过自然对话补充 Reservation ID、Source Type 或 Hub Code;补齐前不会进入库存流程。", + detail="可直接通过自然对话补充 Reservation ID;补齐前不会进入库存流程。", extra={ "warnings": warnings, "missing_reservation": missing_reservation[:5], @@ -797,8 +796,6 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: message=( "解析失败:未识别到 Reservation ID / COM ID(预定单号)," "当前任务无法继续匹配库存。请重新上传包含该字段的通知,或重新解析后补充预定单号。" - if only_reservation_missing - else f"订单任务已创建,但缺少 {', '.join(missing_fields)};请通过自然对话补齐后继续。" ), data={**serialize_task_for_tool(task), "missing_reservation": detail}, checkpoint=CP_RSV_REQ, @@ -1158,15 +1155,7 @@ def _commit_notice_edit( ) -> dict[str, Any]: # [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。 step_payload = dict(task.step_payload_json or {}) - existing_gate = step_payload.get('process_field_gate') - require_order_extraction_routing = ( - isinstance(existing_gate, dict) - and existing_gate.get('contract_version') == 'shipping-order-extraction-v1' - ) - validation_issues = _missing_process_field_issues( - list(task.lines_json or []), - require_order_extraction_routing=require_order_extraction_routing, - ) + validation_issues = _missing_process_field_issues(list(task.lines_json or [])) step_payload["parse_validation"] = { "status": "needs_review" if validation_issues else "ready", "issues": validation_issues, @@ -1179,11 +1168,7 @@ def _commit_notice_edit( 'status': 'needs_enrichment', 'missing_fields': missing_fields, 'issues': validation_issues, - 'contract_version': ( - 'shipping-order-extraction-v1' - if require_order_extraction_routing - else 'shipping-line-v1' - ), + 'contract_version': 'shipping-order-extraction-v1', } else: step_payload.pop('process_field_gate', None) diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 292e1854..60ea2eaf 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -2,7 +2,7 @@ services/shipping_notice/tools.py 用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。 -依赖:task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow;order_extraction 延迟导入以避免建批循环依赖。 +依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow;order_extraction 延迟导入以避免建批循环依赖。 逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。 """ @@ -14,6 +14,7 @@ from app.services.shipping_notice import ( inventory_workflow, task_workflow, ) +from app.services.shipping_notice import customer_identity_gate def get_order_extraction_context(payload: dict): @@ -60,6 +61,7 @@ update_notice_fields = task_workflow.update_notice_fields update_notice_line = task_workflow.update_notice_line add_notice_line = task_workflow.add_notice_line remove_notice_line = task_workflow.remove_notice_line +confirm_customer = customer_identity_gate.confirm_customer # 库存阶段 ensure_inventory = inventory_workflow.ensure_inventory diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml index 9d21a02b..81af62d1 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/shipping_inventory_sources.yaml @@ -7,7 +7,7 @@ sources: - source_code: DSV360_AWSBI_BYAWSATL01 display_name: DSV 360 / Bison / AWSBI / BYAWSATL01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI warehouse_id: BYAWSATL01 entry_url: https://s360.dbschenker.com/ @@ -28,7 +28,7 @@ sources: - ATL01 - source_code: DSV360_AWSBI_BYAWSAVP01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSAVP01 warehouse_id: BYAWSAVP01 @@ -49,7 +49,7 @@ sources: - BYAWSAVP01 - source_code: DSV360_AWSBI_BYAWSAZA01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSAZA01 warehouse_id: BYAWSAZA01 @@ -70,7 +70,7 @@ sources: - BYAWSAZA01 - source_code: DSV360_AWSBI_BYAWSCMH01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSCMH01 warehouse_id: BYAWSCMH01 @@ -92,7 +92,7 @@ sources: - CMH - source_code: DSV360_AWSBI_BYAWSCMN01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSCMN01 warehouse_id: BYAWSCMN01 @@ -114,7 +114,7 @@ sources: - CMN - source_code: DSV360_AWSBI_BYAWSEZE01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSEZE01 warehouse_id: BYAWSEZE01 @@ -136,7 +136,7 @@ sources: - EZE - source_code: DSV360_AWSBI_BYAWSFRA01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSFRA01 warehouse_id: BYAWSFRA01 @@ -157,7 +157,7 @@ sources: - BYAWSFRA01 - source_code: DSV360_AWSBI_BYAWSGRU01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSGRU01 warehouse_id: BYAWSGRU01 @@ -178,7 +178,7 @@ sources: - BYAWSGRU01 - source_code: DSV360_AWSBI_BYAWSIAD01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSIAD01 warehouse_id: BYAWSIAD01 @@ -199,7 +199,7 @@ sources: - BYAWSIAD01 - source_code: DSV360_AWSBI_BYAWSJAN01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSJAN01 warehouse_id: BYAWSJAN01 @@ -220,7 +220,7 @@ sources: - BYAWSJAN01 - source_code: DSV360_AWSBI_BYAWSLTN01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSLTN01 warehouse_id: BYAWSLTN01 @@ -241,7 +241,7 @@ sources: - BYAWSLTN01 - source_code: DSV360_AWSBI_BYAWSMEL01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSMEL01 warehouse_id: BYAWSMEL01 @@ -262,7 +262,7 @@ sources: - BYAWSMEL01 - source_code: DSV360_AWSBI_BYAWSNRT01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSNRT01 warehouse_id: BYAWSNRT01 @@ -283,7 +283,7 @@ sources: - BYAWSNRT01 - source_code: DSV360_AWSBI_BYAWSPHX01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPHX01 warehouse_id: BYAWSPHX01 @@ -304,7 +304,7 @@ sources: - BYAWSPHX01 - source_code: DSV360_AWSBI_BYAWSPNE01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPNE01 warehouse_id: BYAWSPNE01 @@ -325,7 +325,7 @@ sources: - BYAWSPNE01 - source_code: DSV360_AWSBI_BYAWSPRD01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPRD01 warehouse_id: BYAWSPRD01 @@ -346,7 +346,7 @@ sources: - BYAWSPRD01 - source_code: DSV360_AWSBI_BYAWSPSC01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPSC01 warehouse_id: BYAWSPSC01 @@ -367,7 +367,7 @@ sources: - BYAWSPSC01 - source_code: DSV360_AWSBI_BYAWSQRO01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSQRO01 warehouse_id: BYAWSQRO01 @@ -388,7 +388,7 @@ sources: - BYAWSQRO01 - source_code: DSV360_AWSBI_BYAWSRIC01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSRIC01 warehouse_id: BYAWSRIC01 @@ -409,7 +409,7 @@ sources: - BYAWSRIC01 - source_code: DSV360_AWSBI_BYAWSRNO01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSRNO01 warehouse_id: BYAWSRNO01 @@ -430,7 +430,7 @@ sources: - BYAWSRNO01 - source_code: DSV360_AWSBI_BYAWSRUH01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSRUH01 warehouse_id: BYAWSRUH01 @@ -451,7 +451,7 @@ sources: - BYAWSRUH01 - source_code: DSV360_AWSBI_BYAWSSBN01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSSBN01 warehouse_id: BYAWSSBN01 @@ -472,7 +472,7 @@ sources: - BYAWSSBN01 - source_code: DSV360_AWSBI_BYAWSSCL01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSSCL01 warehouse_id: BYAWSSCL01 @@ -493,7 +493,7 @@ sources: - BYAWSSCL01 - source_code: DSV360_AWSBI_BYAWSYYZ01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSYYZ01 warehouse_id: BYAWSYYZ01 @@ -514,7 +514,7 @@ sources: - BYAWSYYZ01 - source_code: DSV360_AWSBI_BYAWSZAZ01 enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSZAZ01 warehouse_id: BYAWSZAZ01 @@ -535,7 +535,7 @@ sources: - BYAWSZAZ01 - source_code: DSV360_AWSCV enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSCV warehouse_id: AWSCV display_name: DSV 360 / Cincinnati / AWSCV @@ -551,7 +551,7 @@ sources: - AWSCV - source_code: DSV360_AWSDU enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSDU warehouse_id: AWSDU display_name: DSV 360 / Dublin / AWSDU - Prod (JDA) @@ -567,7 +567,7 @@ sources: - DUBLIN - source_code: DSV360_AWSAMS enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSAMS warehouse_id: RTM display_name: DSV 360 / Moerdijk / AWSAMS @@ -595,7 +595,7 @@ sources: - AWSAMS - source_code: DSV360_AWSSL enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSSL warehouse_id: AWSSL display_name: DSV 360 / Salt Lake City / AWSSL @@ -611,7 +611,7 @@ sources: - SALTLAKECITY - source_code: DSV360_AWSSG enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSSG warehouse_id: AWSSG display_name: DSV 360 / Singapore / AWSSG - Prod (JDA) @@ -628,7 +628,7 @@ sources: - VMI-SIN - source_code: CRANE enabled: true - source_type: crane_footprint + connector_type: crane_footprint site_id: CRANE warehouse_resolution: alias_match display_name: Crane FootPrint diff --git a/backend/migrations/versions/a2c3d4e5f6a7_shipping_customer_imports.py b/backend/migrations/versions/a2c3d4e5f6a7_shipping_customer_imports.py new file mode 100644 index 00000000..0be7d297 --- /dev/null +++ b/backend/migrations/versions/a2c3d4e5f6a7_shipping_customer_imports.py @@ -0,0 +1,108 @@ +""" +用途:增加客户外部来源键、期初导入批次与导入行暂存表。 +依赖:Alembic revision f1a2b3c4d5e6。 +逻辑:导入文件仅保存哈希和逐行结果;发布后正式客户仍由 shipping_customers 作为真相源。 + +Revision ID: a2c3d4e5f6a7 +Revises: f1a2b3c4d5e6 +Create Date: 2026-07-15 13:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'a2c3d4e5f6a7' +down_revision = 'f1a2b3c4d5e6' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建客户来源映射与期初导入暂存结构。""" + op.create_table( + 'shipping_customer_external_refs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=False), + sa.Column('source_system', sa.String(length=64), nullable=False), + sa.Column('legacy_customer_key', sa.String(length=128), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('source_system', 'legacy_customer_key', name='uq_shipping_customer_external_refs_source_key'), + ) + op.create_index('ix_shipping_customer_external_refs_customer_id', 'shipping_customer_external_refs', ['customer_id'], unique=False) + + op.create_table( + 'shipping_customer_import_batches', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('batch_no', sa.String(length=64), nullable=False), + sa.Column('file_name', sa.String(length=255), nullable=False), + sa.Column('file_hash', sa.String(length=64), nullable=False), + sa.Column('file_size', sa.Integer(), nullable=False), + sa.Column('source_system', sa.String(length=64), nullable=False), + sa.Column('status', sa.String(length=32), server_default='validated', nullable=False), + sa.Column('total_rows', sa.Integer(), server_default='0', nullable=False), + sa.Column('valid_rows', sa.Integer(), server_default='0', nullable=False), + sa.Column('warning_rows', sa.Integer(), server_default='0', nullable=False), + sa.Column('error_rows', sa.Integer(), server_default='0', nullable=False), + sa.Column('published_rows', sa.Integer(), server_default='0', nullable=False), + sa.Column('uploaded_by_id', sa.Integer(), nullable=True), + sa.Column('published_by_id', sa.Integer(), nullable=True), + sa.Column('published_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['published_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['uploaded_by_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('batch_no'), + sa.UniqueConstraint('file_hash', 'source_system', name='uq_shipping_customer_import_batches_hash_source'), + ) + op.create_index('ix_shipping_customer_import_batches_created_at', 'shipping_customer_import_batches', ['created_at'], unique=False) + op.create_index('ix_shipping_customer_import_batches_status_created', 'shipping_customer_import_batches', ['status', 'created_at'], unique=False) + + op.create_table( + 'shipping_customer_import_rows', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('batch_id', sa.Integer(), nullable=False), + sa.Column('sheet_name', sa.String(length=32), nullable=False), + sa.Column('row_no', sa.Integer(), nullable=False), + sa.Column('row_order', sa.Integer(), nullable=False), + sa.Column('row_type', sa.String(length=32), nullable=False), + sa.Column('legacy_customer_key', sa.String(length=128), nullable=True), + sa.Column('raw_json', sa.JSON(), nullable=False), + sa.Column('normalized_json', sa.JSON(), nullable=False), + sa.Column('validation_status', sa.String(length=32), nullable=False), + sa.Column('errors_json', sa.JSON(), nullable=False), + sa.Column('warnings_json', sa.JSON(), nullable=False), + sa.Column('suggested_action', sa.String(length=32), nullable=True), + sa.Column('decision_action', sa.String(length=32), nullable=True), + sa.Column('target_customer_id', sa.Integer(), nullable=True), + sa.Column('decision_note', sa.Text(), nullable=True), + sa.Column('result_customer_id', sa.Integer(), nullable=True), + sa.Column('result_status', sa.String(length=32), nullable=True), + sa.Column('result_message', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['batch_id'], ['shipping_customer_import_batches.id']), + sa.ForeignKeyConstraint(['result_customer_id'], ['shipping_customers.id']), + sa.ForeignKeyConstraint(['target_customer_id'], ['shipping_customers.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('batch_id', 'sheet_name', 'row_no', name='uq_shipping_customer_import_rows_location'), + ) + op.create_index('ix_shipping_customer_import_rows_batch_id', 'shipping_customer_import_rows', ['batch_id'], unique=False) + op.create_index('ix_shipping_customer_import_rows_batch_status', 'shipping_customer_import_rows', ['batch_id', 'validation_status'], unique=False) + + +def downgrade() -> None: + """移除期初客户导入暂存结构与来源映射。""" + op.drop_index('ix_shipping_customer_import_rows_batch_status', table_name='shipping_customer_import_rows') + op.drop_index('ix_shipping_customer_import_rows_batch_id', table_name='shipping_customer_import_rows') + op.drop_table('shipping_customer_import_rows') + op.drop_index('ix_shipping_customer_import_batches_status_created', table_name='shipping_customer_import_batches') + op.drop_index('ix_shipping_customer_import_batches_created_at', table_name='shipping_customer_import_batches') + op.drop_table('shipping_customer_import_batches') + op.drop_index('ix_shipping_customer_external_refs_customer_id', table_name='shipping_customer_external_refs') + op.drop_table('shipping_customer_external_refs') diff --git a/backend/migrations/versions/b3d4e5f6a7b8_shipping_customer_shadow_resolution.py b/backend/migrations/versions/b3d4e5f6a7b8_shipping_customer_shadow_resolution.py new file mode 100644 index 00000000..414d3ff2 --- /dev/null +++ b/backend/migrations/versions/b3d4e5f6a7b8_shipping_customer_shadow_resolution.py @@ -0,0 +1,66 @@ +""" +用途:增加客户影子识别结果与人工标签表。 +依赖:Alembic revision a2c3d4e5f6a7。 +逻辑:每个订单 Candidate 保存一条可重算影子结果;不增加业务单客户外键或 Gate。 + +Revision ID: b3d4e5f6a7b8 +Revises: a2c3d4e5f6a7 +Create Date: 2026-07-15 16:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'b3d4e5f6a7b8' +down_revision = 'a2c3d4e5f6a7' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建客户影子识别审计表。""" + op.create_table( + 'shipping_customer_shadow_resolutions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('candidate_id', sa.Integer(), nullable=False), + sa.Column('intake_id', sa.Integer(), nullable=False), + sa.Column('resolution_version', sa.String(length=32), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False), + sa.Column('evidence_json', sa.JSON(), nullable=False), + sa.Column('candidate_matches_json', sa.JSON(), nullable=False), + sa.Column('top_customer_id', sa.Integer(), nullable=True), + sa.Column('top_score', sa.Float(), nullable=True), + sa.Column('manual_customer_id', sa.Integer(), nullable=True), + sa.Column('labeled_by_id', sa.Integer(), nullable=True), + sa.Column('labeled_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['candidate_id'], ['shipping_notice_candidates.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['intake_id'], ['shipping_notice_intakes.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['top_customer_id'], ['shipping_customers.id']), + sa.ForeignKeyConstraint(['manual_customer_id'], ['shipping_customers.id']), + sa.ForeignKeyConstraint(['labeled_by_id'], ['users.id']), + sa.CheckConstraint( + "status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed')", + name='ck_shipping_customer_shadow_status', + ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('candidate_id'), + ) + op.create_index('ix_shipping_customer_shadow_resolutions_intake_id', 'shipping_customer_shadow_resolutions', ['intake_id']) + op.create_index('ix_shipping_customer_shadow_resolutions_status', 'shipping_customer_shadow_resolutions', ['status']) + op.create_index('ix_shipping_customer_shadow_status_created', 'shipping_customer_shadow_resolutions', ['status', 'created_at']) + op.create_index('ix_shipping_customer_shadow_labeled_created', 'shipping_customer_shadow_resolutions', ['manual_customer_id', 'created_at']) + op.create_index('ix_shipping_customer_shadow_resolutions_created_at', 'shipping_customer_shadow_resolutions', ['created_at']) + + +def downgrade() -> None: + """移除客户影子识别审计表。""" + op.drop_index('ix_shipping_customer_shadow_resolutions_created_at', table_name='shipping_customer_shadow_resolutions') + op.drop_index('ix_shipping_customer_shadow_labeled_created', table_name='shipping_customer_shadow_resolutions') + op.drop_index('ix_shipping_customer_shadow_status_created', table_name='shipping_customer_shadow_resolutions') + op.drop_index('ix_shipping_customer_shadow_resolutions_status', table_name='shipping_customer_shadow_resolutions') + op.drop_index('ix_shipping_customer_shadow_resolutions_intake_id', table_name='shipping_customer_shadow_resolutions') + op.drop_table('shipping_customer_shadow_resolutions') diff --git a/backend/migrations/versions/c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type.py b/backend/migrations/versions/c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type.py new file mode 100644 index 00000000..e1bd4fd4 --- /dev/null +++ b/backend/migrations/versions/c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type.py @@ -0,0 +1,43 @@ +""" +backend/migrations/versions/c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type.py + +用途:将 shipping_tasks 库存连接器类型列改名为 inventory_connector_type。 +依赖:Alembic、SQLAlchemy;承接当前迁移 head b3d4e5f6a7b8。 +逻辑:仅重命名列并保留原数据;降级时恢复旧列名,不改历史迁移。 + +Revision ID: c4d5e6f7a8b9 +Revises: b3d4e5f6a7b8 +Create Date: 2026-07-16 02:10:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = "c4d5e6f7a8b9" +down_revision = "b3d4e5f6a7b8" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """重命名库存连接器类型列,并原样保留已有任务数据。""" + op.alter_column( + "shipping_tasks", + "inventory_source_type", + new_column_name="inventory_connector_type", + existing_type=sa.String(length=32), + existing_nullable=True, + ) + + +def downgrade() -> None: + """将库存连接器类型列恢复为旧名称,便于安全回滚。""" + op.alter_column( + "shipping_tasks", + "inventory_connector_type", + new_column_name="inventory_source_type", + existing_type=sa.String(length=32), + existing_nullable=True, + ) diff --git a/backend/migrations/versions/f1a2b3c4d5e6_shipping_customer_case_foundation.py b/backend/migrations/versions/f1a2b3c4d5e6_shipping_customer_case_foundation.py new file mode 100644 index 00000000..f11fc8f8 --- /dev/null +++ b/backend/migrations/versions/f1a2b3c4d5e6_shipping_customer_case_foundation.py @@ -0,0 +1,175 @@ +""" +用途:建立货代客户主数据、识别证据、业务单聚合、业务流水及任务客户裁决字段。 +依赖:Alembic revision e0f1a2b3c4d5。 +逻辑:新增表与 nullable 任务外键,历史任务保持不回填以兼容现有生产数据。 + +Revision ID: f1a2b3c4d5e6 +Revises: e0f1a2b3c4d5 +Create Date: 2026-07-15 13:00:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'f1a2b3c4d5e6' +down_revision = 'e0f1a2b3c4d5' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建客户与业务单基础表,并为任务增加可空关联字段。""" + op.create_table( + 'shipping_customers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('standard_name', sa.String(length=200), nullable=False), + sa.Column('short_code', sa.String(length=6), nullable=False), + sa.Column('status', sa.String(length=32), server_default='active', nullable=False), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=True), + sa.Column('updated_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['updated_by_id'], ['users.id']), + sa.CheckConstraint( + ( + "short_code ~ '^[A-Z]{2,6}$'" + if op.get_bind().dialect.name == 'postgresql' + else "length(short_code) BETWEEN 2 AND 6 " + "AND short_code = upper(short_code) " + "AND short_code NOT GLOB '*[^A-Z]*'" + ), + name='ck_shipping_customers_short_code_shape', + ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('short_code'), + ) + op.create_index('ix_shipping_customers_standard_name', 'shipping_customers', ['standard_name'], unique=False) + op.create_index('ix_shipping_customers_status_name', 'shipping_customers', ['status', 'standard_name'], unique=False) + op.create_index('ix_shipping_customers_created_at', 'shipping_customers', ['created_at'], unique=False) + + op.create_table( + 'shipping_customer_identifiers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=False), + sa.Column('identifier_type', sa.String(length=32), nullable=False), + sa.Column('raw_value', sa.String(length=500), nullable=False), + sa.Column('normalized_value', sa.String(length=500), nullable=False), + sa.Column('auto_match_allowed', sa.Boolean(), server_default=sa.text('false'), nullable=False), + sa.Column('status', sa.String(length=32), server_default='pending', nullable=False), + sa.Column('source', sa.String(length=32), server_default='manual', nullable=False), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('confirmed_by_id', sa.Integer(), nullable=True), + sa.Column('confirmed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['confirmed_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint( + 'customer_id', + 'identifier_type', + 'normalized_value', + name='uq_shipping_customer_identifiers_customer_type_value', + ), + ) + op.create_index('ix_shipping_customer_identifiers_customer_id', 'shipping_customer_identifiers', ['customer_id'], unique=False) + op.create_index('ix_shipping_customer_identifiers_created_at', 'shipping_customer_identifiers', ['created_at'], unique=False) + op.create_index('ix_shipping_customer_identifiers_lookup', 'shipping_customer_identifiers', ['identifier_type', 'normalized_value', 'status'], unique=False) + + op.create_table( + 'shipping_cases', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('case_no', sa.String(length=64), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('business_no', sa.String(length=32), nullable=True), + sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True), + sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True), + sa.Column('business_date', sa.Date(), nullable=True), + sa.Column('sequence_value', sa.Integer(), nullable=True), + sa.Column('numbering_rule_version', sa.String(length=32), nullable=True), + sa.Column('numbering_status', sa.String(length=32), server_default='pending', nullable=False), + sa.Column('status', sa.String(length=32), server_default='open', nullable=False), + sa.Column('replaces_case_id', sa.Integer(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']), + sa.ForeignKeyConstraint(['replaces_case_id'], ['shipping_cases.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('business_no'), + sa.UniqueConstraint('case_no'), + sa.UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'), + ) + op.create_index('ix_shipping_cases_customer_id', 'shipping_cases', ['customer_id'], unique=False) + op.create_index('ix_shipping_cases_customer_created', 'shipping_cases', ['customer_id', 'created_at'], unique=False) + op.create_index('ix_shipping_cases_status_created', 'shipping_cases', ['status', 'created_at'], unique=False) + op.create_index('ix_shipping_cases_created_at', 'shipping_cases', ['created_at'], unique=False) + + op.create_table( + 'shipping_business_sequences', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('business_type', sa.String(length=32), server_default='shipping_notice', nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=False), + sa.Column('business_date', sa.Date(), nullable=False), + sa.Column('current_value', sa.Integer(), server_default='0', nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']), + sa.CheckConstraint( + 'current_value BETWEEN 0 AND 99', + name='ck_shipping_business_sequences_current_value', + ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('business_type', 'customer_id', 'business_date', name='uq_shipping_business_sequences_type_customer_date'), + ) + op.create_index('ix_shipping_business_sequences_customer_id', 'shipping_business_sequences', ['customer_id'], unique=False) + op.create_index('ix_shipping_business_sequences_business_date', 'shipping_business_sequences', ['business_date'], unique=False) + + with op.batch_alter_table('shipping_tasks', schema=None) as batch_op: + batch_op.add_column(sa.Column('shipping_case_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('customer_resolution_status', sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column('customer_resolution_method', sa.String(length=32), nullable=True)) + batch_op.add_column(sa.Column('customer_identity_fingerprint', sa.String(length=64), nullable=True)) + batch_op.add_column(sa.Column('customer_confirmed_by', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('customer_confirmed_at', sa.DateTime(), nullable=True)) + batch_op.create_foreign_key('fk_shipping_tasks_shipping_case_id', 'shipping_cases', ['shipping_case_id'], ['id']) + batch_op.create_foreign_key('fk_shipping_tasks_customer_confirmed_by_users', 'users', ['customer_confirmed_by'], ['id']) + batch_op.create_index('ix_shipping_tasks_shipping_case_id', ['shipping_case_id'], unique=False) + batch_op.create_index('ix_shipping_tasks_customer_resolution_status', ['customer_resolution_status'], unique=False) + + +def downgrade() -> None: + """移除客户与业务单基础结构。""" + with op.batch_alter_table('shipping_tasks', schema=None) as batch_op: + batch_op.drop_index('ix_shipping_tasks_customer_resolution_status') + batch_op.drop_index('ix_shipping_tasks_shipping_case_id') + batch_op.drop_constraint('fk_shipping_tasks_customer_confirmed_by_users', type_='foreignkey') + batch_op.drop_constraint('fk_shipping_tasks_shipping_case_id', type_='foreignkey') + batch_op.drop_column('customer_confirmed_at') + batch_op.drop_column('customer_confirmed_by') + batch_op.drop_column('customer_identity_fingerprint') + batch_op.drop_column('customer_resolution_method') + batch_op.drop_column('customer_resolution_status') + batch_op.drop_column('shipping_case_id') + + op.drop_index('ix_shipping_business_sequences_business_date', table_name='shipping_business_sequences') + op.drop_index('ix_shipping_business_sequences_customer_id', table_name='shipping_business_sequences') + op.drop_table('shipping_business_sequences') + op.drop_index('ix_shipping_cases_created_at', table_name='shipping_cases') + op.drop_index('ix_shipping_cases_status_created', table_name='shipping_cases') + op.drop_index('ix_shipping_cases_customer_created', table_name='shipping_cases') + op.drop_index('ix_shipping_cases_customer_id', table_name='shipping_cases') + op.drop_table('shipping_cases') + op.drop_index('ix_shipping_customer_identifiers_lookup', table_name='shipping_customer_identifiers') + op.drop_index('ix_shipping_customer_identifiers_created_at', table_name='shipping_customer_identifiers') + op.drop_index('ix_shipping_customer_identifiers_customer_id', table_name='shipping_customer_identifiers') + op.drop_table('shipping_customer_identifiers') + op.drop_index('ix_shipping_customers_created_at', table_name='shipping_customers') + op.drop_index('ix_shipping_customers_status_name', table_name='shipping_customers') + op.drop_index('ix_shipping_customers_standard_name', table_name='shipping_customers') + op.drop_table('shipping_customers') diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 021fdd6d..3f47e84f 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -150,7 +150,7 @@ def seed_task_inventory_source( ) identity = resolution.identity task.inventory_source_code = identity.source_code - task.inventory_source_type = identity.source_type + task.inventory_connector_type = identity.connector_type task.inventory_site_id = identity.site_id task.inventory_warehouse_id = identity.warehouse_id task.inventory_source_status = "resolved" diff --git a/backend/tests/services/admin/test_shipping_customer_import_service.py b/backend/tests/services/admin/test_shipping_customer_import_service.py new file mode 100644 index 00000000..f6181780 --- /dev/null +++ b/backend/tests/services/admin/test_shipping_customer_import_service.py @@ -0,0 +1,199 @@ +""" +backend/tests/services/admin/test_shipping_customer_import_service.py + +用途:验证货代期初客户 Excel 的预检、决策、发布、幂等和事务回滚。 +依赖:openpyxl、FileStorage、内存数据库、shipping_customer_import_service。 +逻辑:在内存中构造标准工作簿,经真实服务链路验证暂存数据与正式客户主数据。 +""" + +from __future__ import annotations + +from datetime import datetime +from io import BytesIO + +import pytest +from openpyxl import Workbook +from werkzeug.datastructures import FileStorage + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import ( + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerImportBatch, +) +from app.services.admin.shipping_customer_import_service import ( + CUSTOMER_HEADERS, + IDENTIFIER_HEADERS, + build_reconciliation_csv, + create_import_batch, + decide_import_row, + publish_import_batch, +) + + +def _make_upload( + customer_rows: list[tuple], + identifier_rows: list[tuple] | None = None, + *, + filename: str = 'customers.xlsx', +) -> FileStorage: + """按正式模板在内存中构造上传文件。""" + workbook = Workbook() + customers = workbook.active + customers.title = 'customers' + customers.append(CUSTOMER_HEADERS) + for row in customer_rows: + customers.append(row) + identifiers = workbook.create_sheet('identifiers') + identifiers.append(IDENTIFIER_HEADERS) + for row in identifier_rows or []: + identifiers.append(row) + content = BytesIO() + workbook.save(content) + content.seek(0) + return FileStorage(stream=content, filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') + + +def test_import_upload_is_hash_idempotent_and_json_safe(app): + """相同文件重复上传返回原批次,日期单元格可安全写入 JSON 暂存。""" + with app.app_context(): + rows = [('INIT-1', '无锡宇辰', 'WYC', 'active', 'ERP', datetime(2026, 7, 15, 9, 30))] + original_upload = _make_upload(rows) + content = original_upload.read() + first = create_import_batch( + FileStorage(stream=BytesIO(content), filename='customers.xlsx'), + source_system='INITIAL_EXCEL', + actor_id=None, + ) + replay = create_import_batch( + FileStorage(stream=BytesIO(content), filename='customers.xlsx'), + source_system='INITIAL_EXCEL', + actor_id=None, + ) + + assert replay['id'] == first['id'] + assert replay['idempotent_replay'] is True + assert first['rows'][0]['raw']['remark'] == '2026-07-15T09:30:00' + assert db.session.query(ShippingCustomerImportBatch).count() == 1 + + different_source = create_import_batch( + FileStorage(stream=BytesIO(content), filename='customers.xlsx'), + source_system='ANOTHER_ERP', + actor_id=None, + ) + assert different_source['id'] != first['id'] + + +def test_import_rejects_oversized_source_without_staging_batch(app): + """来源系统超出数据库长度时在暂存前拒绝,避免产生半成品批次。""" + with app.app_context(): + with pytest.raises(ValidationError) as exc_info: + create_import_batch( + _make_upload([('INIT-1', '无锡宇辰', 'WYC', 'active', '', '')]), + source_system='X' * 65, + actor_id=None, + ) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID' + assert db.session.query(ShippingCustomerImportBatch).count() == 0 + + +def test_import_marks_oversized_row_fields_as_blocking_errors(app): + """行内稳定键和客户名称超长时进入错误行,发布必须被阻断。""" + with app.app_context(): + batch = create_import_batch( + _make_upload([('K' * 129, '客' * 201, 'WYC', 'active', 'ERP', '')]), + source_system='ERP', + actor_id=None, + ) + codes = {item['code'] for item in batch['rows'][0]['errors']} + assert 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID' in codes + assert 'SHIPPING.CUSTOMER_IMPORT_NAME_TOO_LONG' in codes + with pytest.raises(ValidationError) as exc_info: + publish_import_batch(batch['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS' + + +def test_import_errors_and_unresolved_warnings_block_publish(app): + """错误行直接阻断发布,公共邮箱警告行必须先明确 create 或 skip。""" + with app.app_context(): + invalid = create_import_batch( + _make_upload([('INIT-ERR', '错误客户', 'A1', 'active', 'ERP', '')]), + source_system='ERP', + actor_id=None, + ) + with pytest.raises(ValidationError) as exc_info: + publish_import_batch(invalid['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS' + + warning = create_import_batch( + _make_upload( + [('INIT-WARN', '公共邮箱客户', 'GGC', 'active', 'ERP', '')], + [('INIT-WARN', 'ERP', 'email', 'buyer@gmail.com', True, '')], + filename='warning.xlsx', + ), + source_system='ERP', + actor_id=None, + ) + warning_row = next(row for row in warning['rows'] if row['row_type'] == 'identifier') + assert warning_row['normalized']['auto_match_allowed'] is False + with pytest.raises(ValidationError) as exc_info: + publish_import_batch(warning['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_DECISIONS_REQUIRED' + + with pytest.raises(ValidationError) as exc_info: + decide_import_row(warning_row['id'], {'action': 'merge', 'target_customer_id': 1}) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID' + + +def test_publish_uses_row_source_system_for_customer_and_identifier(app): + """客户与标识按行级来源系统稳定关联,并创建 approved 识别证据和来源映射。""" + with app.app_context(): + batch = create_import_batch( + _make_upload( + [('ERP-001', '无锡宇辰有限公司', 'WYC', 'active', 'LEGACY_ERP', '期初客户')], + [('ERP-001', '', 'name_alias', 'WUXI YUCHEN', False, '英文名')], + ), + source_system='INITIAL_EXCEL', + actor_id=None, + ) + published = publish_import_batch(batch['id'], actor_id=None) + + customer = db.session.query(ShippingCustomer).one() + external_ref = db.session.query(ShippingCustomerExternalRef).one() + identifier = db.session.query(ShippingCustomerIdentifier).one() + assert published['status'] == 'published' + assert external_ref.customer_id == customer.id + assert external_ref.source_system == 'LEGACY_ERP' + assert identifier.customer_id == customer.id + assert identifier.status == 'approved' + assert identifier.auto_match_allowed is False + + replay = publish_import_batch(batch['id'], actor_id=None) + assert replay['idempotent_replay'] is True + csv_content, filename = build_reconciliation_csv(batch['id']) + assert filename.endswith('_reconciliation.csv') + assert b'identifier_created' in csv_content + + +def test_publish_conflict_rolls_back_entire_batch(app): + """发布中出现简码唯一冲突时,客户、来源映射和逐行结果全部回滚。""" + with app.app_context(): + batch = create_import_batch( + _make_upload([ + ('ERP-101', '客户一', 'DUP', 'active', 'ERP', ''), + ('ERP-102', '客户二', 'DUP', 'active', 'ERP', ''), + ]), + source_system='ERP', + actor_id=None, + ) + + with pytest.raises(ConflictError) as exc_info: + publish_import_batch(batch['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT' + assert db.session.query(ShippingCustomer).count() == 0 + assert db.session.query(ShippingCustomerExternalRef).count() == 0 + persisted = db.session.get(ShippingCustomerImportBatch, batch['id']) + assert persisted.status == 'validated' + assert all(row.result_status is None for row in persisted.rows) diff --git a/backend/tests/services/admin/test_shipping_customer_service.py b/backend/tests/services/admin/test_shipping_customer_service.py new file mode 100644 index 00000000..d0976df9 --- /dev/null +++ b/backend/tests/services/admin/test_shipping_customer_service.py @@ -0,0 +1,165 @@ +""" +backend/tests/services/admin/test_shipping_customer_service.py + +用途:验证货代客户主数据与识别证据的管理规则。 +依赖:pytest、内存数据库、shipping_customer_service。 +逻辑:直接调用服务层,覆盖简码唯一性、公共邮箱限制、审核门槛与列表统计。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy.exc import IntegrityError + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier +from app.services.admin.shipping_customer_service import ( + create_customer, + create_identifier, + list_customers, + update_identifier, +) + + +def _create_customer(*, name: str = '无锡宇辰有限公司', short_code: str = 'WYC') -> dict: + """创建测试客户并返回序列化结果。""" + return create_customer({'standard_name': name, 'short_code': short_code}, actor_id=None) + + +def test_customer_short_code_is_normalized_and_unique(app): + """简码统一转大写,且标准化后重复必须返回冲突。""" + with app.app_context(): + created = _create_customer(short_code='wyc') + assert created['short_code'] == 'WYC' + + with pytest.raises(ConflictError) as exc_info: + _create_customer(name='另一客户', short_code='WYC') + assert exc_info.value.code == 'SHIPPING.CUSTOMER_SHORT_CODE_EXISTS' + + with pytest.raises(ValidationError) as exc_info: + _create_customer(name='格式错误客户', short_code='W1') + assert exc_info.value.code == 'SHIPPING.CUSTOMER_SHORT_CODE_INVALID' + + +def test_customer_short_code_database_constraint_rejects_non_letters(app): + """绕过管理服务直接写库时,数据库仍须拒绝包含数字的客户简码。""" + with app.app_context(): + db.session.add(ShippingCustomer(standard_name='异常客户', short_code='W1', status='active')) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + assert db.session.query(ShippingCustomer).count() == 0 + + +def test_identifier_auto_match_requires_approval_and_rejects_public_mail(app): + """自动匹配仅允许已审核证据,公共邮箱地址和域名即使已审核也禁止启用。""" + with app.app_context(): + customer = _create_customer() + + with pytest.raises(ValidationError) as exc_info: + create_identifier( + customer['id'], + { + 'identifier_type': 'name_alias', + 'identifier_value': 'WUXI YUCHEN', + 'status': 'pending', + 'auto_match_allowed': True, + }, + actor_id=None, + ) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED' + + for identifier_type, value in (('domain', 'qq.com'), ('email', 'buyer@qq.com')): + with pytest.raises(ValidationError) as exc_info: + create_identifier( + customer['id'], + { + 'identifier_type': identifier_type, + 'identifier_value': value, + 'status': 'approved', + 'auto_match_allowed': True, + }, + actor_id=None, + ) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN' + + with pytest.raises(ValidationError) as exc_info: + create_identifier( + customer['id'], + { + 'identifier_type': 'domain', + 'identifier_value': 'wyc.example.com', + 'status': 'approved', + 'auto_match_allowed': 'false', + }, + actor_id=None, + ) + assert exc_info.value.details == {'field': 'auto_match_allowed'} + + +def test_identifier_loses_auto_match_when_approval_is_revoked(app): + """已审核证据降为 pending 或 disabled 时必须同步关闭自动匹配。""" + with app.app_context(): + customer = _create_customer() + identifier = create_identifier( + customer['id'], + { + 'identifier_type': 'domain', + 'identifier_value': 'wyc.example.com', + 'status': 'approved', + 'auto_match_allowed': True, + }, + actor_id=None, + ) + + updated = update_identifier(identifier['id'], {'status': 'pending'}, actor_id=None) + assert updated['status'] == 'pending' + assert updated['auto_match_allowed'] is False + + +def test_identifier_validation_failure_does_not_leave_dirty_state(app): + """联合更新违反审核门槛时,ORM 记录不得残留部分修改。""" + with app.app_context(): + customer = _create_customer() + identifier = create_identifier( + customer['id'], + { + 'identifier_type': 'domain', + 'identifier_value': 'wyc.example.com', + 'status': 'approved', + 'auto_match_allowed': True, + }, + actor_id=None, + ) + + with pytest.raises(ValidationError) as exc_info: + update_identifier( + identifier['id'], + {'status': 'pending', 'auto_match_allowed': True}, + actor_id=None, + ) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED' + persisted = db.session.get(ShippingCustomerIdentifier, identifier['id']) + assert persisted.status == 'approved' + assert persisted.auto_match_allowed is True + + +def test_customer_list_returns_preaggregated_reference_counts(app): + """列表返回业务单和识别证据数量,避免管理端逐客户补查。""" + with app.app_context(): + customer = _create_customer() + db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id'])) + db.session.add(ShippingCustomerIdentifier( + customer_id=customer['id'], + identifier_type='name_alias', + raw_value='WYC LTD', + normalized_value='WYCLTD', + status='approved', + source='manual', + )) + db.session.commit() + + result = list_customers({'page': 1, 'page_size': 20}) + assert result['items'][0]['case_count'] == 1 + assert result['items'][0]['identifier_count'] == 1 diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py new file mode 100644 index 00000000..a05a620c --- /dev/null +++ b/backend/tests/test_admin_shipping_customers.py @@ -0,0 +1,217 @@ +""" +backend/tests/test_admin_shipping_customers.py + +用途:验证货代客户管理 API 的权限、成功响应与错误 envelope。 +依赖:Flask 测试客户端、User、客户管理路由。 +逻辑:创建真实 admin/user 账户,通过 legacy header 访问管理路由并断言 RBAC 与响应契约。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + FileAsset, + ShippingCase, + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingNoticeCandidate, + ShippingNoticeDocument, + ShippingNoticeIntake, + ShippingTask, + User, +) +from tests.conftest import parse_api_data, parse_api_error + + +def _create_users() -> None: + """创建管理 API 权限测试所需的 admin 与普通用户。""" + db.session.add_all([ + User(username='shipping-admin', email='shipping-admin@example.com', role='admin', status='active'), + User(username='shipping-user', email='shipping-user@example.com', role='user', status='active'), + ]) + db.session.commit() + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造 legacy header 认证信息。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +def test_shipping_customer_admin_crud_uses_standard_contract(app, client): + """管理员可创建和查询客户,校验失败返回标准错误 envelope。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + + headers = _headers('shipping-admin', 'admin') + created_response = client.post( + '/api/admin/shipping-customers', + json={'standard_name': '无锡宇辰有限公司', 'short_code': 'wyc'}, + headers=headers, + ) + assert created_response.status_code == 201 + created = parse_api_data(created_response.get_json()) + assert created['short_code'] == 'WYC' + + list_response = client.get('/api/admin/shipping-customers', headers=headers) + assert list_response.status_code == 200 + listed = parse_api_data(list_response.get_json()) + assert listed['total'] == 1 + + invalid_response = client.post( + '/api/admin/shipping-customers', + json={'standard_name': '错误客户', 'short_code': 'A1'}, + headers=headers, + ) + assert invalid_response.status_code == 400 + assert parse_api_error(invalid_response.get_json())['code'] == 'SHIPPING.CUSTOMER_SHORT_CODE_INVALID' + + +def test_shipping_customer_admin_routes_reject_non_admin(app, client): + """普通用户访问客户主数据和导入模板均返回 403。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + + headers = _headers('shipping-user', 'user') + for path in ('/api/admin/shipping-customers', '/api/admin/shipping-customers/import-template'): + response = client.get(path, headers=headers) + assert response.status_code == 403 + assert parse_api_error(response.get_json())['code'] == 'AUTH.FORBIDDEN' + + +def test_shipping_customer_historical_backfill_api_does_not_number(app, client): + """管理员可为历史任务回填客户,且响应与业务单均不生成历史业务号。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + customer = ShippingCustomer(standard_name='历史客户', short_code='HIS', status='active') + task = ShippingTask(task_no='SN-20200101-HISTAPI', source_type='manual', process_status='closed') + db.session.add_all([customer, task]) + db.session.commit() + customer_id = customer.id + + response = client.post( + '/api/admin/shipping-customers/historical-task-backfill', + json={'task_no': 'SN-20200101-HISTAPI', 'customer_id': customer_id}, + headers=_headers('shipping-admin', 'admin'), + ) + assert response.status_code == 200 + payload = parse_api_data(response.get_json()) + assert payload['business_no'] is None + with app.app_context(): + persisted = ShippingTask.query.filter_by(task_no='SN-20200101-HISTAPI').one() + assert persisted.shipping_case.business_no is None + assert persisted.shipping_case.numbering_status == 'historical_unnumbered' + + +def test_shipping_customer_shadow_report_and_label_api(app, client): + """管理员可读取影子报告并写真值标签,普通用户不可访问。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + admin = db.session.query(User).filter_by(username='shipping-admin').one() + customer = ShippingCustomer(standard_name='ACME', short_code='ACM', status='active') + db.session.add(customer) + db.session.flush() + asset = FileAsset( + asset_no='FA-SHADOW-API', owner_user_id=admin.id, original_filename='notice.txt', + storage_provider='minio', storage_bucket='test', storage_key='shadow-api', + content_hash='b' * 64, file_size=1, upload_status='uploaded', lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-SHADOW-API', asset_id=asset.id, user_id=admin.id, parser_version='v6', parse_status='parsed', + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file', + classification='order_notice', parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + candidate = ShippingNoticeCandidate( + candidate_no='SNC-SHADOW-API', intake_id=intake.id, primary_document_id=document.id, + candidate_key='document:1', validation_status='ready', + ) + db.session.add(candidate) + db.session.flush() + shadow = ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=intake.id, resolution_version='shadow-v1', + status='unique_candidate', evidence_json=[], candidate_matches_json=[], + top_customer_id=customer.id, top_score=60, + ) + db.session.add(shadow) + db.session.commit() + shadow_id = shadow.id + customer_id = customer.id + + admin_headers = _headers('shipping-admin', 'admin') + report_response = client.get('/api/admin/shipping-customer-shadow-report', headers=admin_headers) + assert report_response.status_code == 200 + report = parse_api_data(report_response.get_json()) + assert report['total'] == 1 + assert report['items'][0]['candidate_no'] == 'SNC-SHADOW-API' + assert report['auto_resolution']['enabled'] is False + assert report['auto_resolution']['recent_events'] == [] + + label_response = client.put( + f'/api/admin/shipping-customer-shadow-resolutions/{shadow_id}/label', + json={'customer_id': customer_id}, + headers=admin_headers, + ) + assert label_response.status_code == 200 + assert parse_api_data(label_response.get_json())['is_correct'] is True + + forbidden = client.get( + '/api/admin/shipping-customer-shadow-report', + headers=_headers('shipping-user', 'user'), + ) + assert forbidden.status_code == 403 + + +def test_shipping_customer_numbered_correction_api_preserves_old_number(app, client): + """管理员纠错 API 作废原号并返回替代新号,普通用户不可调用。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active') + correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active') + case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending') + db.session.add_all([wrong, correct, case]) + db.session.flush() + task = ShippingTask( + task_no='SN-CORRECTION-API', shipping_case_id=case.id, + source_type='manual', process_status='parsed', customer_resolution_status='pending', + ) + db.session.add(task) + db.session.commit() + from app.services.shipping_notice.customer_identity_gate import confirm_task_customer + + confirm_task_customer(task, customer_id=wrong.id, actor_id=None) + old_business_no = task.shipping_case.business_no + correct_id = correct.id + + forbidden = client.post( + '/api/admin/shipping-customers/numbered-task-correction', + json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'}, + headers=_headers('shipping-user', 'user'), + ) + assert forbidden.status_code == 403 + + response = client.post( + '/api/admin/shipping-customers/numbered-task-correction', + json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'}, + headers=_headers('shipping-admin', 'admin'), + ) + assert response.status_code == 200 + payload = parse_api_data(response.get_json()) + assert payload['old_business_no'] == old_business_no + assert payload['new_business_no'].startswith('NEW') + with app.app_context(): + old_case = ShippingCase.query.filter_by(business_no=old_business_no).one() + replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one() + assert old_case.status == 'voided' + assert replacement.business_no == payload['new_business_no'] diff --git a/backend/tests/test_chat_executors_registry.py b/backend/tests/test_chat_executors_registry.py index f9cb6f87..12f18658 100644 --- a/backend/tests/test_chat_executors_registry.py +++ b/backend/tests/test_chat_executors_registry.py @@ -1,7 +1,9 @@ """ tests/test_chat_executors_registry.py -用途:RUNTIME_PROVIDER_REGISTRY 与 Hybrid Executor 单元测试。 +用途:RUNTIME_PROVIDER_REGISTRY、Hybrid Executor 与 Handler 前置时序单元测试。 +依赖:executor registry、agent handler/context adapter bootstrap、pytest Flask fixture。 +逻辑:验证 provider 解析、Handler 强制约束,以及 prepare_stream 在上游生成器迭代前完成。 """ from __future__ import annotations @@ -93,3 +95,36 @@ def test_stream_chat_via_executor_delegates_to_dify(app, monkeypatch): assert captured['kwargs']['session_id'] == 'sess-1' inputs = captured['kwargs'].get('inputs') or {} assert 'agent_runtime_context' in inputs + + +def test_stream_chat_via_executor_prepares_handler_before_generator_iteration(app, monkeypatch): + """Handler 必须在返回惰性上游生成器前完成准备,供 chat.py preface 立即读取领域状态。""" + prepared = {'count': 0} + + class _Handler: + def prepare_stream(self, ctx): + prepared['count'] += 1 + ctx.hxops_turn_id = 'prepared-before-preface' + return ctx + + with app.app_context(): + monkeypatch.setattr( + 'app.services.chat.executors.resolve_handler_for_agent_code', + lambda agent: _Handler(), + ) + ctx = ChatStreamContext( + query='hello', + display_query='hello', + user=SimpleNamespace(id=1), + agent=_agent(), + session=SimpleNamespace(session_id='sess-prepare'), + external_conversation_id=None, + request_id='req-prepare', + ) + + generator = stream_chat_via_executor(ctx) + + # 关键断言:此时尚未 list(generator),prepare 已同步完成且只执行一次。 + assert prepared['count'] == 1 + assert ctx.hxops_turn_id == 'prepared-before-preface' + assert generator is not None diff --git a/backend/tests/test_chat_user_attachments.py b/backend/tests/test_chat_user_attachments.py new file mode 100644 index 00000000..0ed4de49 --- /dev/null +++ b/backend/tests/test_chat_user_attachments.py @@ -0,0 +1,98 @@ +""" +backend/tests/test_chat_user_attachments.py + +用途:验证聊天附件快照的后端白名单清洗与归属安全合并。 +依赖:chat API 附件辅助函数、pytest monkeypatch。 +逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。 +""" + +from app.api.chat import ( + CHAT_USER_ATTACHMENT_LIMIT, + _merge_user_attachments_from_terminal_event, + _normalize_user_attachments, +) + + +def test_normalize_user_attachments_keeps_only_display_whitelist(): + items = [{ + 'id': 'attachment-1', + 'name': 'C:\\temp\\purchase-order.pdf\x00', + 'size': '144456', + 'extension': 'PDF', + 'type': 'document', + 'source': 'local', + 'url': 'https://example.com/?signature=secret', + 'upload_file_id': 'internal-upload', + 'asset_no': 'ASSET-1', + }] + + assert _normalize_user_attachments(items) == [{ + 'id': 'attachment-1', + 'name': 'purchase-order.pdf', + 'size': 144456, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + }] + + +def test_normalize_user_attachments_limits_items_and_drops_invalid_values(): + valid = { + 'id': 'attachment-1', + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)] + items[0] = {**valid, 'type': 'executable'} + items[1] = {**valid, 'source': 'unknown'} + items[2] = {**valid, 'size': -1, 'extension': '../pdf'} + + normalized = _normalize_user_attachments(items) + + assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2 + assert 'size' not in normalized[0] + assert 'extension' not in normalized[0] + + +def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch): + monkeypatch.setattr('app.services.chat.log_service.merge_chat_log_payload', lambda **kwargs: True) + + assert _merge_user_attachments_from_terminal_event( + {'event': 'error'}, + user_id=1, + agent_id=2, + session_id='session-1', + user_attachments=[{'name': 'file.pdf', 'type': 'document', 'source': 'local'}], + ) is False + + +def test_merge_user_attachments_uses_chat_log_ownership(monkeypatch): + captured = {} + + def fake_merge(**kwargs): + captured.update(kwargs) + return True + + monkeypatch.setattr('app.services.chat.log_service.merge_chat_log_payload', fake_merge) + + result = _merge_user_attachments_from_terminal_event( + {'event': 'message_end', 'chat_log_id': 42}, + user_id=1, + agent_id=2, + session_id='session-1', + user_attachments=[{'name': 'file.pdf', 'type': 'document', 'source': 'local'}], + ) + + assert result is True + assert captured == { + 'chat_log_id': 42, + 'user_id': 1, + 'agent_id': 2, + 'session_id': 'session-1', + 'payload_patch': { + 'user_attachments': [{'name': 'file.pdf', 'type': 'document', 'source': 'local'}], + }, + } diff --git a/backend/tests/test_dify_workflow_reliability.py b/backend/tests/test_dify_workflow_reliability.py index dc2ec2dc..76b8460b 100644 --- a/backend/tests/test_dify_workflow_reliability.py +++ b/backend/tests/test_dify_workflow_reliability.py @@ -2,6 +2,8 @@ tests/test_dify_workflow_reliability.py 用途:覆盖 Dify Workflow streaming 断连补偿、重试与可靠性元信息。 +依赖:requests、DifyService、FileCheckService 与 pytest Flask fixture。 +逻辑:模拟 Dify SSE、HTTP 错误及超时,验证 Workflow 轮询补偿和 Chatflow 终态事件不会丢失。 """ from __future__ import annotations @@ -22,6 +24,7 @@ class _Agent: def _sse_lines(*events: dict) -> list[bytes]: + """把事件字典编码为 Dify requests.iter_lines 返回的字节行。""" return [f"data: {json.dumps(evt, ensure_ascii=False)}".encode("utf-8") for evt in events] @@ -308,3 +311,73 @@ def test_dedupe_exact_doubled_text_fixes_historical_records(): doubled = "检核完成,共处理 3 个文件。" * 2 assert DifyService._dedupe_exact_doubled_text(doubled) == "检核完成,共处理 3 个文件。" assert DifyService._dedupe_exact_doubled_text("unique answer") == "unique answer" + + +def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch): + """连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。""" + monkeypatch.setattr( + "app.services.dify.requests.post", + lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")), + ) + monkeypatch.setattr( + DifyService, + "_persist_stream_chat_record", + staticmethod(lambda **kwargs: {"chat_log_id": 42, "run_id": None}), + ) + + with app.app_context(): + lines = list(DifyService.stream_chat( + "extract orders", + 1, + _Agent(), + request_id="req-connect-timeout", + session_id="session-connect-timeout", + )) + + events = [json.loads(line.removeprefix("data: ").strip()) for line in lines] + error_event = next(event for event in events if event.get("event") == "error") + # 关键断言:持久化返回的主键必须沿原 error 事件继续向 relay 传播。 + assert error_event["chat_log_id"] == 42 + assert error_event["message"] + + +def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeypatch): + """已有正文后 ReadTimeout 应合成 message_end,避免领域状态永久停留在 extracting。""" + class _ChatResponse: + ok = True + status_code = 200 + reason = "OK" + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def raise_for_status(self): + return None + + def iter_lines(self): + yield _sse_lines({"event": "message", "answer": "partial answer"})[0] + raise requests.exceptions.ReadTimeout("read timed out") + + monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse()) + monkeypatch.setattr( + DifyService, + "_persist_stream_chat_record", + staticmethod(lambda **kwargs: {"chat_log_id": 43, "run_id": None}), + ) + + with app.app_context(): + lines = list(DifyService.stream_chat( + "extract orders", + 1, + _Agent(), + request_id="req-read-timeout", + session_id="session-read-timeout", + )) + + events = [json.loads(line.removeprefix("data: ").strip()) for line in lines] + terminal = next(event for event in events if event.get("event") == "message_end") + assert terminal["answer"] == "partial answer" + assert terminal["chat_log_id"] == 43 diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index b5ea0613..b11c93cc 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -53,7 +53,7 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]: "attempt": 3, "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", "enabled": True, "entry_url": "https://s360.dbschenker.com/", @@ -276,7 +276,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path assert trigger["task_no"] == "SN-20260629-2EDADC77" assert trigger["attempt"] == 3 assert trigger["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU" - assert trigger["rpa_inventory_source"]["source_type"] == "dsv360" + assert trigger["rpa_inventory_source"]["connector_type"] == "dsv360" assert trigger["rpa_inventory_source"]["query"]["program_label"] == "AWSDU - Prod (JDA)" assert trigger["rpa_inventory_source"]["query"]["owner_code"] == "CADU-0000000100" diff --git a/backend/tests/test_shipping_business_numbering.py b/backend/tests/test_shipping_business_numbering.py new file mode 100644 index 00000000..b37a0b6c --- /dev/null +++ b/backend/tests/test_shipping_business_numbering.py @@ -0,0 +1,181 @@ +""" +backend/tests/test_shipping_business_numbering.py + +用途:验证货代业务编号格式、上海日期、两位流水上限及业务单版本继承。 +依赖:ShippingCase/Customer/Sequence、business_numbering_service、customer_identity_gate。 +逻辑:直接调用领域服务,覆盖幂等、01-99、修订共享与强制新建独立编号。 +""" + +from datetime import datetime, timezone + +import pytest + +from app import db +from app.core.errors import ConflictError +from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent +from app.services.shipping_notice.business_numbering_service import ( + assign_business_number, + format_business_no, + shanghai_business_date, +) +from app.services.shipping_notice.customer_identity_gate import confirm_task_customer +from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref + + +def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"): + """创建待客户确认的业务单、任务和启用客户。""" + customer = ShippingCustomer( + standard_name=f"编号测试客户 {short_code}", + short_code=short_code, + status="active", + ) + case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending") + db.session.add_all([customer, case]) + db.session.flush() + task = ShippingTask( + task_no=task_no, + shipping_case_id=case.id, + customer_resolution_status="pending", + source_type="manual", + process_status="parsed", + ) + db.session.add(task) + db.session.commit() + return task, case, customer + + +def test_number_format_and_shanghai_date_boundary(app): + """UTC 日期跨日时必须按 Asia/Shanghai 生成 YYMMDD 且不含分隔符。""" + with app.app_context(): + moment = datetime(2026, 7, 14, 16, 30, tzinfo=timezone.utc) + business_date = shanghai_business_date(moment) + assert business_date.isoformat() == "2026-07-15" + assert format_business_no("WYC", business_date, 1) == "WYC26071501" + + +def test_confirmation_assigns_idempotent_business_number(app): + """重复确认同一客户不得重复占用流水,正式编号保持不变。""" + with app.app_context(): + task, case, customer = _seed_case() + first = confirm_task_customer(task, customer_id=customer.id, actor_id=None) + first_no = first.shipping_case.business_no + second = confirm_task_customer(first, customer_id=customer.id, actor_id=None) + + assert first_no + assert second.shipping_case.business_no == first_no + assert ShippingBusinessSequence.query.one().current_value == 1 + assert second.shipping_case.customer_short_code_snapshot == "WYC" + assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1 + + +def test_revision_inherits_and_force_case_uses_next_sequence(app): + """同一业务单修订继承编号,独立业务单确认同客户时占用下一流水。""" + with app.app_context(): + task, case, customer = _seed_case() + confirm_task_customer(task, customer_id=customer.id, actor_id=None) + revision = ShippingTask( + task_no="SN-NUMBER-REV", + shipping_case_id=case.id, + supersedes_task_id=task.id, + customer_resolution_status="confirmed", + source_type="manual", + process_status="parsed", + ) + forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending") + db.session.add_all([revision, forced_case]) + db.session.flush() + forced_task = ShippingTask( + task_no="SN-NUMBER-FORCED", + shipping_case_id=forced_case.id, + customer_resolution_status="pending", + source_type="manual", + process_status="parsed", + ) + db.session.add(forced_task) + db.session.commit() + + confirm_task_customer(forced_task, customer_id=customer.id, actor_id=None) + assert revision.shipping_case.business_no == case.business_no + assert forced_task.shipping_case.business_no[:-2] == case.business_no[:-2] + assert case.business_no.endswith("01") + assert forced_task.shipping_case.business_no.endswith("02") + + +def test_daily_sequence_blocks_one_hundredth_case(app): + """客户当日已有 99 笔时,第 100 笔必须阻断且不写业务号。""" + with app.app_context(): + task, case, customer = _seed_case() + business_date = shanghai_business_date() + db.session.add(ShippingBusinessSequence( + business_type="shipping_notice", + customer_id=customer.id, + business_date=business_date, + current_value=99, + )) + db.session.commit() + case.customer_id = customer.id + + with pytest.raises(ConflictError) as exc_info: + assign_business_number(case) + assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED" + assert case.business_no is None + assert ShippingBusinessSequence.query.one().current_value == 99 + + +def test_numbering_failure_rolls_back_customer_confirmation(app): + """流水耗尽导致确认失败时,业务单客户和任务确认状态不得半落库。""" + with app.app_context(): + task, case, customer = _seed_case() + db.session.add(ShippingBusinessSequence( + business_type="shipping_notice", + customer_id=customer.id, + business_date=shanghai_business_date(), + current_value=99, + )) + db.session.commit() + + with pytest.raises(ConflictError): + confirm_task_customer(task, customer_id=customer.id, actor_id=None) + db.session.rollback() + db.session.expire_all() + persisted_case = db.session.get(ShippingCase, case.id) + persisted_task = db.session.get(ShippingTask, task.id) + assert persisted_case.customer_id is None + assert persisted_case.business_no is None + assert persisted_task.customer_resolution_status == "pending" + + +def test_business_number_query_returns_latest_revision(app): + """使用正式业务号查询时应返回同业务单最新修订任务。""" + with app.app_context(): + task, case, customer = _seed_case() + confirm_task_customer(task, customer_id=customer.id, actor_id=None) + revision = ShippingTask( + task_no="SN-NUMBER-QUERY-REV", + shipping_case_id=case.id, + supersedes_task_id=task.id, + document_version=2, + customer_resolution_status="confirmed", + source_type="manual", + process_status="parsed", + ) + db.session.add(revision) + db.session.commit() + + resolved = get_task_by_ref(case.business_no) + assert resolved.id == revision.id + assert extract_task_no_from_text(f"请继续处理 {case.business_no}") == case.business_no + + +def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app): + """客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。""" + with app.app_context(): + task, case, customer = _seed_case() + case.customer_id = customer.id + customer.short_code = "W1" + # 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。 + with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info: + assign_business_number(case) + assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID" + assert case.business_no is None + db.session.rollback() diff --git a/backend/tests/test_shipping_customer_auto_resolution.py b/backend/tests/test_shipping_customer_auto_resolution.py new file mode 100644 index 00000000..873c50a7 --- /dev/null +++ b/backend/tests/test_shipping_customer_auto_resolution.py @@ -0,0 +1,283 @@ +""" +backend/tests/test_shipping_customer_auto_resolution.py + +用途:验证受控自动客户确认、降级开关、强规则歧义和历史客户回填。 +依赖:客户主数据/证据、Candidate 影子结果、ShippingTask/Case、customer_auto_resolution。 +逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 +""" + +import pytest + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import ( + FileAsset, + ShippingCase, + ShippingCustomer, + ShippingCustomerIdentifier, + ShippingCustomerShadowResolution, + ShippingNoticeCandidate, + ShippingNoticeDocument, + ShippingNoticeIntake, + ShippingTask, + ShippingTaskEvent, + User, +) +from app.services.shipping_notice.customer_auto_resolution import ( + AUTO_RESOLUTION_VERSION, + backfill_historical_task_customer, + correct_numbered_task_customer, + get_auto_resolution_metrics, + try_auto_confirm_task_customer, +) +from app.services.shipping_notice.customer_identity_gate import confirm_task_customer +from app.services.shipping_notice.query_service import get_task_by_ref + + +def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"): + """创建带邮件证据的 Candidate、影子记录和待确认任务。""" + user = User(username=f"auto-user-{db.session.query(User).count()}", email="auto@example.com", role="user") + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no=f"AUTO-ASSET-{user.id}", owner_user_id=user.id, original_filename="notice.eml", + storage_provider="minio", storage_bucket="test", storage_key=f"auto-{user.id}", + content_hash=f"{user.id:064d}", file_size=1, upload_status="uploaded", lifecycle_status="temporary", + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no=f"AUTO-INTAKE-{user.id}", asset_id=asset.id, user_id=user.id, + parser_version="v6", parse_status="parsed", structured_result_json={"email": {"from": sender}}, + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type="attachment", attachment_key="file", + filename="notice.pdf", classification="order_notice", parse_status="parsed", + ) + db.session.add(document) + db.session.flush() + candidate = ShippingNoticeCandidate( + candidate_no=f"AUTO-CAND-{user.id}", intake_id=intake.id, primary_document_id=document.id, + candidate_key="document:1", validation_status="ready", selected=True, + structured_result_json={"business_summary": {"customer_name": "unstable name"}}, + ) + case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending") + db.session.add_all([candidate, case]) + db.session.flush() + task = ShippingTask( + task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id, + user_id=user.id, source_type="email_attachment", process_status="parsed", + customer_resolution_status="pending", + ) + db.session.add(task) + db.session.flush() + shadow = ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=intake.id, resolution_version="shadow-v1", + status="unique_candidate", + evidence_json=[ + {"type": "email", "raw_value": sender, "normalized_value": sender}, + {"type": "domain", "raw_value": sender.split("@")[-1], "normalized_value": sender.split("@")[-1]}, + ], + candidate_matches_json=[], + ) + db.session.add(shadow) + db.session.commit() + return task + + +def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, status: str = "approved"): + """创建客户及邮箱强证据。""" + customer = ShippingCustomer(standard_name=f"客户 {code}", short_code=code, status="active") + db.session.add(customer) + db.session.flush() + db.session.add(ShippingCustomerIdentifier( + customer_id=customer.id, identifier_type="email", raw_value=value, normalized_value=value, + status=status, source="manual", auto_match_allowed=allowed, + )) + db.session.flush() + return customer + + +def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): + """开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。""" + with app.app_context(): + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + + result = try_auto_confirm_task_customer(task) + + assert result["status"] == "auto_confirmed" + assert result["rule_version"] == AUTO_RESOLUTION_VERSION + assert task.customer_resolution_status == "confirmed" + assert task.customer_resolution_method == "auto_rule" + assert task.shipping_case.customer_id == customer.id + assert task.shipping_case.business_no.startswith("WYC") + assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 + metrics = get_auto_resolution_metrics() + assert metrics["auto_confirmed_count"] == 1 + assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed" + assert metrics["recent_events"][0]["task_no"] == task.task_no + + +def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): + """总开关关闭或证据未审核/未授权时保持 pending,不占用业务流水。""" + with app.app_context(): + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com", allowed=False) + task = _seed_candidate_task() + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False + disabled = try_auto_confirm_task_customer(task) + assert disabled["status"] == "disabled" + assert task.shipping_case.business_no is None + + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + unmatched = try_auto_confirm_task_customer(task) + assert unmatched["status"] == "unmatched" + assert task.customer_resolution_status == "pending" + assert task.shipping_case.business_no is None + + +def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): + """同一强证据映射多个客户时必须降级人工确认。""" + with app.app_context(): + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + _customer_with_identifier(code="AAA", value="buyer@wyc.example.com") + _customer_with_identifier(code="BBB", value="buyer@wyc.example.com") + task = _seed_candidate_task() + + result = try_auto_confirm_task_customer(task) + assert result["status"] == "ambiguous" + assert len(result["candidate_customer_ids"]) == 2 + assert task.customer_resolution_status == "pending" + assert task.shipping_case.business_no is None + + +def test_historical_backfill_binds_customer_without_numbering(app): + """历史任务回填客户后业务号仍为空,不倒占当日流水。""" + with app.app_context(): + customer = ShippingCustomer(standard_name="历史客户", short_code="HIS", status="active") + task = ShippingTask(task_no="SN-20200101-HISTORY", source_type="manual", process_status="closed") + db.session.add_all([customer, task]) + db.session.commit() + + result = backfill_historical_task_customer(task, customer_id=customer.id, actor_id=None) + assert result["business_no"] is None + assert task.shipping_case.customer_id == customer.id + assert task.shipping_case.numbering_status == "historical_unnumbered" + assert task.shipping_case.business_no is None + assert task.customer_resolution_method == "historical_backfill" + metrics = get_auto_resolution_metrics() + assert metrics["historical_backfilled_count"] == 1 + assert metrics["recent_events"][0]["event_type"] == "customer_historical_backfilled" + + +def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): + """批次编排失败时,自动确认、编号和审计必须随外层事务整体回滚。""" + with app.app_context(): + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + task_id = task.id + case_id = task.shipping_case_id + + result = try_auto_confirm_task_customer(task) + assert result["status"] == "auto_confirmed" + db.session.rollback() + db.session.expire_all() + + persisted_task = db.session.get(ShippingTask, task_id) + persisted_case = db.session.get(ShippingCase, case_id) + assert persisted_task.customer_resolution_status == "pending" + assert persisted_case.customer_id is None + assert persisted_case.business_no is None + assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 + + +def test_numbered_customer_correction_voids_old_number_and_replaces_case(app): + """客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。""" + with app.app_context(): + wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") + correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") + case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending") + db.session.add_all([wrong, correct, case]) + db.session.flush() + first = ShippingTask( + task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1, + source_type="manual", process_status="parsed", customer_resolution_status="pending", + ) + db.session.add(first) + db.session.flush() + latest = ShippingTask( + task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2, + supersedes_task_id=first.id, source_type="manual", process_status="waiting_upload", + customer_resolution_status="pending", inventory_source_code="DSV", + inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}], + match_status="fulfillable", line_results_json=[{"sku": "A"}], + export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx", + ) + db.session.add(latest) + db.session.commit() + confirm_task_customer(first, customer_id=wrong.id, actor_id=None) + old_case_id = case.id + old_business_no = case.business_no + + result = correct_numbered_task_customer( + latest, + customer_id=correct.id, + reason="自动识别客户错误", + actor_id=None, + ) + + old_case = db.session.get(ShippingCase, old_case_id) + replacement = db.session.get(ShippingCase, result["new_case_id"]) + assert old_case.business_no == old_business_no + assert old_case.status == "voided" + assert old_case.numbering_status == "voided" + assert replacement.replaces_case_id == old_case.id + assert replacement.business_no.startswith("NEW") + assert replacement.business_no != old_business_no + assert latest.shipping_case_id == replacement.id + assert first.shipping_case_id == replacement.id + assert latest.customer_resolution_method == "admin_correction" + assert latest.inventory_source_status is None + assert latest.inventory_lines_json is None + assert latest.export_file_path is None + assert latest.process_status == "parsed" + assert get_task_by_ref(old_business_no).id == latest.id + assert get_task_by_ref(replacement.business_no).id == latest.id + assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2 + metrics = get_auto_resolution_metrics() + assert metrics["corrected_task_count"] == 2 + assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no + + +def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app): + """纠错必须有原因,且已对外上传业务单需先走外部作废流程。""" + with app.app_context(): + wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active") + correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active") + case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending") + db.session.add_all([wrong, correct, case]) + db.session.flush() + task = ShippingTask( + task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id, + source_type="manual", process_status="parsed", customer_resolution_status="pending", + ) + db.session.add(task) + db.session.commit() + confirm_task_customer(task, customer_id=wrong.id, actor_id=None) + + with pytest.raises(ValidationError) as exc_info: + correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None) + assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED" + db.session.rollback() + + task.process_status = "uploaded" + db.session.commit() + with pytest.raises(ConflictError) as exc_info: + correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None) + assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED" + db.session.rollback() + assert db.session.query(ShippingCase).count() == 1 diff --git a/backend/tests/test_shipping_customer_identity_gate.py b/backend/tests/test_shipping_customer_identity_gate.py new file mode 100644 index 00000000..2eecf307 --- /dev/null +++ b/backend/tests/test_shipping_customer_identity_gate.py @@ -0,0 +1,175 @@ +""" +backend/tests/test_shipping_customer_identity_gate.py + +用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 +依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 +逻辑:构造 pending 任务逐入口断言无副作用;确认后验证业务单/修订同步和历史兼容。 +""" + +from __future__ import annotations + +from io import BytesIO + +import pytest +from werkzeug.datastructures import FileStorage + +from app import db +from app.core.errors import AppError +from app.models import ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent, User +from app.services.shipping_notice.customer_identity_gate import ( + assert_customer_identity_gate, + confirm_task_customer, + customer_identity_is_confirmed, +) +from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight +from app.services.shipping_notice.inventory_rpa_workflow import ( + _validate_rpa_callback_gate, + ensure_inventory_via_rpa, +) +from app.services.shipping_notice.inventory_workflow import ensure_inventory, parse_inventory, upload_inventory_file +from app.services.shipping_notice.progress_workflow import auto_progress + + +def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustomer, User]: + """创建待确认任务、启用客户和任务用户。""" + sequence = db.session.query(User).count() + user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') + short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}' + customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') + db.session.add_all([user, customer]) + db.session.flush() + case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None + if case: + db.session.add(case) + db.session.flush() + task = ShippingTask( + task_no=f'SN-GATE-{user.id}', user_id=user.id, + shipping_case_id=case.id if case else None, + customer_resolution_status='pending' if case else None, + process_status='parsed', lines_json=[{'sku': 'A001', 'quantity': 1}], + inventory_source_status='user_confirmed', inventory_source_code='DSV', + ) + db.session.add(task) + db.session.commit() + return task, customer, user + + +def _assert_customer_gate_response(result: dict) -> None: + """断言 Tool 入口返回统一客户检查点。""" + assert result['status'] == 'needs_human' + assert result['checkpoint'] == 'customer_review' + assert result['human_options'] == ['confirm_customer'] + + +def test_pending_customer_blocks_every_downstream_entry(app): + """未确认客户时所有库存与履约公共入口都必须在副作用前停止。""" + with app.app_context(): + task, _customer, _user = _seed_task() + app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True + + results = [ + auto_progress({'task_id': task.task_no}), + parse_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), + ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), + upload_inventory_file( + task.task_no, + FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'), + ), + ensure_inventory_via_rpa(task, mode='auto'), + match_inventory({'task_id': task.task_no}), + generate_excel({'task_id': task.task_no}), + upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}), + ] + for result in results: + _assert_customer_gate_response(result) + + callback = _validate_rpa_callback_gate(task) + assert callback is not None + assert callback['status'] == 'failed' + db.session.refresh(task) + assert task.inventory_lines_json is None + assert task.export_file_path is None + assert task.upload_status is None + + +def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): + """客户确认同步同业务单全部任务,并在同事务生成正式业务号。""" + with app.app_context(): + task, customer, user = _seed_task() + revision = ShippingTask( + task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id, + supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending', + process_status='parsed', + ) + db.session.add(revision) + db.session.commit() + + updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) + db.session.refresh(revision) + case = db.session.get(ShippingCase, task.shipping_case_id) + assert updated.customer_resolution_status == 'confirmed' + assert revision.customer_resolution_status == 'confirmed' + assert updated.customer_resolution_method == 'manual' + assert case.customer_id == customer.id + assert case.customer_name_snapshot == customer.standard_name + assert case.customer_short_code_snapshot == customer.short_code + assert case.business_no.startswith(customer.short_code) + assert len(case.business_no) == len(customer.short_code) + 8 + assert case.sequence_value == 1 + assert case.numbering_status == 'assigned' + assert customer_identity_is_confirmed(updated) is True + assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2 + assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2 + + +def test_inactive_customer_reblocks_and_legacy_task_is_compatible(app): + """已确认客户停用后重新阻断;历史无业务单任务继续兼容。""" + with app.app_context(): + task, customer, user = _seed_task() + confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) + customer.status = 'inactive' + db.session.commit() + with pytest.raises(AppError) as exc_info: + assert_customer_identity_gate(task, operation='match_inventory') + assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' + + legacy, _other_customer, _other_user = _seed_task(with_case=False) + assert_customer_identity_gate(legacy, operation='match_inventory') + assert customer_identity_is_confirmed(legacy) is True + + +def test_workspace_customer_search_and_confirmation_api(app, client): + """业务用户只能确认自己的任务,确认响应返回正式业务编号。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + task, customer, user = _seed_task() + other_user = User(username='gate-other-user', email='gate-other@example.com', role='user') + db.session.add(other_user) + db.session.commit() + task_no = task.task_no + customer_id = customer.id + username = user.username + + headers = {'X-Username': username, 'X-Role': 'user', 'Content-Type': 'application/json'} + options_response = client.get('/api/workspace/shipping-customers?q=GAA', headers=headers) + assert options_response.status_code == 200 + assert options_response.get_json()[0]['short_code'] == 'GAA' + + confirm_response = client.post( + f'/api/workspace/shipping-tasks/{task_no}/confirm-customer', + json={'customer_id': customer_id}, + headers=headers, + ) + assert confirm_response.status_code == 200 + payload = confirm_response.get_json() + assert payload['customer_resolution_status'] == 'confirmed' + assert payload['customer_id'] == customer_id + assert payload['business_no'].startswith('GAA') + + other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'} + forbidden_response = client.post( + f'/api/workspace/shipping-tasks/{task_no}/confirm-customer', + json={'customer_id': customer_id}, + headers=other_headers, + ) + assert forbidden_response.status_code == 404 diff --git a/backend/tests/test_shipping_customer_migrations.py b/backend/tests/test_shipping_customer_migrations.py new file mode 100644 index 00000000..eb97e4af --- /dev/null +++ b/backend/tests/test_shipping_customer_migrations.py @@ -0,0 +1,89 @@ +""" +backend/tests/test_shipping_customer_migrations.py + +用途:独立验证客户主数据、期初导入与影子识别三段迁移可升级和降级。 +依赖:Alembic MigrationContext、SQLAlchemy、f1/a2/b3 客户迁移模块。 +逻辑:构造订单抽取阶段的最小历史结构,依序执行迁移并检查约束,再逆序回滚。 +""" + +from __future__ import annotations + +import importlib + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy.exc import IntegrityError + + +def _customer_pre_migration_schema(engine: sa.Engine) -> None: + """创建 f1 客户基础迁移所需的最小历史表。""" + metadata = sa.MetaData() + sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_notice_intakes', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_notice_candidates', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + metadata.create_all(engine) + + +def test_shipping_customer_migrations_upgrade_and_downgrade(): + """三段客户迁移应建立关键约束,并能逆序移除全部新增结构。""" + engine = sa.create_engine('sqlite:///:memory:') + _customer_pre_migration_schema(engine) + modules = [ + importlib.import_module('migrations.versions.f1a2b3c4d5e6_shipping_customer_case_foundation'), + importlib.import_module('migrations.versions.a2c3d4e5f6a7_shipping_customer_imports'), + importlib.import_module('migrations.versions.b3d4e5f6a7b8_shipping_customer_shadow_resolution'), + ] + + with engine.begin() as connection: + operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True})) + original_ops = [module.op for module in modules] + for module in modules: + module.op = operations + try: + for module in modules: + module.upgrade() + + inspector = sa.inspect(connection) + assert { + 'shipping_customers', + 'shipping_customer_identifiers', + 'shipping_cases', + 'shipping_business_sequences', + 'shipping_customer_import_batches', + 'shipping_customer_import_rows', + 'shipping_customer_shadow_resolutions', + } <= set(inspector.get_table_names()) + task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')} + assert {'shipping_case_id', 'customer_resolution_status', 'customer_confirmed_at'} <= task_columns + case_constraints = { + item['name'] for item in inspector.get_unique_constraints('shipping_cases') + } + assert 'uq_shipping_cases_replaces_case_id' in case_constraints + + connection.execute(sa.text( + "INSERT INTO shipping_customers " + "(id, standard_name, short_code, status, created_at, updated_at) " + "VALUES (1, 'Valid', 'WYC', 'active', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" + )) + with pytest.raises(IntegrityError): + with connection.begin_nested(): + connection.execute(sa.text( + "INSERT INTO shipping_customers " + "(id, standard_name, short_code, status, created_at, updated_at) " + "VALUES (2, 'Invalid', 'W1', 'active', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)" + )) + + for module in reversed(modules): + module.downgrade() + remaining = set(sa.inspect(connection).get_table_names()) + assert 'shipping_customers' not in remaining + assert 'shipping_customer_import_batches' not in remaining + assert 'shipping_customer_shadow_resolutions' not in remaining + task_columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_tasks')} + assert 'shipping_case_id' not in task_columns + finally: + for module, original_op in zip(modules, original_ops, strict=True): + module.op = original_op diff --git a/backend/tests/test_shipping_customer_shadow_resolution.py b/backend/tests/test_shipping_customer_shadow_resolution.py new file mode 100644 index 00000000..6dc1b145 --- /dev/null +++ b/backend/tests/test_shipping_customer_shadow_resolution.py @@ -0,0 +1,177 @@ +""" +backend/tests/test_shipping_customer_shadow_resolution.py + +用途:验证客户影子识别的确定性候选、幂等、质量标签和零副作用边界。 +依赖:内存数据库、客户主数据、Candidate/Intake、customer_shadow_resolution。 +逻辑:构造真实 ORM 样本后刷新影子结果,断言业务单客户与业务编号始终不被写入。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + FileAsset, + ShippingCase, + ShippingCustomer, + ShippingCustomerIdentifier, + ShippingCustomerShadowResolution, + ShippingNoticeCandidate, + ShippingNoticeDocument, + ShippingNoticeIntake, + User, +) +from app.services.shipping_notice.document_candidate_persist import persist_documents_and_candidates +from app.services.shipping_notice.notice_upload import NoticeIntakeResult +from app.services.shipping_notice.customer_shadow_resolution import ( + get_shadow_quality_report, + label_shadow_resolution, + refresh_candidate_shadow_resolution, +) + + +def _seed_candidate(*, customer_name: str, sender: str = '') -> ShippingNoticeCandidate: + """创建影子识别所需的最小 Intake、Document 与 Candidate。""" + user = User(username=f'user-{customer_name}-{sender}', email=f'{db.session.query(User).count()}@example.com', role='user') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no=f'FA-{user.id}', owner_user_id=user.id, original_filename='notice.eml', + storage_provider='minio', storage_bucket='test', storage_key=f'notice-{user.id}', + content_hash=f'{user.id:064d}', file_size=1, upload_status='uploaded', lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no=f'SNI-{user.id}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed', + structured_result_json={'email': {'from': sender}}, + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file', + filename='notice.pdf', classification='order_notice', parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + candidate = ShippingNoticeCandidate( + candidate_no=f'SNC-{user.id}', intake_id=intake.id, primary_document_id=document.id, + candidate_key='document:1', validation_status='ready', + structured_result_json={'business_summary': {'customer_name': customer_name, 'lines': [{'sku': 'A', 'quantity': 1}]}}, + ) + db.session.add(candidate) + db.session.flush() + return candidate + + +def _create_customer(name: str, code: str) -> ShippingCustomer: + """创建启用客户并返回 ORM 记录。""" + customer = ShippingCustomer(standard_name=name, short_code=code, status='active') + db.session.add(customer) + db.session.flush() + return customer + + +def test_shadow_resolution_uses_strong_evidence_without_binding_case(app): + """完整邮箱可形成唯一候选,但业务单客户和业务编号保持为空。""" + with app.app_context(): + customer = _create_customer('无锡宇辰有限公司', 'WYC') + db.session.add(ShippingCustomerIdentifier( + customer_id=customer.id, identifier_type='email', raw_value='buyer@wyc.example.com', + normalized_value='buyer@wyc.example.com', status='approved', source='manual', auto_match_allowed=True, + )) + candidate = _seed_candidate(customer_name='不稳定解析名称', sender='Buyer ') + case = ShippingCase(case_no='CASE-SHADOW-1') + db.session.add(case) + db.session.flush() + + resolution = refresh_candidate_shadow_resolution(candidate) + db.session.commit() + + assert resolution.status == 'unique_candidate' + assert resolution.top_customer_id == customer.id + assert resolution.top_score == 100.0 + assert case.customer_id is None + assert case.business_no is None + assert get_shadow_quality_report()['auto_bound_count'] == 0 + + +def test_shadow_resolution_reports_ambiguous_and_unmatched(app): + """同名客户必须保留歧义,无证据样本必须标记未匹配。""" + with app.app_context(): + _create_customer('ACME', 'ACA') + _create_customer('ACME', 'ACB') + ambiguous = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='ACME')) + unmatched = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='UNKNOWN')) + db.session.commit() + + assert ambiguous.status == 'ambiguous' + assert ambiguous.top_customer_id is None + assert len(ambiguous.candidate_matches_json) == 2 + assert unmatched.status == 'unmatched' + assert unmatched.candidate_matches_json == [] + + +def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app): + """重算复用同一记录;准确率只统计人工标签且不会反向绑定业务。""" + with app.app_context(): + customer = _create_customer('ACME', 'ACM') + candidate = _seed_candidate(customer_name='ACME') + first = refresh_candidate_shadow_resolution(candidate) + first_id = first.id + second = refresh_candidate_shadow_resolution(candidate) + db.session.commit() + assert second.id == first_id + assert db.session.query(ShippingCustomerShadowResolution).count() == 1 + + labeled = label_shadow_resolution(first_id, customer_id=customer.id, actor_id=None) + report = get_shadow_quality_report() + assert labeled['is_correct'] is True + assert report['labeled_count'] == 1 + assert report['correct_count'] == 1 + assert report['accuracy'] == 1.0 + assert report['auto_bound_count'] == 0 + + +def test_shadow_failure_does_not_block_candidate_persistence(app, monkeypatch): + """影子规则异常时 Candidate 主流程仍须创建并可提交。""" + with app.app_context(): + user = User(username='shadow-safe-user', email='shadow-safe@example.com', role='user') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no='FA-SHADOW-SAFE', owner_user_id=user.id, original_filename='notice.txt', + storage_provider='minio', storage_bucket='test', storage_key='shadow-safe', + content_hash='a' * 64, file_size=10, upload_status='uploaded', lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-SHADOW-SAFE', asset_id=asset.id, user_id=user.id, + parser_version='v6', parse_status='parsed', structured_result_json={}, + ) + db.session.add(intake) + db.session.flush() + monkeypatch.setattr( + 'app.services.shipping_notice.customer_shadow_resolution.refresh_candidate_shadow_resolution', + lambda _candidate: (_ for _ in ()).throw(RuntimeError('shadow failure')), + ) + result = NoticeIntakeResult( + filename='notice.txt', source_type='manual', source_file_type='text/plain', + text='Customer: ACME\nPO: PO-1\nSKU: A001 Qty: 1', content_hash='a' * 64, + file_size=10, status='accepted', + ) + + persisted = persist_documents_and_candidates( + intake=intake, + parent_asset=asset, + result=result, + run_duplicate_detection=False, + create_candidates=True, + ) + db.session.commit() + + assert persisted['candidate_count'] == 1 + candidate = db.session.query(ShippingNoticeCandidate).one() + assert candidate.validation_status == 'ready' + shadow = db.session.query(ShippingCustomerShadowResolution).one() + assert shadow.status == 'failed' diff --git a/backend/tests/test_shipping_inventory_connector_migration.py b/backend/tests/test_shipping_inventory_connector_migration.py new file mode 100644 index 00000000..0b7caf5d --- /dev/null +++ b/backend/tests/test_shipping_inventory_connector_migration.py @@ -0,0 +1,35 @@ +""" +backend/tests/test_shipping_inventory_connector_migration.py + +用途:验证库存连接器列重命名迁移的版本链与双向列名。 +依赖:c4d5e6f7a8b9 Alembic 迁移模块、pytest monkeypatch。 +逻辑:拦截 alter_column 调用,确认升级保留数据式重命名且降级可恢复旧列名。 +""" + +from __future__ import annotations + +import importlib +from typing import Any + + +def test_inventory_connector_column_migration_renames_both_directions(monkeypatch): + """迁移应承接当前 head,并仅双向重命名 shipping_tasks 库存连接器列。""" + module = importlib.import_module( + "migrations.versions.c4d5e6f7a8b9_rename_inventory_source_type_to_connector_type" + ) + calls: list[tuple[str, str, dict[str, Any]]] = [] + + def capture_alter_column(table_name: str, column_name: str, **kwargs: Any) -> None: + """记录迁移列变更参数,避免测试依赖具体数据库方言。""" + calls.append((table_name, column_name, kwargs)) + + monkeypatch.setattr(module.op, "alter_column", capture_alter_column) + + module.upgrade() + module.downgrade() + + assert module.down_revision == "b3d4e5f6a7b8" + assert calls[0][0:2] == ("shipping_tasks", "inventory_source_type") + assert calls[0][2]["new_column_name"] == "inventory_connector_type" + assert calls[1][0:2] == ("shipping_tasks", "inventory_connector_type") + assert calls[1][2]["new_column_name"] == "inventory_source_type" diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py index 35233af7..6efdb5e2 100644 --- a/backend/tests/test_shipping_notice_batches.py +++ b/backend/tests/test_shipping_notice_batches.py @@ -11,8 +11,22 @@ import json from datetime import datetime, timedelta from io import BytesIO +import pytest + from app import db -from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, User +from app.models import ( + Agent, + ChatSession, + FileAsset, + Job, + KbJob, + ShippingBatch, + ShippingNoticeDocument, + ShippingNoticeIntake, + ShippingTask, + ShippingTaskEvent, + User, +) from app.core.auth.jwt import issue_local_access_token from app.jobs.context import JobContext from app.jobs.queue import process_next_job @@ -640,7 +654,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path): step_payload_json={ "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "entry_url": "https://s360.dbschenker.com/", "query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"}, } @@ -688,7 +702,7 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli step_payload_json={ "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "entry_url": "https://s360.dbschenker.com/", "query": {"program_group": "Dublin", "program_label": "AWSDU - Prod (JDA)"}, } @@ -761,7 +775,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p assert trigger_path.exists() trigger_text = trigger_path.read_text(encoding="utf-8") assert '"source_code": "DSV360_AWSDU"' in trigger_text - assert '"source_type": "dsv360"' in trigger_text + assert '"connector_type": "dsv360"' in trigger_text def test_inventory_source_rules_cover_dsv360_programs(app): @@ -1075,6 +1089,257 @@ def test_chat_completions_streams_shipping_ui_state(app, client, monkeypatch): assert '"action_buttons"' in body +def test_chat_completions_streams_order_extraction_terminal_ui_state(app, client, monkeypatch): + """事务提交并解绑 ORM 后仍须调用 Dify,并按本轮 Intake 补发权威 Batch UI State。""" + from app.services import dify as dify_module + from app.services.shipping_notice import order_extraction as order_extraction_module + + with app.app_context(): + user = User( + username="shipping_extraction_stream_user", + email="shipping_extraction_stream_user@example.com", + role="user", + status="active", + ) + user.set_password("password") + agent = Agent( + name="货代发货通知 Agent", + agent_code="shipping_notice", + runtime_provider="hybrid", + conversation_mode="task_chat", + dify_api_key="test-dify-key", + api_base_url="http://dify.example/v1", + type="api", + is_active=True, + ) + user.agents.append(agent) + db.session.add_all([user, agent]) + db.session.flush() + session = ChatSession( + session_id="conv-extraction-terminal-ui-state", + user_id=user.id, + agent_id=agent.id, + title="Order extraction", + ) + asset = FileAsset( + asset_no="FA-EXTRACTION-STREAM", + owner_user_id=user.id, + original_filename="orders.eml", + storage_provider="minio", + storage_bucket="test", + storage_key="test/orders.eml", + content_hash="extraction-stream-hash", + file_size=128, + mime_type="message/rfc822", + upload_status="ready", + lifecycle_status="referenced", + ) + batch = ShippingBatch( + batch_no="SB-EXTRACTION-STREAM", + user_id=user.id, + conversation_id=session.session_id, + current_focus_task_no="SN-EXTRACTION-STREAM", + file_count=1, + ) + task = ShippingTask( + task_no="SN-EXTRACTION-STREAM", + batch=batch, + user_id=user.id, + conversation_id=session.session_id, + source_type="email", + process_status="pending_review", + pending_human_reason="rsv_req", + ) + db.session.add_all([session, asset, batch, task]) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no="SNI-EXTRACTION-STREAM", + asset_id=asset.id, + user_id=user.id, + conversation_id=session.session_id, + purpose="shipping_notice", + parse_status="parsed", + parser_version="v6", + order_extraction_status="not_started", + ) + db.session.add(intake) + db.session.commit() + user_id = user.id + agent_id = agent.id + + dify_called = False + original_start_order_extraction = order_extraction_module.start_order_extraction + + def detaching_start_order_extraction(**kwargs): + """模拟生产流开始前原请求 scoped session 已清理,强制暴露 ORM 跨流引用。""" + result = original_start_order_extraction(**kwargs) + db.session.expunge_all() + return result + + def fake_stream_chat(*args, **kwargs): + nonlocal dify_called + dify_called = True + # 模拟 Dify submit_order_extraction Tool 在 terminal 前提交消费关系。 + with app.app_context(): + intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-STREAM").one() + batch = ShippingBatch.query.filter_by(batch_no="SB-EXTRACTION-STREAM").one() + intake.parse_status = "consumed" + intake.order_extraction_status = "completed" + intake.consumed_at = datetime.utcnow() + intake.consumed_batch_id = batch.id + db.session.commit() + yield 'data: {"event":"message","answer":"已创建发货任务。"}\n\n' + yield 'data: {"event":"workflow_finished","answer":"","conversation_id":"dify-extraction-conv"}\n\n' + + monkeypatch.setattr(order_extraction_module, "start_order_extraction", detaching_start_order_extraction) + monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat)) + + res = client.post( + "/api/chat/completions", + headers={ + "X-User-Id": str(user_id), + "X-Username": "shipping_extraction_stream_user", + "X-Role": "user", + "Content-Type": "application/json", + }, + json={ + "agent_id": agent_id, + "query": "请解析邮件并自动建单", + "conversation_id": "conv-extraction-terminal-ui-state", + "shipping_intake_nos": ["SNI-EXTRACTION-STREAM"], + }, + ) + + body = res.get_data(as_text=True) + assert res.status_code == 200 + # 关键断言:prepare_stream 提交事务并解绑 ORM 后,relay 首帧仍可发送且 Dify generator 必须被迭代。 + assert dify_called is True + assert '"event": "session_created"' in body + assert '"event": "message", "answer": "已创建发货任务。"' in body + assert '"event": "shipping_ui_state"' in body + assert '"source": "order_extraction"' in body + assert '"batch_no": "SB-EXTRACTION-STREAM"' in body + assert '"task_no": "SN-EXTRACTION-STREAM"' in body + assert body.index('"event": "workflow_finished"') < body.rindex('"event": "shipping_ui_state"') + + +@pytest.mark.parametrize('failure_mode', ['sse_error', 'relay_exception']) +def test_chat_completions_closes_order_extraction_on_upstream_error( + app, + client, + monkeypatch, + failure_mode, +): + """Dify SSE error 或 relay 异常都必须即时收口,不能等待五分钟超时。""" + from app.services import dify as dify_module + + with app.app_context(): + user = User( + username="shipping_extraction_error_user", + email="shipping_extraction_error_user@example.com", + role="user", + status="active", + ) + user.set_password("password") + agent = Agent( + name="货代发货通知 Agent", + agent_code="shipping_notice", + runtime_provider="hybrid", + conversation_mode="task_chat", + dify_api_key="test-dify-key", + api_base_url="http://dify.example/v1", + type="api", + is_active=True, + ) + user.agents.append(agent) + db.session.add_all([user, agent]) + db.session.flush() + session = ChatSession( + session_id="conv-extraction-upstream-error", + user_id=user.id, + agent_id=agent.id, + title="Order extraction error", + ) + asset = FileAsset( + asset_no="FA-EXTRACTION-ERROR", + owner_user_id=user.id, + original_filename="orders-error.eml", + storage_provider="minio", + storage_bucket="test", + storage_key="test/orders-error.eml", + content_hash="extraction-error-hash", + file_size=128, + mime_type="message/rfc822", + upload_status="ready", + lifecycle_status="referenced", + ) + db.session.add_all([session, asset]) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no="SNI-EXTRACTION-ERROR", + asset_id=asset.id, + user_id=user.id, + conversation_id=session.session_id, + purpose="shipping_notice", + parse_status="parsed", + parser_version="v6", + order_extraction_status="not_started", + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=intake.id, + asset_id=asset.id, + document_type="attachment", + attachment_key="orders-error.pdf", + filename="orders-error.pdf", + content_hash="extraction-error-document-hash", + classification="order_notice", + parse_status="parsed", + extracted_text="SKU ERROR-SKU QTY 1", + ) + db.session.add(document) + db.session.commit() + user_id = user.id + agent_id = agent.id + + def fake_stream_chat(*args, **kwargs): + """模拟 Dify 主动返回 error,或流迭代期间直接抛出异常。""" + if failure_mode == 'relay_exception': + raise RuntimeError('Dify connection reset') + yield 'data: {"event":"error","message":"Dify unavailable"}\n\n' + + monkeypatch.setattr(dify_module.DifyService, "stream_chat", staticmethod(fake_stream_chat)) + res = client.post( + "/api/chat/completions", + headers={ + "X-User-Id": str(user_id), + "X-Username": "shipping_extraction_error_user", + "X-Role": "user", + "Content-Type": "application/json", + }, + json={ + "agent_id": agent_id, + "query": "请解析邮件并自动建单", + "conversation_id": "conv-extraction-upstream-error", + "shipping_intake_nos": ["SNI-EXTRACTION-ERROR"], + }, + ) + + body = res.get_data(as_text=True) + assert res.status_code == 200 + assert '"event": "error"' in body + with app.app_context(): + intake = ShippingNoticeIntake.query.filter_by(intake_no="SNI-EXTRACTION-ERROR").one() + document = ShippingNoticeDocument.query.filter_by(intake_id=intake.id).one() + assert intake.order_extraction_status == "failed" + assert intake.order_extraction_error_code == "SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED" + assert intake.order_extraction_error_message == ( + "Dify connection reset" if failure_mode == 'relay_exception' else "Dify unavailable" + ) + assert document.order_extraction_status == "failed" + + def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client): """同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。""" headers = _workspace_headers(app) diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py new file mode 100644 index 00000000..0a2b5788 --- /dev/null +++ b/backend/tests/test_shipping_notice_business_case.py @@ -0,0 +1,149 @@ +""" +backend/tests/test_shipping_notice_business_case.py + +用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。 +依赖:app fixture、ShippingTask/ShippingCase、business_case_service。 +逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。 +""" + +from app import db +from app.models import ShippingCase, ShippingTask +from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task +from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task + + +def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingTask: + """构造最小货代任务,供业务单关系断言使用。""" + return ShippingTask( + task_no=task_no, + shipping_case_id=case_id, + supersedes_task_id=supersedes_task_id, + source_type='manual', + process_status='created', + ) + + +def test_normal_and_force_create_use_different_cases(app): + """普通建单和强制新建必须各自创建独立业务单。""" + with app.app_context(): + normal = resolve_shipping_case_for_new_task(created_by_id=None) + forced = resolve_shipping_case_for_new_task( + duplicate_resolution_type='force_create', + created_by_id=None, + ) + assert normal.id != forced.id + assert normal.business_no is None + assert forced.business_no is None + + +def test_revision_inherits_existing_parent_case(app): + """修订任务必须继承父任务已有业务单,不能创建新业务单。""" + with app.app_context(): + case = resolve_shipping_case_for_new_task(created_by_id=None) + parent = _task('SN-CASE-PARENT-1', case_id=case.id) + db.session.add(parent) + db.session.flush() + + resolved = resolve_shipping_case_for_new_task( + supersedes_task_id=parent.id, + duplicate_resolution_type='revision', + ) + assert resolved.id == case.id + assert ShippingCase.query.count() == 1 + + +def test_revision_backfills_case_for_legacy_parent(app): + """历史父任务没有业务单时,首次修订应补建并复用同一业务单。""" + with app.app_context(): + parent = _task('SN-CASE-LEGACY-1') + db.session.add(parent) + db.session.flush() + + resolved = resolve_shipping_case_for_new_task( + supersedes_task_id=parent.id, + duplicate_resolution_type='revision', + ) + db.session.flush() + assert parent.shipping_case_id == resolved.id + assert ShippingCase.query.count() == 1 + + +def test_revision_chain_reuses_root_case(app): + """连续修订版本必须沿用同一业务单聚合。""" + with app.app_context(): + case = resolve_shipping_case_for_new_task(created_by_id=None) + parent = _task('SN-CASE-CHAIN-1', case_id=case.id) + db.session.add(parent) + db.session.flush() + revision_case = resolve_shipping_case_for_new_task( + supersedes_task_id=parent.id, + duplicate_resolution_type='revision', + ) + revision = _task('SN-CASE-CHAIN-2', case_id=revision_case.id, supersedes_task_id=parent.id) + db.session.add(revision) + db.session.flush() + + next_case = resolve_shipping_case_for_new_task( + supersedes_task_id=revision.id, + duplicate_resolution_type='revision', + ) + assert next_case.id == case.id + assert ShippingCase.query.count() == 1 + + +def test_create_task_assigns_case_and_serializes_it(app): + """真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。""" + with app.app_context(): + result = create_task({'source_type': 'manual', 'raw_content': 'customer notice'}) + task = ShippingTask.query.filter_by(task_no=result['task_id']).one() + assert task.shipping_case_id is not None + assert result['data']['shipping_case_id'] == task.shipping_case_id + assert result['data']['case_no'] == task.shipping_case.case_no + assert result['data']['business_no'] is None + + +def test_batch_revision_inherits_parent_case(app): + """真实批量建单路径中的 revision 必须继承父任务业务单。""" + with app.app_context(): + case = resolve_shipping_case_for_new_task(created_by_id=None) + parent = _task('SN-CASE-BATCH-PARENT', case_id=case.id) + db.session.add(parent) + db.session.commit() + + result = create_batch_tasks({ + 'notice_items': [{ + 'source_type': 'manual', + 'raw_text': 'revision notice', + 'document_version': 2, + 'supersedes_task_id': parent.id, + 'duplicate_resolution_type': 'revision', + }], + 'defer_parse': True, + }) + task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one() + assert task.shipping_case_id == case.id + assert task.supersedes_task_id == parent.id + assert ShippingCase.query.count() == 1 + + +def test_batch_force_create_uses_new_case(app): + """真实批量建单路径中的 force_create 必须创建独立业务单。""" + with app.app_context(): + original_case = resolve_shipping_case_for_new_task(created_by_id=None) + original = _task('SN-CASE-FORCE-SOURCE', case_id=original_case.id) + db.session.add(original) + db.session.commit() + + result = create_batch_tasks({ + 'notice_items': [{ + 'source_type': 'manual', + 'raw_text': 'forced notice', + 'duplicate_source_task_id': original.id, + 'duplicate_resolution_type': 'force_create', + }], + 'defer_parse': True, + }) + task = ShippingTask.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one() + assert task.shipping_case_id != original_case.id + assert task.duplicate_source_task_id == original.id + assert ShippingCase.query.count() == 2 diff --git a/backend/tests/test_shipping_notice_business_dedup.py b/backend/tests/test_shipping_notice_business_dedup.py index 7e395729..0bf064d2 100644 --- a/backend/tests/test_shipping_notice_business_dedup.py +++ b/backend/tests/test_shipping_notice_business_dedup.py @@ -855,11 +855,11 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a assert candidate.content_fingerprint == revision['content_fingerprint'] assert candidate.content_fingerprint != content['fingerprint'] - hub_changed = { + source_type_changed = { **base, - 'lines': [{**base['lines'][0], 'hub_code': 'DUB'}], + 'lines': [{**base['lines'][0], 'source_type': 'DBS DUB'}], } - assert build_content_fingerprint(hub_changed)['fingerprint'] != content['fingerprint'] + assert build_content_fingerprint(source_type_changed)['fingerprint'] != content['fingerprint'] header_date_changed = {**base, 'required_date': '2026-07-20'} assert build_content_fingerprint(header_date_changed)['fingerprint'] != content['fingerprint'] diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index ae639320..92675bad 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -151,8 +151,8 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD assert rows[0]['source_type'] == 'VMI-FRA01' assert rows[0]['customer_sku'] == 'TEMP-S000218922' assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001' - assert rows[0]['hub_code'] == 'FRA01' - assert rows[2]['hub_code'] == 'DUB' + assert 'hub_code' not in rows[0] + assert 'hub_code' not in rows[2] fused = merge_attachment_candidate( attachment_summary={ @@ -168,7 +168,7 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD assert not fused['conflicts'] assert line['source_type'] == 'VMI-FRA01' assert line['customer_sku'] == 'TEMP-S000218922' - assert line['hub_code'] == 'FRA01' + assert 'hub_code' not in line conflict = merge_attachment_candidate( attachment_summary={ diff --git a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py index 915dbb5b..5dedc37b 100644 --- a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py +++ b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py @@ -1,4 +1,10 @@ -"""shipping_notice 库存快照 TTL 复用测试。""" +""" +backend/tests/test_shipping_notice_inventory_snapshot_reuse.py + +用途:验证库存连接器身份下的快照 TTL、动态库位与任务复用规则。 +依赖:ShippingTask、inventory_snapshot_store、inventory_sources、测试 Excel 夹具。 +逻辑:构造稳定 inventory_connector_type 身份并检查快照查找、绑定和过期行为。 +""" from datetime import datetime, timedelta from pathlib import Path @@ -27,7 +33,7 @@ def _task_with_inventory_source( task_no: str, *, source_code: str, - source_type: str | None = None, + connector_type: str | None = None, site_id: str | None = None, warehouse_id: str = "", ) -> ShippingTask: @@ -42,8 +48,8 @@ def _task_with_inventory_source( task.inventory_site_id = site_id if warehouse_id: task.inventory_warehouse_id = warehouse_id - if source_type: - task.inventory_source_type = source_type + if connector_type: + task.inventory_connector_type = connector_type return task @@ -90,7 +96,7 @@ def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path): task = _task_with_inventory_source( "SN-SNAPSHOT-SITE", source_code="DSV360_AWSBI_BYAWSATL01", - source_type="dsv360", + connector_type="dsv360", site_id="AWSBI", warehouse_id="BYAWSATL01", ) @@ -169,7 +175,7 @@ def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path): task = _task_with_inventory_source( "SN-SNAPSHOT-MISMATCH", source_code="DSV360_AWSAMS", - source_type="dsv360", + connector_type="dsv360", site_id="AWSAMS", ) db.session.add(task) @@ -209,7 +215,7 @@ def test_link_snapshot_writes_audit_fields(app, tmp_path): task = _task_with_inventory_source( "SN-SNAPSHOT-LINK", source_code="DSV360_AWSDU", - source_type="dsv360", + connector_type="dsv360", site_id="AWSDU", ) db.session.add(task) diff --git a/backend/tests/test_shipping_notice_inventory_source_gate.py b/backend/tests/test_shipping_notice_inventory_source_gate.py index 01034add..7b998f7e 100644 --- a/backend/tests/test_shipping_notice_inventory_source_gate.py +++ b/backend/tests/test_shipping_notice_inventory_source_gate.py @@ -20,6 +20,7 @@ from app.services.shipping_notice.inventory_source_gate import is_inventory_sour from app.services.shipping_notice.inventory_source_rules import ( adjudicate_inventory_source, confirm_inventory_source_by_code, + extract_destination_candidates, ) from app.services.shipping_notice.inventory_workflow import ( apply_inventory_mapping, @@ -466,6 +467,35 @@ def test_crane_auto_adjudication_resolves_warehouse_from_alias(app): assert adjudication.warehouse_id == "TZR2" +@pytest.mark.inventory_source_gate +def test_line_source_type_matches_alias_without_using_task_source_type(app): + """orders[].lines[].source_type 应命中 match_aliases,Task.source_type 接入来源不得参与裁决。""" + with app.app_context(): + task = ShippingTask( + task_no="SN-GATE-LINE-SOURCE-TYPE", + source_type="TZR2", + process_status="parsed", + lines_json=[ + { + "sku": "A001", + "qty": 1, + "reservation_id": "R-100", + "source_type": "DBS DUB", + }, + ], + ) + db.session.add(task) + db.session.commit() + + candidates = extract_destination_candidates(task) + adjudication = adjudicate_inventory_source(task) + + assert "DBS DUB" in candidates + assert "TZR2" not in candidates + assert adjudication.status == "resolved" + assert adjudication.source_code == "DSV360_AWSDU" + + @pytest.mark.inventory_source_gate def test_crane_user_confirm_and_gate_stable(app): """Crane 人工确认后应写入完整身份并通过门禁。""" diff --git a/backend/tests/test_shipping_notice_inventory_sources_config.py b/backend/tests/test_shipping_notice_inventory_sources_config.py index d8fe37f7..5839bd6d 100644 --- a/backend/tests/test_shipping_notice_inventory_sources_config.py +++ b/backend/tests/test_shipping_notice_inventory_sources_config.py @@ -1,4 +1,10 @@ -"""shipping_notice inventory_sources YAML/JSON 配置加载与校验测试。""" +""" +backend/tests/test_shipping_notice_inventory_sources_config.py + +用途:验证库存连接器 YAML/JSON 配置加载、校验与缓存刷新。 +依赖:inventory_sources、pytest tmp_path/app 夹具。 +逻辑:以 connector_type 配置样本覆盖 DSV/Crane 身份约束及 worker 兼容 query。 +""" from pathlib import Path @@ -19,7 +25,7 @@ def test_inventory_sources_yaml_loads(app): reload_inventory_sources_config() source = get_inventory_source("DSV360_AWSDU") assert source is not None - assert source["source_type"] == "dsv360" + assert source["connector_type"] == "dsv360" assert source["site_id"] == "AWSDU" assert source["warehouse_id"] == "AWSDU" assert source["query"]["program_label"] @@ -64,8 +70,8 @@ def test_duplicate_source_code_raises(app, tmp_path): { "version": 1, "sources": [ - {"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []}, - {"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []} + {"source_code": "X1", "enabled": true, "connector_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []}, + {"source_code": "X1", "enabled": true, "connector_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []} ] } """, @@ -86,7 +92,7 @@ version: 1 sources: - source_code: DSV360_BAD enabled: true - source_type: dsv360 + connector_type: dsv360 warehouse_id: AWSBI entry_url: http://x navigation: {} @@ -109,7 +115,7 @@ version: 1 sources: - source_code: DSV360_BAD enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: AWSBI entry_url: http://x navigation: {} @@ -129,7 +135,7 @@ def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app): reload_inventory_sources_config() payload = build_rpa_inventory_source("CRANE") assert payload is not None - assert payload["source_type"] == "crane_footprint" + assert payload["connector_type"] == "crane_footprint" assert payload["site_id"] == "CRANE" assert payload["warehouse_id"] == "" assert payload["warehouse_resolution"] == "alias_match" @@ -163,7 +169,7 @@ version: 1 sources: - source_code: CACHE_TEST enabled: true - source_type: dsv360 + connector_type: dsv360 site_id: S1 warehouse_id: W1 entry_url: http://example.com diff --git a/backend/tests/test_shipping_notice_openapi_contract.py b/backend/tests/test_shipping_notice_openapi_contract.py new file mode 100644 index 00000000..69f3fe10 --- /dev/null +++ b/backend/tests/test_shipping_notice_openapi_contract.py @@ -0,0 +1,77 @@ +""" +tests/test_shipping_notice_openapi_contract.py + +用途:锁定发货通知订单行路由线索与库存连接器 OpenAPI 命名契约。 +依赖:Flask 测试 client、静态 Dify OpenAPI JSON。 +逻辑:分别校验动态 builder 输出与脚本生成的静态快照,防止两者发生漂移。 +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + + +def _assert_connector_contract(spec: dict[str, Any]) -> None: + """ + 校验订单行与库存连接器的字段边界。 + + 核心逻辑:订单行保留可选 source_type 且不暴露 hub_code;任务状态说明使用 + inventory_connector_type,并拒绝旧 inventory_source_type 命名。 + + Args: + spec: 动态接口或静态快照读取出的 OpenAPI 对象。 + + Returns: + None;契约不符时由 pytest assertion 报错。 + """ + order_schema = spec["paths"]["/tools/submit_order_extraction"]["post"]["requestBody"]["content"][ + "application/json" + ]["schema"]["properties"]["orders"]["items"] + line_properties = order_schema["properties"]["lines"]["items"]["properties"] + assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type"} + assert "可选订单路由线索" in line_properties["source_type"]["description"] + + status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"] + assert "inventory_connector_type" in status_description + assert "inventory_source_type" not in status_description + + confirm_description = spec["paths"]["/tools/confirm_inventory_source"]["post"]["description"] + assert "connector_type" in confirm_description + assert "source_code、source_type" not in confirm_description + + +def test_dynamic_openapi_uses_connector_contract(app, client) -> None: + """ + 校验公开 OpenAPI 接口使用新的连接器命名。 + + 核心逻辑:通过 Flask 路由获取 builder 实时结果,再复用统一契约断言。 + + Args: + app: pytest Flask 应用 fixture。 + client: pytest Flask 测试客户端 fixture。 + + Returns: + None。 + """ + app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com" + response = client.get("/api/shipping-notice/tools/openapi.json") + + assert response.status_code == 200 + _assert_connector_contract(response.get_json()) + + +def test_static_openapi_uses_connector_contract() -> None: + """ + 校验仓库脚本生成的 Dify 静态快照与动态契约一致。 + + 核心逻辑:读取 docs/openapi 下的 JSON,并复用统一契约断言。 + + Returns: + None。 + """ + spec_path = Path(__file__).resolve().parents[2] / "docs" / "openapi" / "shipping_notice_tools.dify.json" + spec = json.loads(spec_path.read_text(encoding="utf-8")) + + _assert_connector_contract(spec) diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index cfbb0bb7..3d3bc747 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -1,36 +1,59 @@ """ backend/tests/test_shipping_notice_order_extraction.py -用途:验证点击发送后的 Dify 完整订单抽取、订单级 Candidate、自动建单和安全门禁。 +用途:验证点击发送后的 Dify 完整订单抽取、订单级 Candidate、自动建单、失败收口和安全门禁。 依赖:agent_runtime_context builder、order_extraction、Shipping Notice 模型与 pytest Flask fixture。 -逻辑:构造一封已预处理邮件及单个附件,模拟 Chatflow 读取快照并提交多个 orders[],断言部分成功、幂等与来源漂移。 +逻辑:构造一封已预处理邮件及单个附件,模拟 Chatflow 请求登记、读取快照、提交多个 orders[] 与 terminal, + 断言部分成功、幂等、请求隔离、失败和超时收口。 """ from __future__ import annotations import json +from datetime import datetime, timedelta import pytest from app import db -from app.core.errors import ConflictError +from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( Agent, + ChatLog, ChatSession, FileAsset, + ShippingBatch, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, + ShippingTaskEvent, User, ) from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify +from app.services.agent_registry.handlers.base import ChatStreamContext +from app.services.agent_registry.handlers.bootstrap import load_handlers +from app.services.agent_registry.handlers.registry import get_handler +from app.services.chat.executors import stream_chat_via_executor +from app.services.chat.log_service import merge_chat_log_payload +from app.services.chat.stream_relay import iter_handler_preface_sse from app.services.shipping_notice.order_extraction import ( EXTRACTION_CONTRACT_VERSION, + ORDER_EXTRACTION_FAILED_CODE, + ORDER_EXTRACTION_INCOMPLETE_MESSAGE, + ORDER_EXTRACTION_TIMEOUT_MESSAGE, + expire_stale_order_extractions, + finalize_order_extraction_failure, get_order_extraction_context, + get_order_extraction_state, + start_order_extraction, submit_order_extraction, ) +from app.services.shipping_notice.open_existing_reservation_backfill import ( + backfill_exact_file_open_existing_reservations, +) +from app.services.shipping_notice.intake_service import get_intake_statuses, list_active_intakes_for_conversation from app.services.shipping_notice.progress_workflow import auto_progress +from app.services.shipping_notice.query_service import resolve_order_extraction_ui_target from app.services.shipping_notice.task_workflow import update_notice_line @@ -126,7 +149,7 @@ def _order( """构造符合 Chatflow v1 契约的单个订单结果。""" line = {'sku': sku, 'qty': qty} if include_process_fields: - line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin', 'hub_code': 'DUB'}) + line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin'}) return { 'source_intake_no': intake_no, 'primary_document_id': document_id, @@ -144,6 +167,504 @@ def _order( } +def _add_extraction_intake( + *, + user: User, + session: ChatSession, + suffix: str, +) -> tuple[ShippingNoticeIntake, ShippingNoticeDocument]: + """为隔离测试补充指定用户和会话下的已预处理 Intake/Document。""" + normalized = suffix.upper() + asset = FileAsset( + asset_no=f'FA-ORDER-EXTRACTION-{normalized}', + owner_user_id=int(user.id), + original_filename=f'orders-{suffix.lower()}.eml', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{user.id}/orders-{suffix.lower()}.eml', + content_hash=f'order-extraction-parent-{suffix.lower()}', + file_size=128, + mime_type='message/rfc822', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no=f'SNI-ORDER-EXTRACTION-{normalized}', + asset_id=int(asset.id), + user_id=int(user.id), + conversation_id=session.session_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + order_extraction_status='not_started', + ) + db.session.add(intake) + db.session.flush() + document = ShippingNoticeDocument( + intake_id=int(intake.id), + asset_id=int(asset.id), + document_type='attachment', + attachment_key=f'orders-{suffix.lower()}.pdf', + filename=f'orders-{suffix.lower()}.pdf', + content_hash=f'order-extraction-document-{suffix.lower()}', + classification='order_notice', + parse_status='parsed', + extracted_text=f'SKU SKU-{normalized} QTY 1', + ) + db.session.add(document) + db.session.commit() + return intake, document + + +def _shipping_handler_context( + *, + user: User, + session: ChatSession, + intake_no: str, + request_id: str, +) -> ChatStreamContext: + """ + 构造带固定订单抽取能力契约的 Shipping Handler 上下文。 + + Returns: + 可直接传给 prepare_stream 和 terminal hook 的 ChatStreamContext。 + """ + agent = db.session.get(Agent, int(session.agent_id)) + assert agent is not None + return ChatStreamContext( + query='extract orders', + display_query='extract orders', + user=user, + agent=agent, + session=session, + external_conversation_id=None, + request_id=request_id, + adapter_hints={ + 'shipping_notice': { + 'intake_nos': [intake_no], + 'capability': 'order_extraction', + 'contract_version': EXTRACTION_CONTRACT_VERSION, + }, + }, + ) + + +def test_order_extraction_runtime_identity_requires_request_and_shipping_session(app): + """订单抽取 Tool 必须使用非空请求号,且会话必须属于货代 Agent。""" + with app.app_context(): + user, _session, _intake, _document, runtime_context = _seed_extraction_input() + missing_request = json.loads(runtime_context) + missing_request['platform'].pop('request_id', None) + + with pytest.raises(ValidationError) as missing_error: + get_order_extraction_context({'agent_runtime_context': missing_request}) + assert missing_error.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID' + + other_agent = Agent(name='Other Agent', agent_code='other_agent') + db.session.add(other_agent) + db.session.flush() + other_session = ChatSession( + session_id='non-shipping-order-extraction-session', + user_id=int(user.id), + agent_id=int(other_agent.id), + title='Other agent session', + ) + db.session.add(other_session) + db.session.commit() + wrong_session = json.loads(runtime_context) + wrong_session['platform']['session_id'] = other_session.session_id + + with pytest.raises(NotFoundError) as session_error: + get_order_extraction_context({'agent_runtime_context': wrong_session}) + assert session_error.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID' + + +def test_order_extraction_terminal_closes_failed_and_unsubmitted_turns(app): + """Dify 失败或成功结束但未提交 orders[] 时,Intake/Document 都必须离开 extracting。""" + with app.app_context(): + user, session, intake, document, _runtime_context = _seed_extraction_input() + load_handlers() + handler = get_handler('shipping_notice') + assert handler is not None + + failed_ctx = _shipping_handler_context( + user=user, + session=session, + intake_no=intake.intake_no, + request_id='req-terminal-failed', + ) + handler.prepare_stream(failed_ctx) + db.session.refresh(intake) + db.session.refresh(document) + started_at = (intake.structured_result_json or {})['order_extraction_snapshot']['created_at'] + # Hybrid executor 可能重复调用 prepare_stream;同一 request 不得刷新超时起点。 + handler.prepare_stream(failed_ctx) + db.session.refresh(intake) + assert (intake.structured_result_json or {})['order_extraction_snapshot']['created_at'] == started_at + assert intake.order_extraction_status == 'extracting' + assert document.order_extraction_status == 'extracting' + preface_lines = list(handler.iter_preface_sse_lines(failed_ctx)) + assert len(preface_lines) == 1 + preface_event = json.loads(preface_lines[0].removeprefix('data: ').strip()) + assert preface_event == { + 'event': 'shipping_order_extraction_state', + 'conversation_id': session.session_id, + 'status': 'extracting', + 'phase': 'llm_extraction', + 'message': '正在识别邮件及附件中的订单', + 'created_count': 0, + 'opened_existing_count': 0, + 'pending_count': 0, + 'non_shipping_count': 0, + 'created_with_missing_fields_count': 0, + 'batch_no': None, + 'terminal': False, + } + + lines = list(handler.on_upstream_terminal_event(failed_ctx, { + 'event': 'workflow_finished', + 'data': {'status': 'failed', 'error': '订单抽取节点执行失败'}, + })) + assert len(lines) == 1 + failed_event = json.loads(lines[0].removeprefix('data: ').strip()) + assert failed_event['event'] == 'shipping_order_extraction_state' + assert failed_event['status'] == 'failed' + assert failed_event['phase'] == 'failed' + assert failed_event['message'] == '订单抽取节点执行失败' + assert failed_event['terminal'] is True + db.session.refresh(intake) + db.session.refresh(document) + assert intake.order_extraction_status == 'failed' + assert intake.order_extraction_error_code == ORDER_EXTRACTION_FAILED_CODE + assert intake.order_extraction_error_message == '订单抽取节点执行失败' + assert document.order_extraction_status == 'failed' + + success_ctx = _shipping_handler_context( + user=user, + session=session, + intake_no=intake.intake_no, + request_id='req-terminal-unsubmitted', + ) + handler.prepare_stream(success_ctx) + unsubmitted_lines = list(handler.on_upstream_terminal_event(success_ctx, { + 'event': 'workflow_finished', + 'data': {'status': 'succeeded'}, + })) + assert len(unsubmitted_lines) == 1 + unsubmitted_event = json.loads(unsubmitted_lines[0].removeprefix('data: ').strip()) + assert unsubmitted_event['event'] == 'shipping_order_extraction_state' + assert unsubmitted_event['status'] == 'failed' + assert unsubmitted_event['message'] == ORDER_EXTRACTION_INCOMPLETE_MESSAGE + db.session.refresh(intake) + assert intake.order_extraction_status == 'failed' + assert intake.order_extraction_error_message == ORDER_EXTRACTION_INCOMPLETE_MESSAGE + + +def test_executor_prepare_exposes_extracting_preface_before_upstream_iteration(app): + """真实 executor 入口必须先登记 extracting,preface 才能在 Dify 首帧前显示进度。""" + with app.app_context(): + user, session, intake, _document, _runtime_context = _seed_extraction_input() + load_handlers() + ctx = _shipping_handler_context( + user=user, + session=session, + intake_no=intake.intake_no, + request_id='req-preface-ordering', + ) + + upstream_generator = stream_chat_via_executor(ctx) + lines = list(iter_handler_preface_sse(ctx, emitted_keys=set())) + + assert upstream_generator is not None + assert len(lines) == 1 + event = json.loads(lines[0].removeprefix('data: ').strip()) + assert event['event'] == 'shipping_order_extraction_state' + assert event['status'] == 'extracting' + assert event['terminal'] is False + + +def test_order_extraction_failure_is_request_fenced_and_idempotent(app): + """旧 terminal 不得覆盖新请求,当前 terminal 只能收口一次。""" + with app.app_context(): + user, session, intake, document, _runtime_context = _seed_extraction_input() + start_order_extraction( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-old', + ) + start_order_extraction( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-new', + ) + db.session.refresh(intake) + snapshot = (intake.structured_result_json or {})['order_extraction_snapshot'] + assert snapshot['request_id'] == 'req-new' + assert 'hash' not in snapshot + + assert finalize_order_extraction_failure( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-old', + ) == 0 + db.session.refresh(intake) + assert intake.order_extraction_status == 'extracting' + assert finalize_order_extraction_failure( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-new', + ) == 1 + assert finalize_order_extraction_failure( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-new', + ) == 0 + db.session.refresh(document) + assert document.order_extraction_status == 'failed' + + +def test_order_extraction_state_is_request_fenced_and_reads_submission_facts(app): + """状态投影只读取当前请求,并从 submission.result 返回真实计数。""" + with app.app_context(): + user, session, intake, document, runtime_context = _seed_extraction_input() + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + extracting = get_order_extraction_state( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-order-extraction-001', + ) + assert extracting['status'] == 'extracting' + assert extracting['terminal'] is False + assert extracting['created_count'] == 0 + + with pytest.raises(ConflictError) as old_request: + get_order_extraction_state( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-stale', + ) + assert old_request.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING' + + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [ + _order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000011', + sku='SKU-STATE', + qty=2, + include_process_fields=False, + ), + ], + }) + completed = get_order_extraction_state( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-order-extraction-001', + ) + assert completed['status'] == 'completed' + assert completed['phase'] == 'result_persisted' + assert completed['terminal'] is True + assert completed['created_count'] == len(result['created']) == 1 + assert completed['created_with_missing_fields_count'] == 1 + assert completed['batch_no'] == result['batch_no'] + assert completed['message'] == result['message'] + + +def test_order_extraction_state_reports_mixed_intake_terminals_as_partial(app): + """同一请求多个 Intake 一成一败时必须报告部分完成,不能误报为全部失败。""" + with app.app_context(): + user, session, intake, _document, _runtime_context = _seed_extraction_input() + other_intake, _other_document = _add_extraction_intake( + user=user, + session=session, + suffix='MIXED', + ) + start_order_extraction( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no, other_intake.intake_no], + request_id='req-mixed-terminals', + ) + intake.order_extraction_status = 'completed' + other_intake.order_extraction_status = 'failed' + other_intake.order_extraction_error_message = '第二封邮件识别失败' + db.session.commit() + + state = get_order_extraction_state( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no, other_intake.intake_no], + request_id='req-mixed-terminals', + ) + + assert state['status'] == 'partially_completed' + assert state['phase'] == 'result_persisted' + assert state['terminal'] is True + + +def test_order_extraction_timeout_closes_only_stale_requests(app): + """状态读取兜底只回收超过配置时限的 extracting,并同步 Document。""" + with app.app_context(): + user, session, intake, document, _runtime_context = _seed_extraction_input() + start_order_extraction( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-timeout', + ) + db.session.refresh(intake) + started_at = datetime.fromisoformat( + (intake.structured_result_json or {})['order_extraction_snapshot']['created_at'] + ) + assert expire_stale_order_extractions( + user_id=int(user.id), + intake_nos=[intake.intake_no], + timeout_seconds=300, + now=started_at + timedelta(seconds=299), + ) == 0 + db.session.refresh(intake) + assert intake.order_extraction_status == 'extracting' + + structured = dict(intake.structured_result_json or {}) + snapshot = dict(structured['order_extraction_snapshot']) + snapshot['created_at'] = (datetime.utcnow() - timedelta(seconds=301)).isoformat() + structured['order_extraction_snapshot'] = snapshot + intake.structured_result_json = structured + db.session.commit() + app.config['SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS'] = 300 + statuses = get_intake_statuses(user_id=int(user.id), intake_nos=[intake.intake_no]) + assert statuses[0]['order_extraction_status'] == 'failed' + db.session.refresh(intake) + db.session.refresh(document) + assert intake.order_extraction_status == 'failed' + assert intake.order_extraction_error_code == ORDER_EXTRACTION_FAILED_CODE + assert intake.order_extraction_error_message == ORDER_EXTRACTION_TIMEOUT_MESSAGE + assert document.order_extraction_status == 'failed' + assert expire_stale_order_extractions( + user_id=int(user.id), + intake_nos=[intake.intake_no], + timeout_seconds=300, + now=started_at + timedelta(seconds=600), + ) == 0 + + +def test_active_intake_read_expires_only_current_user_and_conversation(app): + """会话恢复读取不得回收同用户其他会话或其他用户的超时抽取。""" + with app.app_context(): + user, session, intake, _document, _runtime_context = _seed_extraction_input() + agent = db.session.get(Agent, int(session.agent_id)) + assert agent is not None + other_session = ChatSession( + session_id='shipping-order-extraction-other-session', + user_id=int(user.id), + agent_id=int(agent.id), + title='Other shipping session', + ) + other_user = User( + username='order-extraction-other-user', + email='order-extraction-other-user@example.com', + password_hash='x', + ) + db.session.add_all([other_session, other_user]) + db.session.flush() + other_user_session = ChatSession( + session_id='shipping-order-extraction-other-user-session', + user_id=int(other_user.id), + agent_id=int(agent.id), + title='Other user shipping session', + ) + db.session.add(other_user_session) + db.session.commit() + other_intake, _ = _add_extraction_intake(user=user, session=other_session, suffix='OTHER-SESSION') + other_user_intake, _ = _add_extraction_intake( + user=other_user, + session=other_user_session, + suffix='OTHER-USER', + ) + + for target_user, target_session, target_intake, request_id in ( + (user, session, intake, 'req-current-session'), + (user, other_session, other_intake, 'req-other-session'), + (other_user, other_user_session, other_user_intake, 'req-other-user'), + ): + start_order_extraction( + user_id=int(target_user.id), + session_id=target_session.session_id, + intake_nos=[target_intake.intake_no], + request_id=request_id, + ) + structured = dict(target_intake.structured_result_json or {}) + snapshot = dict(structured['order_extraction_snapshot']) + snapshot['created_at'] = (datetime.utcnow() - timedelta(seconds=301)).isoformat() + structured['order_extraction_snapshot'] = snapshot + target_intake.structured_result_json = structured + db.session.commit() + + items = list_active_intakes_for_conversation( + user_id=int(user.id), + conversation_id=session.session_id, + ) + assert [item['intake_no'] for item in items] == [intake.intake_no] + assert items[0]['order_extraction_status'] == 'failed' + db.session.refresh(other_intake) + db.session.refresh(other_user_intake) + assert other_intake.order_extraction_status == 'extracting' + assert other_user_intake.order_extraction_status == 'extracting' + + +def test_superseded_order_extraction_request_cannot_read_or_submit(app): + """新请求登记后,旧 Dify Tool 无权重新读取上下文或提交相同文件快照。""" + with app.app_context(): + user, session, intake, document, old_runtime_context = _seed_extraction_input() + old_context = get_order_extraction_context({'agent_runtime_context': old_runtime_context}) + start_order_extraction( + user_id=int(user.id), + session_id=session.session_id, + intake_nos=[intake.intake_no], + request_id='req-newer-turn', + ) + + with pytest.raises(ConflictError) as read_error: + get_order_extraction_context({'agent_runtime_context': old_runtime_context}) + assert read_error.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING' + + with pytest.raises(ConflictError) as submit_error: + submit_order_extraction({ + 'agent_runtime_context': old_runtime_context, + 'input_snapshot_hash': old_context['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [ + _order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000999', + sku='SKU-STALE', + qty=1, + include_process_fields=True, + ), + ], + }) + assert submit_error.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID' + db.session.refresh(intake) + assert intake.order_extraction_status == 'extracting' + assert (intake.structured_result_json or {})['order_extraction_snapshot']['request_id'] == 'req-newer-turn' + assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0 + + def test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay(app): """一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。""" with app.app_context(): @@ -183,8 +704,16 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re result = submit_order_extraction(payload) # 断言一附件拆成两个 Candidate,仅高置信订单创建 Task,Intake 保留为部分完成。 + assert result['created_count'] == 1 + assert result['opened_existing_count'] == 0 assert result['auto_created_count'] == 1 assert result['pending_count'] == 1 + assert result['non_shipping_count'] == 0 + assert result['created_with_missing_fields_count'] == 1 + assert result['message'] == ( + '已创建 1 个发货任务;另有 1 个订单需要补充信息或处理冲突。' + '其中 1 个新建任务仍缺少 Reservation ID,可通过自然对话补充。' + ) assert result['batch_no'] candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all() assert len(candidates) == 2 @@ -194,13 +723,10 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re task = tasks[0] assert task.process_status == 'pending_review' assert task.pending_human_reason == 'rsv_req' - assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == [ - 'hub_code', - 'reservation_id', - 'source_type', - ] + assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == ['reservation_id'] db.session.refresh(intake) assert intake.parse_status == 'parsed' + # 低置信订单仍未消费,因此 Intake 抽取终态必须保留为 partially_completed。 assert intake.order_extraction_status == 'partially_completed' db.session.refresh(document) assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2 @@ -214,6 +740,9 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re replay = submit_order_extraction(payload) assert replay['idempotent_replay'] is True + assert replay['created_count'] == 1 + assert replay['opened_existing_count'] == 0 + assert replay['pending_count'] == 1 assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1 assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2 @@ -222,8 +751,6 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re 'line_index': 0, 'patch': { 'reservation_id': 'R-100', - 'source_type': 'AWS Dublin', - 'hub_code': 'DUB', }, 'comment': '用户通过自然对话补齐流程字段', }) @@ -233,11 +760,625 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re assert task.pending_human_reason == 'low_confidence' assert 'process_field_gate' not in (task.step_payload_json or {}) assert task.lines_json[0]['reservation_id'] == 'R-100' - assert task.lines_json[0]['source_type'] == 'AWS Dublin' - assert task.lines_json[0]['hub_code'] == 'DUB' assert session.user_id == user.id +def test_submit_order_extraction_consumes_empty_and_confident_non_shipping_results(app): + """空 orders[] 与高置信非发货分类均不生成 Candidate,并返回明确的未建单事实。""" + with app.app_context(): + _user, _session, intake, document, runtime_context = _seed_extraction_input() + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + non_shipping_order = _order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='NOTICE-ONLY', + sku='IGNORED-SKU', + qty=1, + include_process_fields=True, + ) + non_shipping_order['classification'] = 'non_shipping_request' + + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [non_shipping_order], + }) + + assert result['created_count'] == 0 + assert result['opened_existing_count'] == 0 + assert result['pending_count'] == 0 + assert result['non_shipping_count'] == 1 + assert result['auto_created_count'] == 0 + assert result['message'] == '未识别到需要处理的发货订单,已忽略 1 项非发货内容;本次未创建任务。' + assert result['non_shipping_orders'] == [{ + 'order_index': 0, + 'source_intake_no': intake.intake_no, + 'primary_document_id': int(document.id), + 'classification_confidence': 0.99, + }] + assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0 + db.session.refresh(intake) + db.session.refresh(document) + assert intake.parse_status == 'consumed' + assert intake.order_extraction_status == 'completed' + assert (document.order_extraction_result_json or {})['candidate_keys'] == [] + assert (document.order_extraction_result_json or {})['non_shipping_order_indexes'] == [0] + + +def test_submit_order_extraction_reports_opened_existing_without_claiming_creation(app, monkeypatch): + """订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。""" + with app.app_context(): + user, session, intake, document, runtime_context = _seed_extraction_input() + batch = ShippingBatch( + batch_no='SB-ORDER-EXISTING-001', + user_id=int(user.id), + conversation_id=session.session_id, + file_count=1, + ) + db.session.add(batch) + db.session.flush() + existing = ShippingTask( + task_no='SN-ORDER-EXISTING-001', + batch_id=int(batch.id), + user_id=int(user.id), + source_type='manual', + process_status='waiting_inventory', + ) + db.session.add(existing) + db.session.commit() + + duplicate_result = { + 'status': 'same_active_task', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'existing-order-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {}, + 'content_fingerprint': 'existing-order-content', + 'content_fingerprint_version': 'shipping-content-v3', + 'matches': [{ + 'task_no': existing.task_no, + 'process_status': existing.process_status, + 'match_type': 'business_fingerprint', + }], + 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [_order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000001', + sku='SKU-A', + qty=10, + include_process_fields=True, + )], + }) + + assert result['created'] == [] + assert result['created_count'] == 0 + assert result['auto_created_count'] == 0 + assert result['opened_existing_count'] == 1 + assert result['pending_count'] == 0 + assert result['message'] == '已打开 1 个已有任务。' + assert result['opened_existing'][0]['task_no'] == existing.task_no + candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one() + assert candidate.consumed_task_id == existing.id + assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1 + + +def test_submit_order_extraction_empty_orders_reports_no_task_created(app): + """LLM 合法返回空数组时应消费 Intake,并明确说明本次没有创建任务。""" + with app.app_context(): + _user, _session, intake, _document, runtime_context = _seed_extraction_input() + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [], + }) + + assert result['created_count'] == 0 + assert result['opened_existing_count'] == 0 + assert result['pending_count'] == 0 + assert result['non_shipping_count'] == 0 + assert result['message'] == '未识别到发货订单,本次未创建任务。' + db.session.refresh(intake) + assert intake.parse_status == 'consumed' + assert intake.order_extraction_status == 'completed' + + +def test_submit_order_extraction_pending_only_message_does_not_start_with_additionally(app): + """只有低置信订单时,结果文案应直接说明待处理数量,不能无前文使用“另有”。""" + with app.app_context(): + _user, _session, intake, document, runtime_context = _seed_extraction_input() + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [_order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000002', + sku='SKU-B', + qty=20, + confidence=0.60, + include_process_fields=True, + )], + }) + + assert result['created_count'] == 0 + assert result['pending_count'] == 1 + assert result['message'] == '有 1 个订单需要补充信息或处理冲突。' + db.session.refresh(intake) + assert intake.parse_status == 'parsed' + assert intake.order_extraction_status == 'partially_completed' + + +def test_submit_order_extraction_unassigned_pending_keeps_documents_partial(app): + """无法归属到具体 Intake/Document 的异常订单项不得把 Document 伪装为抽取完成。""" + with app.app_context(): + _user, _session, intake, document, runtime_context = _seed_extraction_input() + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [None], + }) + + assert result['created_count'] == 0 + assert result['pending_count'] == 1 + assert result['pending_orders'][0]['reasons'] == ['order_must_be_object'] + db.session.refresh(intake) + db.session.refresh(document) + assert intake.order_extraction_status == 'partially_completed' + assert document.order_extraction_status == 'partially_completed' + + +def test_order_extraction_terminal_ui_state_resolves_only_the_current_intakes(app): + """订单抽取终态先返回抽取事实,再按当前 Intake 集合返回 Batch UI State 并持久化回放状态。""" + with app.app_context(): + user, session, intake, document, runtime_context = _seed_extraction_input() + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [ + _order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000099', + sku='SKU-UI-STATE', + qty=3, + include_process_fields=False, + ), + ], + }) + assert result['batch_no'] + + batch, task = resolve_order_extraction_ui_target( + user_id=int(user.id), + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + assert batch is not None and batch.batch_no == result['batch_no'] + assert task is None + assert resolve_order_extraction_ui_target( + user_id=int(user.id) + 999, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) == (None, None) + assert resolve_order_extraction_ui_target( + user_id=int(user.id), + conversation_id='other-conversation', + intake_nos=[intake.intake_no], + ) == (None, None) + assert resolve_order_extraction_ui_target( + user_id=int(user.id), + conversation_id=session.session_id, + intake_nos=[intake.intake_no, 'SNI-NOT-FOUND'], + ) == (None, None) + + load_handlers() + handler = get_handler('shipping_notice') + agent = db.session.get(Agent, int(session.agent_id)) + assert handler is not None and agent is not None + ctx = ChatStreamContext( + query='extract orders', + display_query='extract orders', + user=user, + agent=agent, + session=session, + external_conversation_id=None, + request_id='req-order-extraction-001', + adapter_hints={ + 'shipping_notice': { + 'intake_nos': [intake.intake_no], + 'capability': 'order_extraction', + 'contract_version': EXTRACTION_CONTRACT_VERSION, + }, + }, + ) + chat_log = ChatLog( + user_id=int(user.id), + agent_id=int(agent.id), + conversation_id=session.session_id, + session_id=session.session_id, + query='extract orders', + answer=result['message'], + payload={'existing_key': 'kept'}, + ) + db.session.add(chat_log) + db.session.commit() + lines = list(handler.on_upstream_terminal_event(ctx, { + 'event': 'workflow_finished', + 'chat_log_id': int(chat_log.id), + })) + assert len(lines) == 2 + extraction_event = json.loads(lines[0].removeprefix('data: ').strip()) + assert extraction_event['event'] == 'shipping_order_extraction_state' + assert extraction_event['status'] == 'completed' + assert extraction_event['created_count'] == 1 + assert extraction_event['created_with_missing_fields_count'] == 1 + assert extraction_event['terminal'] is True + + event = json.loads(lines[1].removeprefix('data: ').strip()) + assert event['event'] == 'shipping_ui_state' + assert event['source'] == 'order_extraction' + assert event['batch_no'] == result['batch_no'] + assert event['batch_ui_state']['batch_no'] == result['batch_no'] + assert event['task_no'] + assert event['ui_state']['task_no'] == event['task_no'] + db.session.refresh(intake) + # 唯一 Candidate 已成功消费建单;流程字段缺失只阻断 Task 后续步骤,不改变 Intake 抽取终态。 + assert intake.order_extraction_status == 'completed' + assert intake.order_extraction_error_code is None + db.session.refresh(chat_log) + assert chat_log.payload['existing_key'] == 'kept' + assert chat_log.payload['task_no'] == event['task_no'] + assert chat_log.payload['batch_no'] == result['batch_no'] + assert chat_log.payload['shipping_ui_state']['task_no'] == event['task_no'] + assert chat_log.payload['shipping_batch_ui_state']['batch_no'] == result['batch_no'] + persisted_state = chat_log.payload['shipping_order_extraction_state'] + assert persisted_state['status'] == 'completed' + assert persisted_state['created_count'] == 1 + assert 'event' not in persisted_state + assert 'conversation_id' not in persisted_state + + # 没有新批次时,沿 Candidate.consumed_task_id 返回本轮打开/消费的既有任务。 + intake.consumed_batch_id = None + db.session.commit() + opened_batch, opened_task = resolve_order_extraction_ui_target( + user_id=int(user.id), + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + assert opened_batch is None + assert opened_task is not None + assert opened_task.task_no == event['task_no'] + + +def test_order_extraction_terminal_history_payload_persists_open_existing_anchor(app, monkeypatch): + """open_existing 终态必须把 task_no 与 ui_state 一并持久化,供历史回放恢复工作台。""" + with app.app_context(): + user, session, intake, document, runtime_context = _seed_extraction_input() + runtime_context_dict = json.loads(runtime_context) + batch = ShippingBatch( + batch_no='SB-ORDER-EXISTING-002', + user_id=int(user.id), + conversation_id=session.session_id, + file_count=1, + ) + db.session.add(batch) + db.session.flush() + existing = ShippingTask( + task_no='SN-ORDER-EXISTING-002', + batch_id=int(batch.id), + user_id=int(user.id), + source_type='manual', + process_status='waiting_inventory', + ) + db.session.add(existing) + db.session.commit() + + duplicate_result = { + 'status': 'same_active_task', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'existing-order-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {}, + 'content_fingerprint': 'existing-order-content', + 'content_fingerprint_version': 'shipping-content-v3', + 'matches': [{ + 'task_no': existing.task_no, + 'process_status': existing.process_status, + 'match_type': 'business_fingerprint', + }], + 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [_order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000100', + sku='SKU-OPEN-EXISTING', + qty=5, + include_process_fields=True, + )], + }) + assert result['opened_existing_count'] == 1 + + load_handlers() + handler = get_handler('shipping_notice') + agent = db.session.get(Agent, int(session.agent_id)) + assert handler is not None and agent is not None + ctx = ChatStreamContext( + query='extract orders', + display_query='extract orders', + user=user, + agent=agent, + session=session, + external_conversation_id=None, + request_id=str(runtime_context_dict['platform']['request_id']), + adapter_hints={ + 'shipping_notice': { + 'intake_nos': [intake.intake_no], + 'capability': 'order_extraction', + 'contract_version': EXTRACTION_CONTRACT_VERSION, + }, + }, + ) + chat_log = ChatLog( + user_id=int(user.id), + agent_id=int(agent.id), + conversation_id=session.session_id, + session_id=session.session_id, + query='extract orders', + answer=result['message'], + payload={'existing_key': 'kept'}, + ) + db.session.add(chat_log) + db.session.commit() + + lines = list(handler.on_upstream_terminal_event(ctx, { + 'event': 'workflow_finished', + 'chat_log_id': int(chat_log.id), + })) + assert len(lines) == 2 + ui_event = json.loads(lines[1].removeprefix('data: ').strip()) + assert ui_event['event'] == 'shipping_ui_state' + assert ui_event['task_no'] == existing.task_no + assert ui_event['batch_no'] == batch.batch_no + assert 'batch_ui_state' not in ui_event + assert ui_event['ui_state']['task_no'] == existing.task_no + + db.session.refresh(chat_log) + assert chat_log.payload['existing_key'] == 'kept' + assert chat_log.payload['task_no'] == existing.task_no + assert chat_log.payload['batch_no'] == batch.batch_no + assert chat_log.payload['shipping_ui_state']['task_no'] == existing.task_no + assert 'shipping_batch_ui_state' not in chat_log.payload + persisted_state = chat_log.payload['shipping_order_extraction_state'] + assert persisted_state['opened_existing_count'] == 1 + assert persisted_state['created_count'] == 0 + + +def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_review(app): + """同文件最新 Candidate 按 PO/SKU/qty 唯一命中时,只补旧任务空 Reservation 并保留人工复核。""" + with app.app_context(): + user, session, intake, document, runtime_context = _seed_extraction_input() + batch = ShippingBatch( + batch_no='SB-ORDER-RSV-BACKFILL-001', + user_id=int(user.id), + conversation_id=session.session_id, + file_count=1, + ) + existing = ShippingTask( + task_no='SN-ORDER-RSV-BACKFILL-001', + batch=batch, + user_id=int(user.id), + source_type='manual', + source_content_hash=document.content_hash, + po_number='4510038672', + process_status='pending_review', + review_status='rsv_req', + pending_human_reason='rsv_req', + error_message='解析失败:未识别到 Reservation ID', + lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}], + step_payload_json={ + 'process_field_gate': { + 'status': 'needs_enrichment', + 'missing_fields': ['reservation_id'], + 'issues': [], + 'contract_version': EXTRACTION_CONTRACT_VERSION, + }, + }, + ) + db.session.add(existing) + db.session.commit() + + context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) + order = _order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510038672', + sku='P123456', + qty=24, + include_process_fields=True, + ) + order['lines'][0]['reservation_id'] = '1000140351' + order['lines'][0]['source_type'] = 'DBS DUB' + result = submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'schema_version': EXTRACTION_CONTRACT_VERSION, + 'orders': [order], + }) + + db.session.refresh(existing) + assert result['created_count'] == 0 + assert result['opened_existing_count'] == 1 + assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1 + candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one() + candidate_line = candidate.structured_result_json['business_summary']['lines'][0] + assert candidate_line['source_type'] == 'DBS DUB' + assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA', 'reservation_id': '1000140351'}] + assert existing.process_status == 'pending_review' + assert existing.pending_human_reason == 'low_confidence' + assert 'process_field_gate' not in (existing.step_payload_json or {}) + assert existing.error_message is None + event = ShippingTaskEvent.query.filter_by( + task_id=int(existing.id), + event_type='reservation_backfilled_from_exact_file_candidate', + ).one() + assert event.detail_json['updated_line_indexes'] == [0] + assert event.detail_json['review_preserved'] is True + + +@pytest.mark.parametrize( + 'task_overrides', + [ + {'process_status': 'waiting_inventory'}, + {'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, + {'match_status': 'matched'}, + {'export_file_path': '/tmp/shipment.xlsx'}, + ], +) +def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states(app, task_overrides): + """旧任务已离开 rsv_req 或产生库存/匹配/导出真相时,Candidate 绝不能覆盖订单行。""" + with app.app_context(): + task_values = { + 'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}", + 'po_number': '4510038672', + 'source_type': 'manual', + 'process_status': 'pending_review', + 'review_status': 'rsv_req', + 'pending_human_reason': 'rsv_req', + 'lines_json': [{'sku': 'P123456', 'qty': 24}], + } + task_values.update(task_overrides) + task = ShippingTask(**task_values) + candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-NEG') + db.session.add(task) + db.session.flush() + + changed = backfill_exact_file_open_existing_reservations( + task=task, + candidate=candidate, + candidate_summary={ + 'po_number': '4510038672', + 'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}], + }, + duplicate_status='exact_file', + duplicate_matches=[{'task_no': task.task_no}], + ) + + assert changed is False + assert 'reservation_id' not in task.lines_json[0] + assert ShippingTaskEvent.query.filter_by( + task_id=int(task.id), + event_type='reservation_backfilled_from_exact_file_candidate', + ).count() == 0 + + +def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguity(app): + """既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。""" + with app.app_context(): + tasks = [ + ShippingTask( + task_no='SN-RSV-BACKFILL-CONFLICT', + po_number='4510038672', + source_type='manual', + process_status='pending_review', + review_status='rsv_req', + pending_human_reason='rsv_req', + lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}], + ), + ShippingTask( + task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES', + po_number='4510038672', + source_type='manual', + process_status='pending_review', + review_status='rsv_req', + pending_human_reason='rsv_req', + lines_json=[ + {'sku': 'P123456', 'qty': 24}, + {'sku': 'P123456', 'qty': 24}, + ], + ), + ShippingTask( + task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET', + po_number='4510038672', + source_type='manual', + process_status='pending_review', + review_status='rsv_req', + pending_human_reason='rsv_req', + lines_json=[{'sku': 'P123456', 'qty': 24}], + ), + ] + db.session.add_all(tasks) + db.session.flush() + candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS') + summary = { + 'po_number': '4510038672', + 'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}], + } + + results = [ + backfill_exact_file_open_existing_reservations( + task=task, + candidate=candidate, + candidate_summary=summary, + duplicate_status='exact_file', + duplicate_matches=( + [{'task_no': task.task_no}, {'task_no': 'SN-OTHER-TARGET'}] + if task.task_no.endswith('AMBIGUOUS-TARGET') + else [{'task_no': task.task_no}] + ), + ) + for task in tasks + ] + + assert results == [False, False, False] + assert tasks[0].lines_json[0]['reservation_id'] == 'R-OLD' + assert all('reservation_id' not in line for line in tasks[1].lines_json) + assert 'reservation_id' not in tasks[2].lines_json[0] + + def test_submit_order_extraction_rejects_changed_document_snapshot(app): """读取上下文后附件文本变化时,旧 LLM 结果不得覆盖新来源。""" with app.app_context(): @@ -257,3 +1398,49 @@ def test_submit_order_extraction_rejects_changed_document_snapshot(app): # 断言来源漂移使用稳定错误码,要求 Dify 重新读取上下文而不是重放旧结果。 assert exc_info.value.code == 'SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED' assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0 + + +def test_merge_chat_log_payload_requires_exact_turn_ownership(app): + """订单抽取终态只允许写回同一用户、Agent 与本地会话所属的 ChatLog。""" + with app.app_context(): + user, session, _intake, _document, _runtime_context = _seed_extraction_input() + agent_id = int(session.agent_id) + chat_log = ChatLog( + user_id=int(user.id), + agent_id=agent_id, + conversation_id=session.session_id, + session_id=session.session_id, + query='extract orders', + answer='done', + payload={'existing_key': 'kept'}, + ) + db.session.add(chat_log) + db.session.commit() + + patch = {'shipping_order_extraction_state': {'status': 'completed'}} + mismatched_owners = ( + {'user_id': int(user.id) + 1, 'agent_id': agent_id, 'session_id': session.session_id}, + {'user_id': int(user.id), 'agent_id': agent_id + 1, 'session_id': session.session_id}, + {'user_id': int(user.id), 'agent_id': agent_id, 'session_id': 'other-session'}, + ) + for owner in mismatched_owners: + assert merge_chat_log_payload( + chat_log_id=int(chat_log.id), + payload_patch=patch, + **owner, + ) is False + db.session.refresh(chat_log) + assert chat_log.payload == {'existing_key': 'kept'} + + assert merge_chat_log_payload( + chat_log_id=int(chat_log.id), + user_id=int(user.id), + agent_id=agent_id, + session_id=session.session_id, + payload_patch=patch, + ) is True + db.session.refresh(chat_log) + assert chat_log.payload == { + 'existing_key': 'kept', + 'shipping_order_extraction_state': {'status': 'completed'}, + } diff --git a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py index 28d88020..cd6d7335 100644 --- a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py +++ b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py @@ -1,4 +1,10 @@ -"""rpa.py 按需 trigger 包装测试。""" +""" +backend/tests/test_shipping_notice_rpa_trigger_for_task.py + +用途:验证按需库存导出在 batch 与 legacy 模式下生成正确 trigger。 +依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。 +逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。 +""" from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task @@ -11,7 +17,7 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path): source = { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "warehouse_id": "AWSDU", "entry_url": "https://s360.dbschenker.com/", "parameters": [], @@ -38,7 +44,7 @@ def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path): app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False - source = {"source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU", "query": {}} + source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}} with app.app_context(): path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source) assert path diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index a322d530..91f7966a 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -1,10 +1,18 @@ +""" +backend/tests/test_shipping_notice_tools.py + +用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。 +依赖:Flask 测试客户端、ShippingTask/Customer、货代 workflow 测试辅助。 +逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。 +""" + import json from pathlib import Path import pytest from app import db -from app.models import ChatLog, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent +from app.models import ChatLog, ShippingCustomer, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent from app.services.shipping_notice.match import match_notice_lines from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source @@ -18,6 +26,34 @@ def _tool_headers(app): } +@pytest.fixture(autouse=True) +def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch): + """为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。""" + from app.services.shipping_notice import task_workflow + + original = task_workflow.resolve_shipping_case_for_new_task + + def _resolve_confirmed_case(**kwargs): + case = original(**kwargs) + if case.customer_id is not None: + return case + customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none() + if customer is None: + customer = ShippingCustomer( + standard_name="Tool 流程测试客户", + short_code="TST", + status="active", + ) + db.session.add(customer) + db.session.flush() + case.customer_id = customer.id + case.customer_name_snapshot = customer.standard_name + case.customer_short_code_snapshot = customer.short_code + return case + + monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) + + def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None: """测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。""" client.post( @@ -127,7 +163,6 @@ def test_shipping_notice_tool_flow(app, client): "qty": 10, "uom": "EA", "source_type": "AWS Dublin", - "hub_code": "DUB", }], "confidence": 0.95, }, @@ -780,21 +815,20 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): wb.save(inv_file) wb.close() - cb_res = client.post( - "/api/shipping-notice/rpa/inventory-ready", - headers=headers, - json={ - "task_no": task_id, - "success": True, - "file_path": str(inv_file), + from app.services.shipping_notice import tools as shipping_tools + + with app.app_context(): + data = shipping_tools.rpa_report_inventory( + { + "task_no": task_id, + "success": True, + "file_path": str(inv_file), "run_no": "RUN-TOOLS-CB", "source_code": "DSV360_AWSDU", - "site_id": "AWSDU", - "warehouse_id": "AWSDU", - }, - ) - assert cb_res.status_code == 200 - data = cb_res.get_json() + "site_id": "AWSDU", + "warehouse_id": "AWSDU", + } + ) assert data["status"] == "needs_human" assert data.get("checkpoint") in {"map_infer", "align_review"} assert "confirm_inventory_mapping" in (data.get("human_options") or []) @@ -1567,6 +1601,7 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, monkeypatch): import app.services.shipping_notice.decision_workflow as decision_workflow + import app.services.shipping_notice.task_workflow as task_workflow headers = _tool_headers(app) called: dict[str, str] = {} @@ -1576,6 +1611,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, return True monkeypatch.setattr(decision_workflow, "start_task_orchestrator", fake_start_task_orchestrator) + monkeypatch.setattr(task_workflow, "start_task_orchestrator", lambda _task_no: False) create_res = client.post( "/api/shipping-notice/tools/create_task", @@ -1630,16 +1666,15 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client, ) ) db.session.commit() - - confirm_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "confirm_inventory_mapping"}, - ) - confirm_data = confirm_res.get_json() - assert confirm_data["status"] == "running" - assert "后台继续处理匹配与后续步骤" in confirm_data["message"] - assert called.get("task_no") == task_id + persisted = ShippingTask.query.filter_by(task_no=task_id).first() + assert persisted is not None + assert persisted.review_status == "align_review" + confirm_data = decision_workflow.submit_decision( + {"task_id": task_id, "decision": "confirm_inventory_mapping"} + ) + assert confirm_data["status"] == "running" + assert "后台继续处理匹配与后续步骤" in confirm_data["message"] + assert called.get("task_no") == task_id @pytest.mark.auto_rpa @@ -1682,7 +1717,7 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp task.step_payload_json = { "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", "entry_url": "https://s360.dbschenker.com/", "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, @@ -1692,12 +1727,10 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp task.process_status = "parsed" db.session.commit() - retry_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "retry_rpa"}, - ) - retry_data = retry_res.get_json() + from app.services.shipping_notice import decision_workflow + + with app.app_context(): + retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"}) assert retry_data["status"] == "running" assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"} @@ -1750,7 +1783,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt task.step_payload_json = { "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", "entry_url": "https://s360.dbschenker.com/", "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, @@ -1813,7 +1846,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa task.step_payload_json = { "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", "entry_url": "https://s360.dbschenker.com/", "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, @@ -1833,12 +1866,10 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa ) db.session.commit() - retry_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "retry_rpa"}, - ) - retry_data = retry_res.get_json() + from app.services.shipping_notice import decision_workflow + + with app.app_context(): + retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"}) assert retry_data["status"] == "running" assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1 @@ -1894,7 +1925,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, task.step_payload_json = { "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", "entry_url": "https://s360.dbschenker.com/", "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, diff --git a/backend/tests/test_tasks_0304_chat_features.py b/backend/tests/test_tasks_0304_chat_features.py index 3bda56b4..33f103e7 100644 --- a/backend/tests/test_tasks_0304_chat_features.py +++ b/backend/tests/test_tasks_0304_chat_features.py @@ -86,6 +86,83 @@ def test_chat_messages_history(client): assert msgs[1]['content'] == 'Hello' +def test_chat_messages_restore_user_attachments_without_leaking_into_assistant_payload(client): + """历史回放应把附件放回用户消息,并从助手 payload 中剥离内部 user_attachments。""" + headers = get_headers(client) + with client.application.app_context(): + user = User.query.filter_by(username='testuser').first() + agent = Agent.query.filter_by(name='Test Agent').first() + db.session.add(ChatLog( + user_id=user.id, + agent_id=agent.id, + conversation_id='conv-attachments', + query='总结附件', + answer='已完成总结', + payload={ + 'existing_key': 'kept', + 'user_attachments': [{ + 'id': 'attachment-1', + 'name': 'purchase-order.pdf', + 'size': 144456, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + 'url': 'https://example.com/secret', + }], + }, + )) + db.session.commit() + + res = client.get('/api/chat/messages?conversation_id=conv-attachments&agent_id=1', headers=headers) + + assert res.status_code == 200 + messages = res.get_json() + assert messages[0] == { + 'role': 'user', + 'content': '总结附件', + 'attachments': [{ + 'id': 'attachment-1', + 'name': 'purchase-order.pdf', + 'size': 144456, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + }], + } + assert messages[1]['payload'] == {'existing_key': 'kept'} + + +def test_chat_messages_do_not_create_empty_assistant_for_attachment_only_payload(client): + """仅含用户附件 payload 且无回答时,不应额外回放空助手消息。""" + headers = get_headers(client) + with client.application.app_context(): + user = User.query.filter_by(username='testuser').first() + agent = Agent.query.filter_by(name='Test Agent').first() + db.session.add(ChatLog( + user_id=user.id, + agent_id=agent.id, + conversation_id='conv-attachment-only', + query='', + answer='', + payload={'user_attachments': [{ + 'id': 'attachment-only-1', + 'name': 'notice.eml', + 'type': 'document', + 'source': 'shipping_notice', + }]}, + )) + db.session.commit() + + res = client.get('/api/chat/messages?conversation_id=conv-attachment-only&agent_id=1', headers=headers) + + assert res.status_code == 200 + messages = res.get_json() + assert len(messages) == 1 + assert messages[0]['role'] == 'user' + assert messages[0]['content'] == '' + assert messages[0]['attachments'][0]['name'] == 'notice.eml' + + def test_local_assistant_message_query_does_not_duplicate_user_bubble(client): """助手本地消息即使误传 query,历史回放也不能多生成一条用户确认。""" headers = get_headers(client) diff --git a/docs/demand.md b/docs/demand.md index 7010d99e..03db4509 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -50,12 +50,26 @@ ### 3.x 货代发货通知库存源补充需求 - **核心目标**:在订单解析阶段即确定库存查询来源(`source_code`),避免 RPA 抓错库存池;用户仅需确认来源编码,站点与仓库由系统配置生成。 +- **字段隔离**:订单行 `source_type` 仅作为可选路由线索;库存连接器字段统一为 `connector_type`,任务 API 使用 `inventory_connector_type`,不得复用 `ShippingTask.source_type` 通知来源。 - **自动匹配**:根据发货通知目的地/港口/仓库线索与 `shipping_inventory_sources.yaml` 规则自动 adjudicate;唯一命中则 `resolved` 并继续流程。 - **人工确认**:无法唯一命中时进入 `inventory_source_review` 检查点,用户在聊天区选择或输入线索确认 `source_code`。 - **硬阻断**:库存源未稳定(`resolved` / `user_confirmed`)时,RPA、库存匹配、Excel 生成、货代上传均不得执行。 -- **身份校验**:关联库存快照时校验 `source_code`、`site_id`、`warehouse_id` 与任务一致。 +- **身份校验**:关联库存快照时校验 `source_code`、`connector_type`、`site_id`、`warehouse_id` 与任务一致。 - 技术方案见 [docs/features/shipping-notice/inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 +### 3.x 货代客户身份与业务编号 + +- **双编号**:`ShippingTask.task_no` 继续作为创建即生成且永不修改的内部技术编号;客户确认后生成面向业务的 `business_no`,队列、文件目录、RPA、外键和内部 API 仍使用 `task_no`。 +- **业务编号格式**:固定为 `{customer_short_code}{YYMMDD}{sequence_2}`,不使用分隔符;例如客户简码 `WYC` 在 2026-07-15 的第 1 票为 `WYC26071501`。 +- **客户简码格式**:由管理员维护,全局唯一,固定为 `2-6` 位大写英文字母(`^[A-Z]{2,6}$`);完整业务编号满足 `^[A-Z]{2,6}\d{8}$`。 +- **日期与容量**:日期严格按 `Asia/Shanghai` 计算;流水按“客户 + 上海业务日期”独立从 `01` 递增至 `99`,第 100 票必须阻断并提示容量耗尽,禁止归零、覆盖或随机补号。 +- **客户身份来源**:邮件/文件解析结果仅作为客户候选线索,不能直接作为稳定客户身份;系统以 HXOPS 客户主数据中的稳定 `customer_id` 和人工维护的唯一 `customer_short_code` 为准。 +- **识别与人工确认**:系统可使用已审核名称别名、完整发件人邮箱、非公共且独占的邮箱域名、模板指纹等证据生成候选;未匹配、多候选或证据冲突时进入 `customer_review`,客户未稳定前不得进入库存源判定、RPA、库存匹配、Excel 生成或货代上传。 +- **修订规则**:同一业务单的任务修订版本继承原业务编号;`force_create` 创建新的业务单并申请新流水。业务编号生成后不得静默修改,客户实质更正须保留原号作废与替代关系。 +- **历史兼容**:历史任务允许没有客户主数据关联和业务编号,默认不补发历史业务编号;历史客户回填仅新增稳定客户关联,不覆盖原始解析字段。 +- **期初导入**:客户主数据必须通过“上传暂存 → 标准化与预检 → 冲突处理 → 审核发布 → 对账”导入,禁止 Excel 直接写正式表;以 `source_system + legacy_customer_key` 保证幂等。 +- **权限边界**:普通业务用户可选择已有客户或提交新客户申请;正式客户建档、简码维护、识别证据审核和期初导入仅允许管理员执行。 + ### 3.x 货代发货通知建单防重复(第一阶段) ### 3.x 一封邮件多订单与 Candidate 级判重 @@ -64,9 +78,12 @@ - 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。 - 正文与附件由 LLM 结合语义关联;附件优先作为主证据,SKU/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。 - 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。 -- 高置信发货需求只要包含可信 SKU + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID、Source Type、Hub Code 允许缺失,但 Task 必须停在自然对话补字段门禁。 +- 高置信发货需求只要包含可信 SKU + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;订单行 Source Type 是可选路由线索,不作为必填门禁。 - 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。 - 本期复用现有货代 Chatflow,不新增独立 Dify Workflow,不新增 `agent_runtime_bindings`。 +- 用户点击发送后,聊天区必须立即显示订单识别进行态;该阶段无法获得可信完成比例,因此使用不确定进度,不展示伪造百分比。 +- 订单识别终态必须区分新建任务、打开已有任务、待补充/冲突、非发货忽略和已建但缺流程字段,并在刷新或重新进入会话后仍可恢复。 +- Dify 错误、网络超时或成功结束但未提交 `orders[]` 时,订单识别必须离开 `extracting` 并显示可重试的失败原因。 ### 3.x 发货通知关键字段真值校验 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 86ff3d59..6472ffc1 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -11,9 +11,10 @@ ## 目录 1. [功能概述](#1-功能概述) -2. [入口与任务编号](#2-入口与任务编号) +2. [入口与编号](#2-入口与编号) - [2.1 从哪里进入](#21-从哪里进入) - - [2.2 任务编号(SN-…)](#22-任务编号sn-) + - [2.2 内部任务编号(SN-…)](#22-内部任务编号sn-) + - [2.3 业务编号(WYC26071501)](#23-业务编号wyc26071501) 3. [需要准备哪些资料](#3-需要准备哪些资料) 4. [订单与库存字段说明](#4-订单与库存字段说明) - [4.1 订单行(来自发货通知)](#41-订单行来自发货通知) @@ -22,11 +23,12 @@ 6. [各阶段您需要做什么(分阶段 SOP)](#6-各阶段您需要做什么分阶段-sop) - [阶段 ① — 提交发货通知](#阶段--提交发货通知) - [阶段 ② — 确认发货通知解析](#阶段--确认发货通知解析) - - [阶段 ③ — 提供库存](#阶段--提供库存) - - [阶段 ④ — 确认字段对齐](#阶段--确认字段对齐) - - [阶段 ⑤ — 自动匹配库存](#阶段--自动匹配库存) - - [阶段 ⑥ — 库存不足时的处理](#阶段--库存不足时的处理) - - [阶段 ⑦⑧ — 生成 Excel 与上传货代](#阶段-生成-excel-与上传货代) + - [阶段 ③ — 确认标准客户](#阶段--确认标准客户) + - [阶段 ④ — 提供库存](#阶段--提供库存) + - [阶段 ⑤ — 确认字段对齐](#阶段--确认字段对齐) + - [阶段 ⑥ — 自动匹配库存](#阶段--自动匹配库存) + - [阶段 ⑦ — 库存不足时的处理](#阶段--库存不足时的处理) + - [阶段 ⑧⑨ — 生成 Excel 与上传货代](#阶段-生成-excel-与上传货代) 7. [库存匹配规则](#7-库存匹配规则) 8. [库存不足时的处理](#8-库存不足时的处理) 9. [生成发货 Excel 与上传货代](#9-生成发货-excel-与上传货代) @@ -70,22 +72,23 @@ **系统如何工作(便于理解)**: - 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后由 AI 完整识别订单。只要明确属于发货需求且 SKU、数量可信,系统会自动创建任务,无需再次人工确认建单。 -- Reservation ID、Source Type、Hub Code 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;您可直接在对话中说明正确值。 +- Reservation ID 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;订单行 Source Type 是可选路由线索,可在候选编辑中补充,不作为必填门禁。 - 上传 **库存 Excel** 后,系统会**自动识别表头**(如 `Reservation Order`、`COM ID`)并给出列映射建议;**不确定的列**可在对齐界面用下拉框修改后再确认。 - 匹配与生成 Excel 由系统规则执行;您主要在解析结果、字段对齐、库存不足时做确认或补货修订。 --- -## 2. 入口与任务编号 +## 2. 入口与编号 ### 2.1 从哪里进入 | 入口 | 说明 | |------|------| | **工作台聊天** | 打开「货代发货通知」智能助手,在对话中上传文件或粘贴文字,逐步完成全流程(推荐) | -| **货代发货列表** | 只读查看历史任务状态与导出文件;如需确认、修订、重试或继续处理,请从某条任务「在 Chat 中继续」回到对应对话 | +| **货代发货 → 客户主数据** | 仅管理员可见;维护标准客户、简码、识别证据、期初导入和识别质量审计 | +| **货代发货 → 发货任务** | 查看历史任务状态与导出文件;如需确认、修订、重试或继续处理,请从某条任务「在 Chat 中继续」回到对应对话 | -### 2.2 任务编号(SN-…) +### 2.2 内部任务编号(SN-…) 每处理一笔新的发货需求,系统会分配唯一**任务编号**,格式类似: @@ -93,10 +96,26 @@ SN-20260529-A1B2C3D4 ``` -后续所有上传、确认、匹配、导出都围绕**明确的任务编号**进行。一次业务委托可以在同一 Agent 会话中拆成多个批次(`SB-...`)和多票任务(`SN-...`);聊天顶部会展示会话执行摘要、批次列表和当前聚焦任务。请在对照库存、核对结果时始终关注当前聚焦的批次与任务编号。 +内部任务编号用于系统定位、重试和问题排查。后续所有上传、确认、匹配、导出都围绕明确的内部任务进行。一次业务委托可以在同一 Agent 会话中拆成多个批次(`SB-...`)和多票任务(`SN-...`);聊天顶部会展示会话执行摘要、批次列表和当前聚焦任务。 同一会话中的多个批次会共享业务委托背景和库存快照等上下文,但执行动作彼此隔离:确认、驳回、重试、上传等操作只影响界面标明的当前批次或当前任务,跨批次批量操作不会自动发生。 +### 2.3 业务编号(WYC26071501) + +系统解析并确认标准客户后,会为该票业务生成业务编号,例如: + +```text +WYC26071501 +``` + +编号由“客户简码 + 上海日期 + 两位流水”组成:`WYC` 是管理员维护的客户简码,`260715` 表示 2026-07-15,`01` 表示该客户当天第 1 票。编号不使用横线,日期按 `Asia/Shanghai` 计算;同一客户每天最多 `99` 票。客户简码固定为 `2-6` 位大写英文字母。 + +- 客户尚未确认时,页面显示“业务编号待生成”,内部任务仍可用于定位和复核解析结果。 +- 客户确认后业务编号固定,不因客户资料日后改名或简码调整而变化。 +- 若已编号但尚未上传货代的业务被确认成错误客户,须由管理员填写原因执行纠错:原业务号保留并作废,新业务号指向替代业务单;已上传货代的业务须先完成外部作废流程。 +- 同一业务的修订版本继续使用原业务编号,并通过版本号区分;强制新建的独立业务会申请新编号。 +- 日常业务沟通、发货 Excel 和列表主标题优先使用业务编号;向 IT 反馈问题时请同时提供内部 `SN-...` 编号。 + --- ## 3. 需要准备哪些资料 @@ -136,6 +155,7 @@ SN-20260529-A1B2C3D4 | **金额** | 单行金额 | Amount、Line Amount、金额、小计 | | **币种** | 单价/金额的货币单位 | Currency、Curr、CCY、币种;也可从 `100.50 USD` 等形式识别 | | **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID、Reservation Order、External reservation ID;Wistron 等 PO 可能在 **PR Number / PR_Number** 字段:`ADU_S-xxx@1000140351`,系统取 `@` 后业务编号 | +| **Source Type** | 可选库存路由线索,不代表通知来源或已确认的库存连接器类型 | Source Type、库存来源类型 | | **要求交期** | 该行物料的交货/发货日期 | Required Date、Delivery Date、ETA、交期、交货日期 | | **供应商料号** | 客户侧记录的供应商物料编码 | Vendor Part Number、Vendor PN、Supplier Part No、供应商料号 | @@ -143,6 +163,7 @@ SN-20260529-A1B2C3D4 - **PO Number** 为文档级字段;**PR Number**(含 `@1000140351`)通常对应 **Reservation ID**,不要与 PO Number 混淆。 - **SKU、需求数量、Reservation ID** 是库存核对的核心字段。 +- **Source Type** 仅辅助库存路由,可展示和修订;缺失时不会单独触发字段门禁。 - 邮件模板可以不同;系统按字段语义和表格列关系识别,不依赖固定列顺序。`Allocation ID`、`Parent allocation ID`、`Commodity group ID` 不属于 Reservation ID。 - AI 解析结果只是候选,后端会再次校验。若候选像 32 位内部主键、与原文列证据冲突或无法可靠对齐,系统会阻断并要求人工复核,不会把猜测值送入库存匹配。 - **要求交期、供应商料号、币种** 按**明细行**解析与导出;若 PDF 仅有一个文档级交期或币种,系统会回填到各行。 @@ -183,29 +204,31 @@ SN-20260529-A1B2C3D4 ↓ ② 确认解析结果(客户、SKU、数量、Reservation ID 等) ↓ -③ 提供库存(上传 Excel / 等待自动导出 / 粘贴少量行) +③ 确认标准客户并生成业务编号 ↓ -④ 确认库存列与订单字段的对齐关系 +④ 提供库存(上传 Excel / 等待自动导出 / 粘贴少量行) ↓ -⑤ 自动匹配库存 +⑤ 确认库存列与订单字段的对齐关系 ↓ -⑥ (若不足)补库存 / 返回修订 / 驳回 — 不可发货 +⑥ 自动匹配库存 ↓ -⑦ 生成发货 Excel +⑦ (若不足)补库存 / 返回修订 / 驳回 — 不可发货 ↓ -⑧ 上传货代系统(自动或手工确认) +⑧ 生成发货 Excel + ↓ +⑨ 上传货代系统(自动或手工确认) ``` **重要原则**: -- 必须先确认**发货通知**,再处理**库存**。 +- 必须先确认**发货通知和标准客户**,再处理**库存**。 - 必须先确认**字段对齐**,再执行**库存匹配**。 - 只有**全部订单行满足**后,才能生成 Excel 并上传货代;存在缺口时系统会阻断后续步骤。 **一句话 SOP** ```text -发货通知 → 确认解析 → 上传库存 → 确认字段对齐 → 匹配库存 → (有缺口则阻断)→ 生成 Excel → 上传货代 +发货通知 → 确认解析 → 确认客户并生成业务编号 → 上传库存 → 确认字段对齐 → 匹配库存 → (有缺口则阻断)→ 生成 Excel → 上传货代 ``` --- @@ -253,7 +276,15 @@ SN-20260529-A1B2C3D4 --- -### 阶段 ③ — 提供库存 +### 阶段 ③ — 确认标准客户 + +系统会根据发货通知中的客户名称、发件人等已审核线索推荐标准客户。您需要确认推荐客户是否正确;若未匹配或存在多个候选,请选择已有客户或提交新客户申请。 + +客户确认后,系统生成类似 `WYC26071501` 的业务编号。客户未确认前不会进入库存处理;Agent 不会自行创建客户简码。 + +--- + +### 阶段 ④ — 提供库存 **推荐方式(大表):** @@ -272,7 +303,7 @@ SN-20260529-A1B2C3D4 --- -### 阶段 ④ — 确认字段对齐 +### 阶段 ⑤ — 确认字段对齐 上传库存后,系统会**先自动推断** Excel 列与订单字段的对应关系(例如 `AWS Sku`→SKU、`Reservation Order`→Reservation ID、`Qty Available`→可用数量),并展示**字段对齐表**供您核对。 @@ -305,7 +336,7 @@ SN-20260529-A1B2C3D4 --- -### 阶段 ⑤ — 自动匹配库存 +### 阶段 ⑥ — 自动匹配库存 确认字段对齐后,系统按规则逐行比对(详见 [§7](#7-库存匹配规则))。 @@ -321,13 +352,13 @@ SN-20260529-A1B2C3D4 --- -### 阶段 ⑥ — 库存不足时的处理 +### 阶段 ⑦ — 库存不足时的处理 若存在缺口,系统会**暂停并阻断发货**,展示缺口明细,并引导您补库存或返回修订(详见 [§8](#8-库存不足时的处理))。**不可**按可发数量部分发货。 --- -### 阶段 ⑦⑧ — 生成 Excel 与上传货代 +### 阶段 ⑧⑨ — 生成 Excel 与上传货代 **全部行满足**后: diff --git a/docs/features/shipping-notice/inventory_source_plan.md b/docs/features/shipping-notice/inventory_source_plan.md index cd142568..be0fe40a 100644 --- a/docs/features/shipping-notice/inventory_source_plan.md +++ b/docs/features/shipping-notice/inventory_source_plan.md @@ -9,10 +9,11 @@ ## 设计原则 - Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段(目的地、港口、仓库线索等),**不负责**最终 RPA URL / source_code 决策。 +- 订单行 `source_type` 仅保留为可选路由线索;库存连接器使用独立 `connector_type`,两者不得混用。 - HXOPS 在 `parse_notice` 阶段根据 YAML 配置做标准化、规则匹配、唯一性判断;唯一命中写入任务独立字段。 - 用户人工确认时**只确认 `source_code`**;`site_id`、`warehouse_id` 由配置自动生成,禁止前端或 LLM 直写。 - RPA、库存准备、匹配、Excel 生成、上传等后续步骤均通过 **inventory source gate** 硬阻断,未稳定(`resolved` / `user_confirmed`)不得继续。 -- RPA 只消费 HXOPS 给出的 `rpa_inventory_source` 参数,按 `source_type` 分发到不同 Driver。 +- RPA 只消费 HXOPS 给出的 `rpa_inventory_source` 参数,按 `connector_type` 分发到不同 Driver。 ## 判定时机与状态机 @@ -39,7 +40,7 @@ | --- | --- | | `destination_*` | 目的地候选(城市、国家、港口等),供规则匹配 | | `inventory_source_code` | 正式库存源编码,如 `DSV360_AWSDU` | -| `inventory_source_type` | `dsv360` / `crane_footprint` | +| `inventory_connector_type` | 库存连接器类型:`dsv360` / `crane_footprint` | | `inventory_site_id` | DSV Program / Site(如 `AWSDU`) | | `inventory_warehouse_id` | 具体仓库(如需要) | | `inventory_source_status` | 判定状态 | @@ -55,7 +56,7 @@ 每个 source 含: -- `source_code`、`source_type`、`site_id`、`warehouse_id` +- `source_code`、`connector_type`、`site_id`、`warehouse_id` - `navigation`、`parameters`(RPA 填表) - `match_aliases`:目的地/港口/仓库别名 - `match`:加权评分规则(可选) @@ -71,7 +72,7 @@ "attempt": 1, "rpa_inventory_source": { "source_code": "DSV360_AWSDU", - "source_type": "dsv360", + "connector_type": "dsv360", "entry_url": "https://s360.dbschenker.com/...", "query": { "program_group": "Dublin", @@ -89,7 +90,7 @@ Crane 示例: ```json { "source_code": "CRANE_TZR", - "source_type": "crane_footprint", + "connector_type": "crane_footprint", "entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query", "query": { "owner_code": "0000000100", @@ -108,7 +109,7 @@ Crane 示例: - 发货 Excel 生成 - 货代上传 -库存快照 link 时额外做 **identity check**:`source_code`、`site_id`、`warehouse_id` 与任务字段一致,否则 `SHIPPING.INVENTORY_IDENTITY_MISMATCH`。 +库存快照 link 时额外做 **identity check**:`source_code`、`connector_type`、`site_id`、`warehouse_id` 与任务字段一致,否则 `SHIPPING.INVENTORY_IDENTITY_MISMATCH`。 ## 错误码(API) diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 9e29c8ce..8fbe9f3b 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -20,7 +20,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open -> LLM 一次完整识别 orders[] -> HXOPS 逐订单校验、Candidate 落库、订单级判重 -> 高置信且有 SKU/Qty 原文证据的订单自动建 Batch/Task --> 缺 Reservation ID / Source Type / Hub Code 的 Task 停在字段补充门禁 +-> 缺 Reservation ID 的 Task 停在字段补充门禁;订单行 Source Type 仅作可选路由线索 -> 用户通过自然对话调用既有字段修改 Tool 补齐 ``` @@ -30,7 +30,71 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open - **一封 EML 仍是一个 Intake**;一个 Document 可以产生多个 Candidate;跨附件同一订单由 LLM 合并并以一个主 Document、多个 evidence 记录来源。 - **判重粒度是订单 Candidate,不是整封邮件或单个附件**:附件 hash 是证据之一,最终通过身份指纹 + 内容指纹区分完全重复与可能修订。 - **自动建单硬条件**:`classification=shipping_request`、至少一条合法 SKU + 正数 Qty、分类与 SKU/Qty 置信度达阈值、SKU/Qty 均有非空原文证据、无阻断冲突、无必须人工决策的修订。 -- **流程字段允许缺失**:Reservation ID、Source Type、Hub Code 缺失不阻止 Task 创建,但阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。 +- **流程字段允许缺失**:Reservation ID 缺失不阻止 Task 创建,但会阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。订单行 Source Type 可选,不单独触发门禁。 + +## 2026-07-15 客户身份与业务编号实施基线 + +> 本节冻结客户归一化、期初导入和业务编号规则;后续各阶段实现、Review 与验收均以本节为准。现有 `task_no` 不改格式、不改引用语义。 + +### 业务规则 + +| 项目 | 规则 | +| --- | --- | +| 内部技术编号 | `ShippingTask.task_no`,格式继续为 `SN-YYYYMMDD-XXXXXXXX`,创建即生成、永不修改 | +| 业务编号 | `{customer_short_code}{YYMMDD}{sequence_2}`,无分隔符,例如 `WYC26071501` | +| 客户简码 | 全局唯一的 `2-6` 位大写英文字母,正则 `^[A-Z]{2,6}$` | +| 完整编号校验 | `^[A-Z]{2,6}\d{8}$`,其中末 8 位固定为上海日期 `YYMMDD` + 两位流水 | +| 日期口径 | `Asia/Shanghai`,禁止直接使用 UTC 日期组成业务编号 | +| 流水范围 | 按客户和上海业务日期独立从 `01` 到 `99`;第 100 票明确阻断 | +| 修订任务 | `create_revision` 继承原业务单和业务编号,展示时追加任务版本信息 | +| 强制新建 | `force_create` 创建独立业务单并申请新流水 | +| 客户更正 | 编号前可重新绑定;编号后不得静默改号,须保留原号作废与替代关系 | +| 历史任务 | 允许无标准客户和业务编号,默认不补发历史业务号 | + +### 目标数据边界 + +- `ShippingTask.customer_name/customer_code` 保留为邮件或文件解析原值,继续兼容现有业务指纹与库存列映射,不作为标准客户外键。 +- 标准客户由独立客户主数据维护,至少包含内部 `customer_id`、标准名称、全局唯一简码、启停状态和审计字段。 +- 已审核识别证据独立存储,支持名称别名、完整邮箱、非公共且独占域名、模板指纹等;Agent/LLM 只能提出候选,不能直接创建有效简码或自动批准识别规则。 +- 业务编号归属于独立业务单聚合,不直接归属于某个任务版本;一个业务单可以关联线性的 `ShippingTask` 修订链。 +- 流水表按 `(business_type, customer_id, business_date)` 唯一,使用 PostgreSQL 原子 upsert/returning 分配,`business_no` 唯一约束提供最终保护。 + +### 目标处理顺序 + +```text +创建内部任务 +-> 解析邮件/文件并确认订单字段 +-> 确定性客户裁决 +-> 未匹配/多候选/冲突时进入 customer_review +-> 标准客户稳定后原子生成业务编号 +-> 库存源裁决 +-> 库存/RPA/匹配/Excel/上传 +``` + +客户 Gate 必须同时覆盖解析确认后的自动续跑、任务重试、库存准备、库存匹配、Excel 生成和货代上传,不能只在 `parse_notice` 单点检查。 + +### 期初客户导入 + +- 标准模板包含 `customers` 与 `identifiers` 两个 Sheet;客户行使用 `source_system + legacy_customer_key` 保证幂等。 +- 导入必须经历“上传暂存 → 标准化/预检 → 重复与冲突人工处理 → 审核发布 → 对账”,禁止上传后逐行直接写正式客户表。 +- 阻断项包括标准名称缺失、简码格式或唯一性冲突、标识找不到客户、允许自动匹配的邮箱冲突;名称相似、公共域名和共享域名只产生警告,不得自动合并。 +- 历史任务客户回填是独立批次:保留原始解析字段,仅回填稳定客户关联,默认不生成历史业务编号。 + +### 分阶段交付与验收门 + +| 阶段 | 目标 | 进入下一阶段前必须满足 | +| --- | --- | --- | +| 0 | 冻结需求、架构、业务 SOP 和功能清单 | 编号、时区、流水、修订、权限、历史导入规则在权威文档中一致 | +| 1 | 客户、识别证据、业务单和流水领域模型 | 迁移兼容历史库;普通/修订/强制新建业务单关系测试通过;现有链路不变 | +| 2 | 客户管理与期初导入 | 导入可预检、幂等、整批发布、审计和对账;简码与标识冲突被阻断 | +| 3 | 客户影子识别 | 只记录候选不阻断;真实历史样本形成准确率报告;误自动匹配为 0 | +| 4 | 客户人工确认 Gate | 所有后续副作用入口均不可绕过;客户确认事件完整审计 | +| 5 | 业务编号生成、查询和展示 | PostgreSQL 并发无重复;修订继承、强制新建重新编号;双号查询与历史兼容通过 | +| 6 | 有限自动识别、监控和历史回填 | 仅已审核强规则自动放行;可降级;质量指标、纠错和回填审计可查询 | + +每一阶段完成前必须执行本阶段代码 Review,按严重度列出全部发现、修复后重跑对应测试,并逐条核对验收标准;存在未处理高风险问题时不得进入下一阶段。 + +阶段 6 的客户纠错仅限管理员:已编号且尚未上传货代的业务单保留原号并标记 `voided`,创建 `replaces_case_id` 指向原单的替代业务单并按正确客户申请新流水;任务版本链迁移到替代单,旧号查询跟随替代链返回当前版本,纠错原因与新旧编号写入 `ShippingTaskEvent`。已上传货代的任务必须先完成外部作废流程,系统内纠错接口明确阻断。 ### 第三阶段:业务去重与任务版本(实现摘要) @@ -57,7 +121,7 @@ EML FileAsset -> ShippingNoticeIntake | --- | --- | | 正文与附件融合 | Chatflow 同时读取正文和全部附件文本;附件优先作为订单主证据,正文用于订单通知语义、PO/Reservation 关联和补缺;不确定字段必须输出 `null` | | 建单粒度 | 一个 EML 对应一个 Intake;每个 LLM 识别出的业务订单对应 Candidate;一个 Document 可对应多个 Candidate;高置信订单提交后自动创建 Batch/Task | -| 判重粒度 | Candidate 主附件 `content_hash` 做文件级精确判重;`shipping-v1` 业务身份指纹识别同一订单;`shipping-content-v2` 内容指纹覆盖 PO、收货地、交期、Reservation、SKU、Qty、价格币种、Allocation、Source Type、Hub Code 等,区分 `same_business_content` 与 `possible_revision` | +| 判重粒度 | Candidate 主附件 `content_hash` 做文件级精确判重;`shipping-v1` 业务身份指纹识别同一订单;`shipping-content-v3` 内容指纹覆盖 PO、收货地、交期、Reservation、SKU、Qty、价格币种、Allocation、Source Type 等,区分 `same_business_content` 与 `possible_revision` | | 审核 API | `PATCH /api/workspace/shipping-notice/candidates/{candidate_no}`;`POST .../duplicate-refresh`;`POST .../duplicate-resolution`;所有操作按 Intake owner 隔离,已消费 Candidate 禁止修改 | | 建批 API | `POST /api/workspace/shipping-batches/create-from-intakes` 可传 `candidate_nos`;Candidate 集合参与建批幂等,Task 回填 `source_candidate_id` 与独立附件 hash | | 消费关系 | Candidate 一对一回填 `consumed_task_id`;同 Intake 尚有低置信/冲突 Candidate 时保持 `parse_status=parsed` + `order_extraction_status=partially_completed`,全部处理后才 `consumed` | @@ -896,18 +960,20 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv #### Hxops Shipping Notice Tools -1. `parse_notice` -2. `update_notice_fields` -3. `update_notice_line` -4. `add_notice_line` -5. `remove_notice_line` -6. `get_inventory_schema_preview` -7. `apply_inventory_mapping` -8. `submit_decision` -9. `get_task_status` -10. `get_batch_status` +1. `get_order_extraction_context` +2. `submit_order_extraction` +3. `parse_notice` +4. `update_notice_fields` +5. `update_notice_line` +6. `add_notice_line` +7. `remove_notice_line` +8. `get_inventory_schema_preview` +9. `apply_inventory_mapping` +10. `submit_decision` +11. `get_task_status` +12. `get_batch_status` -当前 Dify 正式职责只包括:通知解析、字段修订、库存映射建议、人工决策提交、任务/批次状态查询与用户解释。 +当前 Dify 正式职责包括:读取上传预处理结果、完整理解一封或多封邮件中的 `orders[]`、提交订单抽取结果、通知解析、字段修订、库存映射建议、人工决策提交、任务/批次状态查询与用户解释。Dify 不直接写 HXOPS 数据库;Candidate 判重、自动建 Batch/Task 与状态推进均由 HXOPS Tool 或 worker 完成。 当前后端 worker 主职责包括:批次派发、自动续跑、库存准备、匹配、生成 Excel、上传货代与 RPA 回写。 ### 2.2.1 编排职责边界 @@ -916,8 +982,10 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv | 能力 / 阶段 | 默认执行方 | 编排要求 | | --- | --- | --- | -| 用户上传通知、建 batch / task、保存 `raw_text` | Hxops 后端 | Hxops 是任务真相源;Dify 不创建任务,只消费已落库任务 | -| 首轮通知理解与结构化抽取 | Dify LLM + `parse_notice` | 仅在 `should_parse_notice=true` 时进入;LLM 负责理解,最终落库由 Tool 完成 | +| 用户上传通知、解析 EML/附件、保存 Intake/Documents | Hxops 后端 | 上传只做确定性预处理,不调用 LLM、不生成 Candidate、不创建 Task | +| 点击发送后的完整订单理解 | Dify 固定 LLM 分支 | 仅在 `refs.capability=order_extraction` 且契约版本匹配时进入;按实际业务订单拆分 `orders[]`,不得按附件数量机械拆单 | +| Candidate 判重与自动建 Batch/Task | Hxops `submit_order_extraction` Tool | Dify 只提交同一快照的结构化结果;HXOPS 负责证据校验、订单级判重、自动建单、待处理 Candidate 与幂等回放 | +| 已建 Task 的首轮通知解析 | Dify LLM + `parse_notice` | 仅在既有任务链 `should_parse_notice=true` 时进入;不得与点击发送订单抽取分支混用 | | 解析结果修订 | Dify 调 `update_notice_*` Tool | 用户用自然语言修单头 / 行项目时,必须落库,不允许只在回答里“口头修正” | | 库存 schema 预览与列映射建议 | Dify | 由 Dify 读取本批库存快照预览、生成 `map_json` 建议;Agent 不得绕过固定链路自行脑补库存结构 | | 应用库存映射、解析完整库存 | Hxops Tool | Dify 只提交 `map_json`;完整库存解析写入批次库存快照,字段对齐确认后本批各票独立匹配 | @@ -930,12 +998,13 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv 本方案不是“用户一句话,Dify 自由发挥到流程结束”,而是“每轮先读状态,再按确定性分支或人工节点收口”。推荐把每轮都视为以下固定编排: -1. **识别上下文**:先从用户消息与 `agent_runtime_context.refs`、`reference_context` 识别 `task_id / batch_no / intent_hint`;模糊指代必须先调用 `parse_agent_runtime_context` 读取 `reference_context`。 -2. **读取真相源**:凡属“继续处理 / 切换任务 / 询问当前状态 / 确认或驳回当前步骤”,优先调用 `get_task_status`;只有库存文件上传链走 `inventory_path`。 -3. **优先直连确定性动作**:`confirm / reject / reparse / retry_rpa / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory / rematch` 必须先走直连 Tool,不先进入 Agent 自由推理。 -4. **仅在固定窗口调用重工具**:`parse_notice` 仅允许出现在“通知待解析”链;`apply_inventory_mapping` 仅允许出现在“库存文件已上传并已拿到 schema preview”链。 -5. **遇到人工门立即停下**:返回 `needs_human`、`stop_agent_turn=true` 或 `forbidden_next_tools` 时,本轮结束;Dify 只展示 `message / parse_msg / align_msg` 并等待用户。 -6. **副作用长链路交回后端**:确认字段对齐后,后续匹配、Excel、上传由后端 worker 自动续跑;Dify 在下一轮通过 `get_task_status` 解释结果,而不是继续串调用多个 Tool。 +1. **先做能力路由**:`parse_agent_runtime_context` 读取 `refs.capability / refs.contract_version / refs.intake_nos`;命中 `order_extraction + shipping-order-extraction-v1` 时,必须先走固定订单抽取分支并在该分支结束本轮。 +2. **识别普通回合上下文**:未命中订单抽取时,再从用户消息、`agent_runtime_context.refs` 与 `reference_context` 识别 `task_id / batch_no / intent_hint`;模糊指代必须使用解析后的 `reference_context`。 +3. **读取真相源**:凡属“继续处理 / 切换任务 / 询问当前状态 / 确认或驳回当前步骤”,优先调用 `get_task_status`;只有库存文件上传链走 `inventory_path`。 +4. **优先直连确定性动作**:`confirm / reject / reparse / retry_rpa / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory / rematch` 必须先走直连 Tool,不先进入 Agent 自由推理。 +5. **仅在固定窗口调用重工具**:`get_order_extraction_context / submit_order_extraction` 仅允许出现在 `order_extraction_path`;`parse_notice` 仅允许出现在已建 Task 的“通知待解析”链;`apply_inventory_mapping` 仅允许出现在库存 schema preview 链。 +6. **遇到人工门立即停下**:返回 `needs_human`、`stop_agent_turn=true` 或 `forbidden_next_tools` 时,本轮结束;Dify 只展示 `message / parse_msg / align_msg` 并等待用户。 +7. **副作用长链路交回后端**:确认字段对齐后,后续匹配、Excel、上传由后端 worker 自动续跑;Dify 在下一轮通过 `get_task_status` 解释结果,而不是继续串调用多个 Tool。 #### 回合收口规则 @@ -974,203 +1043,140 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv ### 2.4 画布配置 -#### 2.4.0 点击发送完整订单抽取固定分支(本期必须手工新增) +#### 2.4.0 主编排接入原则(本期必须手工调整) -本期**不新增 Dify Workflow**。在现有货代 Chatflow 中,把以下分支放在 `运行态上下文标准化` 之后、`用户意图预处理 / 附件意图分类 / 准备读取任务状态 / 货代续办 Agent` 之前: +本期**不新增 Dify Workflow**,订单抽取是现有货代 Chatflow 的最高优先级固定分支。它必须位于 `运行态上下文标准化` 之后、`用户意图预处理` 之前;命中后在本分支内结束,不得再进入库存链、已建 Task 解析链或自由 Agent。 + +主编排分为两层路由: + +1. `顶层能力路由`:只判断平台显式注入的能力契约,决定 `order_extraction_path / normal_path`。 +2. `主路由分支节点`:仅在 `normal_path` 内继续判断 `inventory_path / agent_path / direct_answer`。 ```text 开始 -> Tool 解析运行态上下文 -> 运行态上下文标准化 --> 是否订单抽取请求 - ├─ 是 -> Tool 读取订单抽取上下文 - │ -> 订单完整抽取 LLM - │ -> 订单抽取 JSON 标准化 - │ -> 抽取 JSON 是否有效 - │ ├─ 是 -> Tool 提交订单抽取 - │ │ -> 订单抽取结果回复 -> 结束 - │ └─ 否 -> 订单抽取失败回复 -> 结束 - └─ 否 -> 进入现有“用户意图预处理”及后续链路 +-> 顶层能力路由 + ├─ order_extraction_path + │ -> Tool 读取订单抽取上下文 + │ -> 订单抽取上下文标准化 + │ -> 订单抽取上下文是否有效 + │ ├─ false -> 订单抽取上下文失败回复 -> 结束 + │ └─ true + │ -> 订单完整抽取 LLM + │ -> 订单抽取 JSON 标准化 + │ -> 抽取 JSON 是否有效 + │ ├─ false -> 订单抽取 JSON 失败回复 -> 结束 + │ └─ true + │ -> Tool 提交订单抽取 + │ -> 订单抽取提交结果标准化 + │ -> 提交结果是否有效 + │ ├─ false -> 订单抽取提交失败回复 -> 结束 + │ └─ true -> 订单抽取结果回复 -> 结束 + └─ normal_path + -> 用户意图预处理 + -> 附件意图分类 + -> 分支调度 + -> 主路由分支节点 + ├─ inventory_path + ├─ agent_path + └─ direct_answer ``` -##### A. Tool 解析运行态上下文 +##### 分支输入输出总契约 -原节点的 `paths` 增加并至少包含: +| 阶段 | 输入 | 输出 | 真相源 / 约束 | +| --- | --- | --- | --- | +| 顶层能力识别 | `agent_runtime_context` | `capability`、`contract_version`、`intake_nos_json` | 只读取 `parse_agent_runtime_context` 结果,不分析用户文案 | +| 抽取上下文读取 | 原样 `agent_runtime_context` | Tool `text` | HXOPS 校验会话、用户、Intake 归属并生成不可变快照 | +| 抽取上下文标准化 | Tool `text` | `context_ok`、`input_snapshot_hash`、`context_json`、`error_message` | Code 只解析 JSON 和检查必要字段,不修改业务内容 | +| LLM 完整理解 | `context_json` | LLM `text` | LLM 只识别 `orders[]`,不判重、不建单、不推进任务 | +| LLM JSON 标准化 | LLM `text` | `parse_ok`、`schema_version`、`orders`、`orders_json`、`error_message` | Code 只做契约形状校验;业务门禁仍由 HXOPS 执行 | +| 抽取结果提交 | 运行态上下文、快照、契约版本、`orders` | Tool `text` | HXOPS 做证据校验、Candidate 判重、自动建单及幂等回放 | +| 提交结果标准化 | Tool `text` | `submit_ok`、`message`、`batch_no`、计数与结果 JSON | 回复只消费 HXOPS Tool 返回,不使用 LLM 猜测建单结果 | -```json -[ - "agent_code", - "platform.session_id", - "platform.request_id", - "refs.capability", - "refs.contract_version", - "refs.intake_nos", - "refs.task_no", - "refs.batch_no", - "refs.run_purpose" -] -``` +##### `agent_runtime_context` 订单抽取输入示例 -`运行态上下文标准化` 增加输出: - -| 输出 | 来源 | -| --- | --- | -| `capability` | `data["refs.capability"]`,缺省空字符串 | -| `contract_version` | `data["refs.contract_version"]`,缺省空字符串 | -| `intake_nos_json` | `data["refs.intake_nos"]`,保持 JSON 字符串,不拆成自由文本 | - -##### B. 是否订单抽取请求 - -If-Else 条件必须同时满足: - -```text -capability == "order_extraction" -AND contract_version == "shipping-order-extraction-v1" -``` - -不要只判断 `run_purpose`,也不要根据用户文案猜测是否需要抽取。 - -##### C. Tool 读取订单抽取上下文 - -绑定 `shipping_notice_tools.dify.json` 中的 `get_order_extraction_context`: - -| Tool 参数 | 值 | -| --- | --- | -| `agent_runtime_context` | `{{agent_runtime_context}}` 原样透传 | - -禁止新增 `user_id`、`conversation_id` 或手写 `intake_nos` 参数。HXOPS 会从运行态上下文的本地 ChatSession 反查用户并校验 Intake 归属。 - -主要输出: - -- `input_snapshot_hash` -- `documents[]`:`document_id/source_intake_no/document_type/filename/text/text_truncated/warnings` -- `rule_hints` -- `contract` - -##### D. 订单完整抽取 LLM - -建议 Temperature `0.1`。模型输入为 `Tool 读取订单抽取上下文` 的完整 JSON;不要再使用 Dify `sys.files` 读取原文件。 - -系统 Prompt 可直接使用: - -```text -你是货代发货订单结构化抽取器。你只负责理解 HXOPS 提供的邮件正文与附件文本,不负责建单、判重或推进业务状态。 - -必须遵守: -1. 只输出一个 JSON 对象,格式为 {"schema_version":"shipping-order-extraction-v1","orders":[]};禁止 Markdown、解释、代码围栏。 -2. 一封邮件可能包含 0、1 或多个业务订单;一个附件也可能包含多个订单。按实际业务订单拆分 orders[],不要按附件数量机械拆分。 -3. 同一订单信息可能分散在正文和多个附件中;可以合并,但必须选择一个 primary_document_id,并在 evidence 中记录真实来源 document_id。 -4. 非发货需求返回 orders=[]。不要为了产生任务而猜测订单。 -5. 不确定字段返回 null 或省略,禁止编造 Reservation ID、PO、Hub Code、Source Type、SKU、Qty。 -6. 每个订单必须包含 source_intake_no、primary_document_id、classification、classification_confidence、field_confidence、lines、evidence、conflicts。 -7. classification 仅允许 shipping_request、non_shipping_request、uncertain。 -8. field_confidence.sku 与 field_confidence.qty 是 0..1 的订单级最低可信度;任一行不确定时取更低值。 -9. 每条有效订单行至少包含 sku 与正数 qty;reservation_id、source_type、hub_code 可以为 null。 -10. evidence 至少分别提供 SKU 和 Qty 原文证据,格式 {"field":"lines[0].sku","quote":"原文片段","document_id":123};quote 必须是原文,不得改写。 -11. Reservation/SKU/Qty 来源冲突、订单归属冲突或可能修订时写入 conflicts[];需要阻断自动建单的冲突 severity=blocking。 -12. candidate_key_hint 只能使用稳定业务标识(如 PO/客户订单号),没有则省略;禁止随机值或数组序号。 -``` - -用户 Prompt: - -```text -请根据以下 HXOPS 订单抽取上下文完整识别所有发货订单: -{{Tool 读取订单抽取上下文.text}} -``` - -期望输出示例: +HXOPS 点击发送时应在现有 Chatflow 的 `inputs.agent_runtime_context` 中注入以下字段;整个 JSON 在两个订单抽取 Tool 中必须原样透传: ```json { - "schema_version": "shipping-order-extraction-v1", - "orders": [ - { - "source_intake_no": "SNI-...", - "primary_document_id": 123, - "candidate_key_hint": "4510000001", - "classification": "shipping_request", - "classification_confidence": 0.98, - "field_confidence": {"sku": 0.97, "qty": 0.96}, - "po_number": "4510000001", - "lines": [ - {"sku": "SKU-A", "qty": 10, "reservation_id": null, "source_type": null, "hub_code": null} - ], - "evidence": [ - {"field": "lines[0].sku", "quote": "SKU SKU-A", "document_id": 123}, - {"field": "lines[0].qty", "quote": "QTY 10", "document_id": 123} - ], - "conflicts": [] - } - ] + "schema_version": "1", + "context_id": "ctx-xxx", + "agent_code": "shipping_notice", + "scope": "chat_turn", + "platform": { + "session_id": "conv-xxx", + "request_id": "req-xxx", + "trigger_source": "frontend_chat" + }, + "refs": { + "capability": "order_extraction", + "contract_version": "shipping-order-extraction-v1", + "intake_nos": ["SNI-20260715-ABCDEFGH"], + "run_purpose": "chat_turn" + } } ``` -##### E. 订单抽取 JSON 标准化 +禁止在 Dify 节点中自行构造 `user_id / conversation_id / intake_nos`,也禁止把 `run_purpose` 当作能力路由条件。节点逐项配置、变量类型、代码、Prompt 与连线分别见 `2.4.6`、`2.4.7` 和 `2.4.8`。 -Code 节点输入 `llm_text` 绑定上一步 LLM 文本,使用 Python: +##### HXOPS 订单识别生命周期事件 -```python -import json -import re - - -def main(llm_text: str) -> dict: - text = str(llm_text or "").strip() - text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.I | re.S).strip() - try: - payload = json.loads(text) - except Exception as exc: - return {"parse_ok": False, "schema_version": "", "orders": [], "error": f"invalid_json:{exc}"} - if not isinstance(payload, dict): - return {"parse_ok": False, "schema_version": "", "orders": [], "error": "result_must_be_object"} - schema_version = str(payload.get("schema_version") or "").strip() - orders = payload.get("orders") - if schema_version != "shipping-order-extraction-v1" or not isinstance(orders, list): - return {"parse_ok": False, "schema_version": schema_version, "orders": [], "error": "contract_mismatch"} - return { - "parse_ok": True, - "schema_version": schema_version, - "orders": orders, - "error": "", - } -``` - -输出类型:`parse_ok=Boolean`、`schema_version=String`、`orders=Array[Object]`、`error=String`。 - -##### F. Tool 提交订单抽取 - -仅当 `parse_ok=true` 时调用 `submit_order_extraction`: - -| Tool 参数 | 值 | -| --- | --- | -| `agent_runtime_context` | `{{agent_runtime_context}}` 原样透传 | -| `input_snapshot_hash` | `{{Tool 读取订单抽取上下文.input_snapshot_hash}}` | -| `schema_version` | `{{订单抽取 JSON 标准化.schema_version}}` | -| `orders` | `{{订单抽取 JSON 标准化.orders}}` | - -Tool 返回是唯一建单事实源: - -- `batch_no/created/opened_existing`:已自动处理结果; -- `pending_orders`:低置信、证据不足、冲突、重复/修订待决策; -- `pending_count=0` 不代表后续库存链已完成,只代表本次订单抽取没有待处理订单; -- `idempotent_replay=true` 时直接解释原结果,禁止再次调用建单 Tool。 - -##### G. 回复节点 - -成功回复建议直接基于 Tool 字段模板化,不再经过自由 Agent: +订单抽取分支仍由 Dify 完成语义理解,但进度和最终建单事实由 HXOPS Handler 生成,不要求 Dify 画布增加进度节点。聊天 executor 必须先同步执行 `prepare_stream` 登记 Intake 状态,再允许 relay 发送 preface: ```text -{{Tool 提交订单抽取.message}} -{{#if Tool 提交订单抽取.batch_no}}批次:{{Tool 提交订单抽取.batch_no}}{{#endif}} +Handler.prepare_stream(登记 extracting) +-> session_created +-> shipping_order_extraction_state(extracting) +-> Dify 正文 SSE +-> message_end / workflow_finished / error +-> Handler 收口未提交请求 +-> shipping_order_extraction_state(completed / partially_completed / failed) +-> shipping_ui_state(存在 Batch/Task 时) ``` -`pending_count > 0` 时只说明“部分订单需要补充或确认”,具体 Candidate 由 HXOPS 前端/工作台展示;不要把 Candidate 称为用户必须先选择的“候选建单”。 +事件名称固定为 `shipping_order_extraction_state`,字段契约如下: -JSON 失败回复: +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `status` | String | `extracting / completed / partially_completed / failed` | +| `phase` | String | `llm_extraction / result_persisted / failed` | +| `message` | String | HXOPS 权威用户文案或已友好化失败原因 | +| `created_count` | Integer | 本轮实际新建 Task 数 | +| `opened_existing_count` | Integer | 订单判重后实际打开已有 Task 数 | +| `pending_count` | Integer | 待补充信息或阻断冲突订单数 | +| `non_shipping_count` | Integer | 明确非发货内容数 | +| `created_with_missing_fields_count` | Integer | 已建单但仍缺 Reservation/Source/Hub 等流程字段的 Task 数 | +| `batch_no` | String/null | 本轮新建批次号;无新批次时为空 | +| `terminal` | Boolean | `extracting=false`,其余终态为 `true` | -```text -未能得到符合 shipping-order-extraction-v1 的结构化订单结果,请重新发送;本次未创建任务。 -``` +实现约束: + +- 状态读取必须同时校验 `user_id + session_id + intake_nos + request_id`,旧请求不得读取或覆盖新请求。 +- `extracting` 使用旋转指示器,不展示百分比;当前链路没有可审计的 LLM 实时完成比例。 +- terminal 计数只读取 `order_extraction_submission.result`,不得根据 Candidate 数或 Dify 文案推导。 +- terminal 状态合并到本轮 `ChatLog.payload.shipping_order_extraction_state`;历史消息加载时恢复同一状态卡片。 +- Dify 错误和 ReadTimeout 必须产生可收口的 terminal SSE;已有部分正文的 ReadTimeout 合成为 `message_end`,无正文的错误保留 `error`。 +- 前端在上游 terminal 后仍必须消费 `shipping_order_extraction_state` 和 `shipping_ui_state`,但不得继续拼接迟到的普通 Dify 文本。 + +**聊天工作台恢复契约(阶段 0 冻结)** + +> 适用范围:订单抽取终态进入 `open_existing`、历史消息刷新回放、页面重进后恢复右侧轻量批次工作台。 + +| 字段 | 所在载荷 | 必填级别 | 说明 | +| --- | --- | --- | --- | +| `task_no` | assistant `payload` 顶层 | 必填 | `open_existing` 终态恢复工作台的最小锚点;未携带则前端不得宣称可恢复该任务工作台 | +| `batch_no` | assistant `payload` 顶层 | 条件必填 | 后端能识别既有任务所属批次时必须补齐;未知时允许为空 | +| `shipping_ui_state` | assistant `payload.shipping_ui_state` | 推荐 | 已能构造单任务状态机快照时写入,供刷新后免首轮接口恢复 | +| `shipping_batch_ui_state` | assistant `payload.shipping_batch_ui_state` | 推荐 | 已能构造批次快照时写入;若存在则必须至少包含 `batch_no` 与 `tasks[]` | +| `shipping_order_extraction_state` | assistant `payload.shipping_order_extraction_state` | 必填 | 订单抽取摘要真相源;只负责“新建/打开/待处理”统计,不替代任务锚点 | + +恢复约束: + +- `open_existing` 终态不能只保留 “已打开 N 个已有任务” 摘要,必须同时提供可恢复任务锚点。 +- 前端恢复顺序以 `shipping_batch_ui_state` 为最高优先级,其次 `task_no / batch_no`,最后才允许按当前会话补拉 workspace。 +- `ChatLog.payload` 与实时 SSE 的恢复字段必须同构;历史回放不得弱化为只剩 `shipping_order_extraction_state`。 #### 2.4.1 完整画布总览 @@ -1178,12 +1184,28 @@ JSON 失败回复: 开始 -> Tool 解析运行态上下文 -> 运行态上下文标准化 --> 是否订单抽取请求 --> (命中时走完整订单抽取固定分支并结束) --> 用户意图预处理 --> 附件意图分类 --> 分支调度 --> 主路由分支节点 +-> 顶层能力路由 + +order_extraction_path: + Tool 读取订单抽取上下文 + -> 订单抽取上下文标准化 + -> 订单抽取上下文是否有效 + -> (false)订单抽取上下文失败回复 -> 结束 + -> (true)订单完整抽取 LLM + -> 订单抽取 JSON 标准化 + -> 抽取 JSON 是否有效 + -> (false)订单抽取 JSON 失败回复 -> 结束 + -> (true)Tool 提交订单抽取 + -> 订单抽取提交结果标准化 + -> 提交结果是否有效 + -> (false)订单抽取提交失败回复 -> 结束 + -> (true)订单抽取结果回复 -> 结束 + +normal_path: + 用户意图预处理 + -> 附件意图分类 + -> 分支调度 + -> 主路由分支节点 inventory_path: 库存任务检查 @@ -1345,7 +1367,21 @@ http:///api/shipping-notice/tools/openapi.json flowchart TD A["开始"] --> B["Tool 解析运行态上下文"] B --> B1["运行态上下文标准化"] - B1 --> C["用户意图预处理"] + B1 --> R{"顶层能力路由"} + R -- "order_extraction_path" --> OE1["Tool 读取订单抽取上下文"] + OE1 --> OE2["订单抽取上下文标准化"] + OE2 --> OE3{"订单抽取上下文是否有效?"} + OE3 -- "否" --> OEF1["订单抽取上下文失败回复"] + OE3 -- "是" --> OE4["订单完整抽取 LLM"] + OE4 --> OE5["订单抽取 JSON 标准化"] + OE5 --> OE6{"抽取 JSON 是否有效?"} + OE6 -- "否" --> OEF2["订单抽取 JSON 失败回复"] + OE6 -- "是" --> OE7["Tool 提交订单抽取"] + OE7 --> OE8["订单抽取提交结果标准化"] + OE8 --> OE9{"提交结果是否有效?"} + OE9 -- "否" --> OEF3["订单抽取提交失败回复"] + OE9 -- "是" --> OES["订单抽取结果回复"] + R -- "normal_path" --> C["用户意图预处理"] C --> C1["附件意图分类"] C1 --> D["分支调度"] @@ -1399,11 +1435,30 @@ flowchart TD | ------- | --------------- | ---------------- | ---------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------- | | 开始 | `开始` | Start | 接收消息、附件、会话号与平台上下文 | `sys.query`、`sys.files`、`sys.conversation_id`、`agent_runtime_context` | 无 | | Tool 解析运行态上下文 | `Tool 解析运行态上下文` | Tool | 调 `parse_agent_runtime_context` 读取 shipping 画布需要的字段 | `agent_runtime_context` | Tool `text` | -| 运行态上下文标准化 | `运行态上下文标准化` | Code | 将 parse 结果转为后续节点可直接使用的 shipping 领域变量 | `Tool 解析运行态上下文.text` | `task_no`、`batch_no`、`trigger_source`、`focus_task_no`、`last_action`、`candidate_count` | +| 运行态上下文标准化 | `运行态上下文标准化` | Code | 将 parse 结果转为后续节点可直接使用的 shipping 领域变量 | `Tool 解析运行态上下文.text` | `capability`、`contract_version`、`intake_nos_json`、`task_no`、`batch_no`、`trigger_source`、`focus_task_no`、`last_action`、`candidate_count` | +| 顶层能力路由 | `顶层能力路由` | If-Else | 最高优先级识别点击发送订单抽取回合,并与普通聊天链隔离 | `capability`、`contract_version` | `order_extraction_path / normal_path` | | 用户意图预处理 | `用户意图预处理` | Code | 结合用户消息与已标准化上下文识别任务锚点和短动作意图 | `sys.query`、`sys.conversation_id`、`运行态上下文标准化.*` | `task_no`、`batch_no`、`detected_task_no`、`detected_batch_no`、`intent_hint`、`trigger_source` | | 附件意图分类 | `附件意图分类` | Code | 区分通知附件、库存附件、任务续办 | `用户意图预处理.normalized_query`、`sys.files` | `route_key`、`reason` | | 分支调度 | `分支调度` | Code | 决定 direct / inventory / agent 三条路径 | `附件意图分类.route_key`、任务号 | `branch`、`final_reply`、`resolved_task_no` | -| 主路由分支节点 | `主路由分支节点` | If-Else / Branch | 按 `branch` 一次分流到库存链 / 任务续办链 / 引导回复 | `分支调度.branch` | `inventory_path / agent_path / direct_answer` | +| 主路由分支节点 | `主路由分支节点` | If-Else / Branch | 普通回合按 `branch` 分流到库存链 / 任务续办链 / 引导回复 | `分支调度.branch` | `inventory_path / agent_path / direct_answer` | + +##### A2. `order_extraction_path` 分支节点 + +| 节点名 | 节点标识 | 类型 | 主要职责 | 核心输入 | 核心输出 | +| --- | --- | --- | --- | --- | --- | +| Tool 读取订单抽取上下文 | `Tool 读取订单抽取上下文` | Tool | 按运行态上下文读取邮件正文、附件文本、规则提示与不可变快照 | `agent_runtime_context` | Tool `text` | +| 订单抽取上下文标准化 | `订单抽取上下文标准化` | Code | 解析 Tool JSON 并校验 `status / snapshot / documents / contract` | `Tool 读取订单抽取上下文.text` | `context_ok`、`input_snapshot_hash`、`context_json`、`documents_json`、`error_message` | +| 订单抽取上下文是否有效 | `订单抽取上下文是否有效` | If-Else | 阻止无效上下文进入 LLM | `订单抽取上下文标准化.context_ok` | true / false | +| 订单完整抽取 LLM | `订单完整抽取 LLM` | LLM | 从邮件正文与附件文本识别 0..N 个实际业务订单 | `订单抽取上下文标准化.context_json` | `text` | +| 订单抽取 JSON 标准化 | `订单抽取 JSON 标准化` | Code | 校验 LLM JSON 契约并输出 Tool 可接收的 `orders` | `订单完整抽取 LLM.text` | `parse_ok`、`schema_version`、`orders`、`orders_json`、`order_count`、`error_message` | +| 抽取 JSON 是否有效 | `抽取 JSON 是否有效` | If-Else | 仅允许合法契约结果进入提交 Tool | `订单抽取 JSON 标准化.parse_ok` | true / false | +| Tool 提交订单抽取 | `Tool 提交订单抽取` | Tool | 提交同一快照的 `orders[]`,由 HXOPS 校验、判重并自动建单 | 运行态上下文、快照、契约版本、`orders` | Tool `text` | +| 订单抽取提交结果标准化 | `订单抽取提交结果标准化` | Code | 解析唯一建单事实源,生成稳定回复字段 | `Tool 提交订单抽取.text` | `submit_ok`、`message`、`batch_no`、`created_count`、`opened_existing_count`、`pending_count`、`non_shipping_count`、`idempotent_replay`、结果 JSON | +| 提交结果是否有效 | `提交结果是否有效` | If-Else | 区分 HXOPS 成功结果与非法/异常 Tool 结果 | `订单抽取提交结果标准化.submit_ok` | true / false | +| 订单抽取结果回复 | `订单抽取结果回复` | Answer | 模板化展示 HXOPS 的处理结果 | `message`、`batch_line` | 最终回复 | +| 订单抽取上下文失败回复 | `订单抽取上下文失败回复` | Answer | 上下文读取或契约失败时结束本轮 | `订单抽取上下文标准化.error_message` | 最终回复 | +| 订单抽取 JSON 失败回复 | `订单抽取 JSON 失败回复` | Answer | LLM 输出不符合 JSON 契约时结束本轮 | `订单抽取 JSON 标准化.error_message` | 最终回复 | +| 订单抽取提交失败回复 | `订单抽取提交失败回复` | Answer | 提交 Tool 返回异常或非法结果时结束本轮 | `订单抽取提交结果标准化.error_message` | 最终回复 | ##### B. `inventory_path` 分支节点 @@ -1474,58 +1529,77 @@ flowchart TD 1. 开始 2. Tool 解析运行态上下文 3. 运行态上下文标准化 -4. 用户意图预处理 -5. 附件意图分类 -6. 分支调度 -7. 主路由分支节点 +4. 顶层能力路由 + +order_extraction_path: +5. Tool 读取订单抽取上下文 +6. 订单抽取上下文标准化 +7. 订单抽取上下文是否有效 +8. 订单抽取上下文失败回复 +9. 订单完整抽取 LLM +10. 订单抽取 JSON 标准化 +11. 抽取 JSON 是否有效 +12. 订单抽取 JSON 失败回复 +13. Tool 提交订单抽取 +14. 订单抽取提交结果标准化 +15. 提交结果是否有效 +16. 订单抽取提交失败回复 +17. 订单抽取结果回复 + +normal_path 入口与总路由: +18. 用户意图预处理 +19. 附件意图分类 +20. 分支调度 +21. 主路由分支节点 inventory_path: -8. 库存任务检查 -9. 是否已有库存绑定任务 -10. 无TASK_ID提示 -11. Tool 读取库存 schema 预览 -12. 库存 schema 标准化 -13. 库存列映射 LLM -14. 列映射 JSON 标准化 -15. 库存列映射是否成功 -16. 列映射失败回复 -17. Tool 应用库存列映射 -18. 映射结果标准化 +22. 库存任务检查 +23. 是否已有库存绑定任务 +24. 无TASK_ID提示 +25. Tool 读取库存 schema 预览 +26. 库存 schema 标准化 +27. 库存列映射 LLM +28. 列映射 JSON 标准化 +29. 库存列映射是否成功 +30. 列映射失败回复 +31. Tool 应用库存列映射 +32. 映射结果标准化 direct_answer: -19. 直接回复(引导) +33. 直接回复(引导) agent_path 公共前置: -20. 准备读取任务状态 -21. Tool 读取任务状态 -22. 工具结果标准化 -23. 当前任务动作判断 -24. 是否进入 Agent +34. 准备读取任务状态 +35. Tool 读取任务状态 +36. 工具结果标准化 +37. 当前任务动作判断 +38. 是否进入 Agent agent_path / direct_action: -25. 当前任务直连动作分支 -26. 当前任务直连 Tool 节点 -27. 直连动作结果标准化 -28. 直接回复(动作结果) +39. 当前任务直连动作分支 +40. 当前任务直连 Tool 节点 +41. 直连动作结果标准化 +42. 直接回复(动作结果) agent_path / need_agent: -29. 是否待解析通知 -30. 提取通知原文 -31. 订单需求解析 LLM -32. 结构化结果标准化 -33. Tool 解析发货通知 -34. 解析结果标准化 +43. 是否待解析通知 +44. 提取通知原文 +45. 订单需求解析 LLM +46. 结构化结果标准化 +47. Tool 解析发货通知 +48. 解析结果标准化 共享收口: -35. Agent 状态输入标准化 -36. 货代续办 Agent -37. Agent 指令(维护入口) -38. 直接回复 +49. Agent 状态输入标准化 +50. 货代续办 Agent +51. Agent 指令(维护入口) +52. 直接回复 ``` 说明: - `Agent 状态输入标准化 / 货代续办 Agent / 直接回复` 是库存链与任务链复用的收口节点,配置一次即可,连线时从多个上游汇入。 +- `order_extraction_path` 是独立终止分支,成功或失败都不得汇入 `Agent 状态输入标准化`。 - `当前任务动作判断` 必须紧跟 `工具结果标准化`,因为它依赖标准化后的当前任务状态与动作意图。 - `直接回复(引导)` 是 `direct_answer` 分支专用节点,不参与任务解析链。 @@ -1589,6 +1663,12 @@ Tool 绑定: ```json [ + "agent_code", + "platform.session_id", + "platform.request_id", + "refs.capability", + "refs.contract_version", + "refs.intake_nos", "refs.task_no", "refs.batch_no", "refs.run_purpose", @@ -1630,6 +1710,9 @@ Tool 绑定: | 字段 | 说明 | | --- | --- | +| `capability` | 平台显式请求的能力;本期订单抽取固定为 `order_extraction` | +| `contract_version` | 能力契约版本;本期固定为 `shipping-order-extraction-v1` | +| `intake_nos_json` | 本轮 Intake 编号数组的 JSON 字符串;仅用于观察和排查,不作为 Tool 手写参数 | | `task_no` | shipping 当前任务号,来自 `refs.task_no` | | `batch_no` | shipping 当前批次号,来自 `refs.batch_no` | | `run_purpose` | 本轮运行目的,如 `chat_turn / parse_notice` | @@ -1673,11 +1756,17 @@ def main(text: str = ""): candidates = _object_value(parsed, "reference_context.candidates") or [] if not isinstance(candidates, list): candidates = [] + intake_nos = _object_value(parsed, "refs.intake_nos") or [] + if not isinstance(intake_nos, list): + intake_nos = [] focus_task_no = ( _value(parsed, "domain.state_hint.focus_task_no") or _value(parsed, "reference_context.focus_object.id") ).upper() return { + "capability": _value(parsed, "refs.capability"), + "contract_version": _value(parsed, "refs.contract_version"), + "intake_nos_json": json.dumps(intake_nos, ensure_ascii=False), "task_no": _value(parsed, "refs.task_no").upper(), "batch_no": _value(parsed, "refs.batch_no").upper(), "run_purpose": _value(parsed, "refs.run_purpose"), @@ -1696,9 +1785,664 @@ def main(text: str = ""): 说明: - 本节点只把 parse Tool 的结果转成 Dify 后续节点方便引用的 shipping 领域变量。 +- `capability / contract_version` 只用于 `顶层能力路由`;不得根据 `sys.query` 覆盖。 +- `intake_nos_json` 只用于调试或显示;订单抽取 Tool 仍必须接收完整 `agent_runtime_context` 并在 HXOPS 内部重新校验归属。 - `task_no / batch_no` 允许为空;空值表示当前会话尚未有明确任务或批次锚点。 - `candidate_count > 1` 时,Agent 必须追问用户选择具体任务,不得自行猜测。 +##### 节点:顶层能力路由 + +类型:`If-Else` + +上游节点:`运行态上下文标准化` + +输入字段: + +| Dify 变量 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `运行态上下文标准化.capability` | String | 是 | 平台显式能力标识;普通聊天为空 | +| `运行态上下文标准化.contract_version` | String | 是 | 订单抽取契约版本;普通聊天为空 | + +条件配置(使用 `AND` 同时满足): + +```text +条件 1:运行态上下文标准化.capability +运算符:is +右值:order_extraction + +AND + +条件 2:运行态上下文标准化.contract_version +运算符:is +右值:shipping-order-extraction-v1 +``` + +分支去向: + +| 分支 | 下游节点 | 说明 | +| --- | --- | --- | +| true / `order_extraction_path` | `Tool 读取订单抽取上下文` | 点击发送后的完整订单抽取固定链 | +| false / `normal_path` | `用户意图预处理` | 原有库存、任务续办和引导回复链 | + +说明: + +- 本节点是主编排最高优先级路由;必须位于所有用户意图、附件意图、任务状态和 Agent 节点之前。 +- 不得添加 `run_purpose`、关键词、文件扩展名或 `sys.files` 作为订单抽取判断条件。 +- 契约版本不匹配时不得降级进入旧订单抽取逻辑;当前按 `normal_path` 处理,并由 HXOPS 联调监控发现协议漂移。 + +##### 节点:Tool 读取订单抽取上下文 + +类型:`Tool` + +上游节点:`顶层能力路由.order_extraction_path` + +下游节点:`订单抽取上下文标准化` + +Tool 绑定: + +| 项 | 值 | +| --- | --- | +| `provider_show_name` | `Hxops Shipping Notice` | +| `tool_name` | `get_order_extraction_context` | + +参数映射: + +| 参数名 | 来源 | 类型 | 是否必填 | 说明 | +| --- | --- | --- | --- | --- | +| `agent_runtime_context` | `{{agent_runtime_context}}` | String | 是 | Start 注入的完整 JSON 字符串,原样透传 | + +输出: + +| 字段 | 类型 | 说明 | 下游使用方 | +| --- | --- | --- | --- | +| `text` | String | Tool 原始 JSON 字符串 | `订单抽取上下文标准化.text` | + +成功 JSON 主要字段: + +| JSON 路径 | 类型 | 说明 | +| --- | --- | --- | +| `status` | String | 成功固定为 `ok` | +| `request_id` | String | HXOPS 请求追踪号 | +| `input_snapshot_hash` | String | 当前 Intake/Documents 内容的不可变 SHA-256,提交时必须原样带回 | +| `intake_nos` | Array[String] | HXOPS 校验通过的 Intake 编号 | +| `documents` | Array[Object] | 邮件正文与附件文本集合;元素见下表 | +| `rule_hints` | Object | 上传预处理的规则提示,只可作为辅助信号 | +| `contract` | Object | 固定输出契约与字段门禁说明 | + +`documents[]` 字段: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `document_id` | Integer | HXOPS Document 主键;LLM evidence 和 `primary_document_id` 必须引用此值 | +| `source_intake_no` | String | Document 所属 Intake 编号 | +| `document_type` | String | `email_body / attachment` 等来源类型 | +| `filename` | String / Null | 原附件文件名;正文可为空 | +| `mime_type` | String / Null | MIME 类型 | +| `classification_hint` | String / Null | 规则预分类提示,不是最终订单分类 | +| `parse_status` | String | 文本预处理状态 | +| `text` | String | LLM 可使用的正文或附件提取文本 | +| `text_truncated` | Boolean | 是否因总文本上限被截断 | +| `warnings` | Array | 预处理警告;LLM 应降低对应来源置信度 | + +说明: + +- 禁止新增 `user_id / conversation_id / intake_nos` Tool 参数;HXOPS 从 `platform.session_id` 反查用户并校验 Intake 归属。 +- Dify Tool 节点通常只暴露 `text`;不得在后续节点直接选择 `input_snapshot_hash` 等假定的顶层输出。 +- 本节点失败、超时或返回非 JSON 时,不进入 LLM,由下游标准化节点统一失败。 + +##### 节点:订单抽取上下文标准化 + +类型:`Code` + +上游节点:`Tool 读取订单抽取上下文` + +输入映射: + +| 变量名 | 来源 | 类型 | 是否必填 | +| --- | --- | --- | --- | +| `text` | `Tool 读取订单抽取上下文.text` | String | 是 | + +输出变量(在 Dify Code 节点中逐项声明): + +| 字段 | Dify 类型 | 说明 | 下游使用方 | +| --- | --- | --- | --- | +| `context_ok` | Boolean | Tool JSON 与必要契约是否有效 | `订单抽取上下文是否有效` | +| `input_snapshot_hash` | String | 不可变输入快照 | `Tool 提交订单抽取` | +| `context_json` | String | 保留完整 Tool JSON 的字符串 | `订单完整抽取 LLM` | +| `documents_json` | String | `documents[]` JSON 字符串,便于调试 | 联调观察 | +| `document_count` | Number | Document 数量 | 联调观察 | +| `intake_nos_json` | String | Intake 编号数组 JSON 字符串 | 联调观察 | +| `rule_hints_json` | String | 规则提示 JSON 字符串 | 联调观察 | +| `contract_json` | String | Tool 契约 JSON 字符串 | 联调观察 | +| `error_message` | String | 失败原因;成功为空 | 失败回复 | + +代码: + +```python +import json + + +def main(text: str = ""): + raw = str(text or "").strip() + try: + data = json.loads(raw) if raw else {} + except json.JSONDecodeError: + data = {} + if not isinstance(data, dict): + data = {} + + documents = data.get("documents") if isinstance(data.get("documents"), list) else [] + intake_nos = data.get("intake_nos") if isinstance(data.get("intake_nos"), list) else [] + rule_hints = data.get("rule_hints") if isinstance(data.get("rule_hints"), dict) else {} + contract = data.get("contract") if isinstance(data.get("contract"), dict) else {} + snapshot = str(data.get("input_snapshot_hash") or "").strip() + schema_version = str(contract.get("schema_version") or "").strip() + + error_message = "" + if str(data.get("status") or "").strip() != "ok": + error_message = str(data.get("message") or "订单抽取上下文读取失败,请重新发送。") + elif not snapshot: + error_message = "订单抽取上下文缺少 input_snapshot_hash,请重新发送。" + elif schema_version != "shipping-order-extraction-v1": + error_message = "订单抽取上下文契约版本不匹配,请联系管理员检查 Dify 配置。" + elif not documents: + error_message = "当前邮件没有可用于识别订单的正文或附件文本;本次未创建任务。" + + return { + "context_ok": not bool(error_message), + "input_snapshot_hash": snapshot, + "context_json": json.dumps(data, ensure_ascii=False), + "documents_json": json.dumps(documents, ensure_ascii=False), + "document_count": len(documents), + "intake_nos_json": json.dumps(intake_nos, ensure_ascii=False), + "rule_hints_json": json.dumps(rule_hints, ensure_ascii=False), + "contract_json": json.dumps(contract, ensure_ascii=False), + "error_message": error_message, + } +``` + +说明: + +- 本节点只做 Tool 输出解析和最小必要字段检查,不对 Document 重新分类,不删除截断文本,也不判断是否属于发货需求。 +- `documents=[]` 视为上下文失败;`orders=[]` 则是 LLM 允许返回的正常业务结果,两者含义不同。 +- `context_json` 是 LLM 唯一业务输入;不得再拼入 `sys.files` 或用户自由文本替代 HXOPS 快照。 + +##### 节点:订单抽取上下文是否有效 + +类型:`If-Else` + +条件配置(直接照填): + +```text +左值:订单抽取上下文标准化.context_ok +运算符:is +右值:true +``` + +| 分支 | 下游节点 | +| --- | --- | +| true | `订单完整抽取 LLM` | +| false | `订单抽取上下文失败回复` | + +##### 节点:订单抽取上下文失败回复 + +类型:`Answer` + +内容: + +```text +{{#订单抽取上下文标准化.error_message#}} +``` + +说明:本节点结束本轮,不创建 Candidate、Batch 或 Task,也不进入自由 Agent。 + +##### 节点:订单完整抽取 LLM + +类型:`LLM` + +上游节点:`订单抽取上下文是否有效.true` + +基础配置: + +| 配置项 | 值 | 说明 | +| --- | --- | --- | +| Model | 使用当前应用已批准的结构化抽取模型 | 不在文档中写死供应商 | +| Temperature | `0.1` | 降低结构漂移与字段臆测 | +| Context | 关闭知识库检索 | 只使用 HXOPS 快照 | +| Vision | 关闭 | 上传阶段已将文件转换为文本 | +| Memory | 不依赖 | 本轮订单事实只来自 `context_json` | + +输入 / Query: + +```text +请根据以下 HXOPS 订单抽取上下文完整识别所有发货订单: +{{#订单抽取上下文标准化.context_json#}} +``` + +System Prompt: + +```text +你是货代发货订单结构化抽取器。你只负责理解 HXOPS 提供的邮件正文与附件文本,不负责建单、判重或推进业务状态。 + +[PROMPT_UPDATE] 2026-07-15:合并原订单需求解析 Prompt 的字段规则,并增加跨 Document 订单关联、Reservation ID 主动搜索及证据要求,避免因流程字段允许缺失而提前返回 null。 + +一、输出与职责边界 +1. 只输出一个 JSON 对象,格式为 {"schema_version":"shipping-order-extraction-v1","orders":[]};禁止 Markdown、解释、代码围栏。 +2. 你只负责识别业务订单并输出候选结构;不得声称已建单、已判重、已推进任务,也不得根据 rule_hints 直接下最终结论。 +3. 非发货需求返回 orders=[]。不要为了产生任务而猜测订单。 +4. orders 最多 50 项;无法确定订单归属时使用 classification=uncertain,不得任意合并或拆分。 +5. 每个订单必须包含 source_intake_no、primary_document_id、classification、classification_confidence、field_confidence、lines、evidence、conflicts。 +6. classification 仅允许 shipping_request、non_shipping_request、uncertain。 +7. classification_confidence、field_confidence.sku、field_confidence.qty 必须是 0..1;field_confidence 取订单各行对应字段的最低可信度。 +8. candidate_key_hint 只能使用稳定业务标识,如 PO、客户订单号或明确 Reservation ID;没有稳定标识则省略,禁止使用随机值或数组序号。 + +二、订单拆分与跨 Document 归并 +1. 一封邮件可能包含 0、1 或多个业务订单;一个附件也可能包含多个订单。必须按实际业务订单拆分 orders[],不得按附件数量机械拆分。 +2. 同一订单的信息可能分散在邮件正文和多个附件中。应主动进行跨 Document 关联,而不是只使用 classification_hint=order_notice 的附件。 +3. 跨 Document 关联信号按可靠性从高到低使用: + a. PO、客户订单号、Reservation ID 等稳定业务标识一致; + b. 完整 SKU 一致; + c. 一个 Document 的 MPN 是另一 Document 复合 SKU 的完整组成部分,且 Qty 一致; + d. MPN/SKU、Qty、客户、目的地或日期等多个字段组合一致。 +4. 当邮件正文中的 MPN 是附件复合 SKU 的完整组成部分,且 Qty 一致时,应把邮件同一数据行中的 Reservation ID、Source Type 等字段合并到附件订单行;Source Type 仅作为可选库存路由线索。 +5. 合并后选择最能代表订单主体的 Document 作为 primary_document_id;每个字段的 evidence.document_id 必须指向该字段真实来源,允许同一订单的 evidence 来自多个 Document。 +6. 只有单一弱信号、字段冲突或无法证明属于同一订单时不得强行合并;应保留 null,并在 conflicts 中记录原因。 + +三、表格与行列关系 +1. 按每份原文的实际表头和数据行逐行抽取,禁止假设所有客户共用固定模板或固定列顺序。 +2. HTML、TSV 或其他明确表格结构必须按列边界对齐;空单元格仍占一列,不得把后续列值左移。 +3. 文本被压平时,必须结合表头顺序、引号包裹字段、复合 SKU/MPN、Qty 和其他 Document 的证据判断;无法可靠证明列关系时留空,禁止仅按数字距离猜测。 +4. rule_hints 只是上传阶段的低成本辅助提示。即使 rule_hints.lines=[]、reservation_ids=[] 或 confidence 较低,也必须继续检查 documents 原文;Document 原文证据优先于 rule_hints。 +5. 若 text_truncated=true 或 warnings 非空,应降低受影响字段的置信度,并在必要时写入 conflicts;不得假装已看到被截断内容。 + +四、Reservation ID 规则 +1. 对每个订单必须主动搜索 reservation_id。该字段允许最终缺失,不代表可以跳过搜索。 +2. reservation_id 的允许来源包括:Reservation ID、Reservation Id、COM ID、Reservation Order、Reservation No、Resv ID、PR Number、PR_Number、PR No、PR#、Reservation N.r、Reservation Nr、External reservation ID、External Reservation ID。 +3. 以下字段禁止映射为 reservation_id:Allocation ID、Parent allocation ID、Commodity group ID、Supplier code。 +4. Reservation ID 可以是 8~12 位数字,也可以是 AWS-311、ORD-3002、R-1 等字母数字业务编号;32 位十六进制串和 UUID 通常是内部标识,禁止作为 reservation_id,除非原文明确将其标为合法 Reservation ID 且不存在更可信字段。 +5. PR Number 形如 xxx@1000140351 时,取 @ 后的业务编号 1000140351。 +6. 原文存在合法 Reservation ID 表头,且能通过同一表格行或跨 Document 稳定信号建立订单关联时,禁止返回 null。 +7. reservation_id 非空时,evidence 必须包含对应原文证据,例如 {"field":"lines[0].reservation_id","quote":"3000092917","document_id":17}。 +8. 原文发现可能的 Reservation ID 但无法证明属于当前订单行时,reservation_id 返回 null,并在 conflicts 中记录 {"field":"lines[0].reservation_id","severity":"warning","reason":"reservation_id_found_but_order_link_uncertain","document_id":17}。 + +五、SKU、MPN 与 Qty 规则 +1. sku 优先取 Material、Part Number、Parts No.、Allocated APN、APN、AWS Sku、Customer PN、料号等业务料号字段。 +2. MPN、Vendor Part Number 是制造商料号;若原文同时存在 SKU/APN 与 MPN,应保留业务 SKU,并可额外输出 vendor_part_number。若附件明确使用复合 SKU,则可保留完整复合值,不得无依据拆改。 +3. qty 必须来自 Qty、Q'TY、Quantity、Allocated QTY、Allocated qty、数量等明确数量字段,并且必须是正数;无法确认时不得输出为有效 shipping_request 订单行。 +4. shipping_request 的每条有效订单行至少包含 sku 与正数 qty;reservation_id 只有在充分搜索且无法可靠识别或关联后才允许为 null;source_type 是可选库存路由线索,可为 null。 +5. SKU 和 Qty 必须分别提供非空原文 evidence;reservation_id、source_type 非空时也必须分别提供 evidence。 + +六、冲突、证据与禁止臆造 +1. evidence 格式为 {"field":"lines[0].sku","quote":"原文片段","document_id":123};quote 必须逐字来自原文,不得改写或生成原文中不存在的文本。 +2. source_intake_no、primary_document_id、evidence.document_id 和 conflict.document_id 必须来自输入上下文,不得创造不存在的编号。 +3. Reservation/SKU/Qty 来源冲突、订单归属冲突、正文与附件版本冲突或可能修订时写入 conflicts[];需要阻断自动建单的冲突 severity=blocking,仅表示不确定但不要求阻断时 severity=warning。 +4. 正文和附件冲突时不得静默覆盖。保留证据更强的值,同时在 conflicts 中记录另一来源、冲突字段和 document_id。 +5. 不确定字段返回 null 或省略,禁止编造 Reservation ID、PO、Source Type、SKU、Qty。 +``` + +输出: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `text` | String | 仅包含 `shipping-order-extraction-v1` JSON 对象 | + +期望输出示例: + +```json +{ + "schema_version": "shipping-order-extraction-v1", + "orders": [ + { + "source_intake_no": "SNI-20260715-4B36C3B7", + "primary_document_id": 18, + "candidate_key_hint": "3400104730", + "classification": "shipping_request", + "classification_confidence": 0.98, + "field_confidence": {"sku": 0.97, "qty": 0.96}, + "po_number": "3400104730", + "lines": [ + { + "sku": "TEMP-S000218929/D4-A08AR12000002", + "vendor_part_number": "D4-A08AR12000002", + "qty": 10, + "reservation_id": "3000092917", + "source_type": null + } + ], + "evidence": [ + {"field": "lines[0].sku", "quote": "TEMP-S000218929/D4-A08AR12000002/ Frame, AR1.2, 48.5U, Welltrust", "document_id": 18}, + {"field": "lines[0].qty", "quote": "EA\n10\n2026/6/12", "document_id": 18}, + {"field": "lines[0].reservation_id", "quote": "3000092917", "document_id": 17}, + {"field": "lines[0].vendor_part_number", "quote": "D4-A08AR12000002", "document_id": 17} + ], + "conflicts": [] + } + ] +} +``` + +##### 节点:订单抽取 JSON 标准化 + +类型:`Code` + +输入映射: + +| 变量名 | 来源 | 类型 | 是否必填 | +| --- | --- | --- | --- | +| `llm_text` | `订单完整抽取 LLM.text` | String | 是 | + +输出变量(在 Dify Code 节点中逐项声明): + +| 字段 | Dify 类型 | 说明 | 下游使用方 | +| --- | --- | --- | --- | +| `parse_ok` | Boolean | JSON 契约形状是否有效 | `抽取 JSON 是否有效` | +| `schema_version` | String | 固定契约版本 | `Tool 提交订单抽取` | +| `orders` | Array[Object] | 结构化订单数组 | `Tool 提交订单抽取.orders` | +| `orders_json` | String | 同一数组的 JSON 字符串 | 联调观察 | +| `order_count` | Number | LLM 识别订单数;允许为 0 | 联调观察 | +| `error_message` | String | 失败原因;成功为空 | 失败回复 | + +代码: + +```python +import json +import re + + +def _fail(message: str): + return { + "parse_ok": False, + "schema_version": "", + "orders": [], + "orders_json": "[]", + "order_count": 0, + "error_message": message, + } + + +def main(llm_text: str = ""): + text = str(llm_text or "").strip() + text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.I | re.S).strip() + try: + payload = json.loads(text) + except (TypeError, ValueError) as exc: + return _fail(f"订单抽取结果不是合法 JSON:{exc}") + if not isinstance(payload, dict): + return _fail("订单抽取结果必须是 JSON 对象;本次未创建任务。") + + schema_version = str(payload.get("schema_version") or "").strip() + orders = payload.get("orders") + if schema_version != "shipping-order-extraction-v1": + return _fail("订单抽取结果契约版本不匹配;本次未创建任务。") + if not isinstance(orders, list): + return _fail("订单抽取结果中的 orders 必须是数组;本次未创建任务。") + if len(orders) > 50: + return _fail("单次识别订单超过 50 条,请拆分邮件后重试;本次未创建任务。") + + required = { + "source_intake_no", + "primary_document_id", + "classification", + "classification_confidence", + "field_confidence", + "lines", + "evidence", + "conflicts", + } + for index, order in enumerate(orders): + if not isinstance(order, dict): + return _fail(f"orders[{index}] 必须是对象;本次未创建任务。") + missing = sorted(required - set(order.keys())) + if missing: + return _fail(f"orders[{index}] 缺少字段:{','.join(missing)};本次未创建任务。") + if not isinstance(order.get("lines"), list): + return _fail(f"orders[{index}].lines 必须是数组;本次未创建任务。") + if not isinstance(order.get("evidence"), list) or not isinstance(order.get("conflicts"), list): + return _fail(f"orders[{index}] 的 evidence/conflicts 必须是数组;本次未创建任务。") + if not isinstance(order.get("field_confidence"), dict): + return _fail(f"orders[{index}].field_confidence 必须是对象;本次未创建任务。") + + return { + "parse_ok": True, + "schema_version": schema_version, + "orders": orders, + "orders_json": json.dumps(orders, ensure_ascii=False), + "order_count": len(orders), + "error_message": "", + } +``` + +说明: + +- 本节点只校验 JSON 形状和 50 单上限,不复制 HXOPS 的置信度、证据、判重与自动建单业务门禁。 +- `orders=[]` 是合法结果,必须继续调用 `submit_order_extraction`,由 HXOPS 正确消费“非发货需求/无订单”Intake。 +- OpenAPI 中 `orders` 是 `Array[Object]`;Tool 参数必须直接选择本节点的 `orders` 数组变量。`orders_json` 只用于日志和联调,不得绑定到 Tool 的数组参数,也不得手工复制 LLM 文本。 + +##### 节点:抽取 JSON 是否有效 + +类型:`If-Else` + +条件配置(直接照填): + +```text +左值:订单抽取 JSON 标准化.parse_ok +运算符:is +右值:true +``` + +| 分支 | 下游节点 | +| --- | --- | +| true | `Tool 提交订单抽取` | +| false | `订单抽取 JSON 失败回复` | + +##### 节点:订单抽取 JSON 失败回复 + +类型:`Answer` + +内容: + +```text +{{#订单抽取 JSON 标准化.error_message#}} +``` + +说明:本节点结束本轮,不调用提交 Tool,不创建 Candidate、Batch 或 Task。 + +##### 节点:Tool 提交订单抽取 + +类型:`Tool` + +Tool 绑定: + +| 项 | 值 | +| --- | --- | +| `provider_show_name` | `Hxops Shipping Notice` | +| `tool_name` | `submit_order_extraction` | + +参数映射: + +| 参数名 | 来源 | OpenAPI 类型 | 是否必填 | 说明 | +| --- | --- | --- | --- | --- | +| `agent_runtime_context` | `{{agent_runtime_context}}` | String | 是 | 与读取上下文时完全相同的 Start 输入,原样透传 | +| `input_snapshot_hash` | `{{#订单抽取上下文标准化.input_snapshot_hash#}}` | String | 是 | 读取 Tool 返回的不可变快照 | +| `schema_version` | `{{#订单抽取 JSON 标准化.schema_version#}}` | String | 是 | 固定为 `shipping-order-extraction-v1` | +| `orders` | `{{#订单抽取 JSON 标准化.orders#}}` | Array[Object] | 是 | 直接选择 Code 节点声明的数组输出 | + +输出: + +| 字段 | 类型 | 说明 | 下游使用方 | +| --- | --- | --- | --- | +| `text` | String | HXOPS 提交结果的原始 JSON 字符串 | `订单抽取提交结果标准化.text` | + +成功 JSON 主要字段: + +| JSON 路径 | 类型 | 说明 | +| --- | --- | --- | +| `status` | String | 成功为 `ok` | +| `request_id` | String | 请求追踪号 | +| `batch_no` | String / Null | 本次自动创建或复用的批次号;无自动建单时可空 | +| `created` | Array[Object] | 新创建 Task 摘要 | +| `opened_existing` | Array[Object] | 订单判重后打开的既有 Task 摘要 | +| `pending_orders` | Array[Object] | 低置信、证据不足、冲突或修订待处理订单 | +| `non_shipping_orders` | Array[Object] | 高置信且无阻断冲突的非发货内容审计摘要;不会生成 Candidate | +| `created_count` | Integer | 实际新创建的 Task 数,等于 `created[]` 数量 | +| `opened_existing_count` | Integer | 订单判重后实际打开的已有 Task 数 | +| `pending_count` | Integer | 低置信、证据不足、冲突或修订待处理订单数 | +| `non_shipping_count` | Integer | 已识别并忽略的非发货内容数 | +| `created_with_missing_fields_count` | Integer | 已建 Task 中仍缺 Reservation ID 的数量 | +| `auto_created_count` | Integer | 兼容旧节点的废弃字段;固定等于 `created_count`,不得解释为 Candidate 数 | +| `message` | String | HXOPS 生成的用户可读摘要 | +| `idempotent_replay` | Boolean | `true` 表示网络重试回放历史结果,未再次建单 | + +说明: + +- 本 Tool 返回是唯一建单事实源;Dify 不根据 LLM 置信度自行宣称“已建单”。 +- `pending_count=0` 只表示本次订单抽取无待处理订单,不表示库存、匹配、Excel 或上传已经完成。 +- 缺 Reservation ID 的高置信订单仍可能创建 Task,但 Task 会停在后端字段补充门禁;Source Type 缺失不单独阻断。 +- 快照变化时 HXOPS 会拒绝旧结果;本分支失败后应提示用户重新发送,不得改用旧 LLM 输出重试提交。 + +##### 节点:订单抽取提交结果标准化 + +类型:`Code` + +输入映射: + +| 变量名 | 来源 | 类型 | 是否必填 | +| --- | --- | --- | --- | +| `text` | `Tool 提交订单抽取.text` | String | 是 | + +输出变量(在 Dify Code 节点中逐项声明): + +| 字段 | Dify 类型 | 说明 | 下游使用方 | +| --- | --- | --- | --- | +| `submit_ok` | Boolean | 是否为合法 HXOPS 成功结果 | `提交结果是否有效` | +| `message` | String | HXOPS 结果摘要 | 成功回复 | +| `batch_no` | String | 批次号;无则空 | 成功回复 / 联调观察 | +| `batch_line` | String | 有批次号时生成 `批次:...`,否则为空 | 成功回复 | +| `created_count` | Number | 实际新建 Task 数 | 联调观察 | +| `opened_existing_count` | Number | 打开已有 Task 数 | 联调观察 | +| `pending_count` | Number | 待处理订单数 | 联调观察 | +| `non_shipping_count` | Number | 已忽略的非发货内容数 | 联调观察 | +| `created_with_missing_fields_count` | Number | 已建但仍需补流程字段的 Task 数 | 联调观察 | +| `auto_created_count` | Number | 兼容旧节点;等于 `created_count`,新节点不得使用 | 仅兼容 | +| `idempotent_replay` | Boolean | 是否幂等回放 | 联调观察 | +| `created_json` | String | 新建 Task 数组 JSON | 联调观察 | +| `opened_existing_json` | String | 打开既有 Task 数组 JSON | 联调观察 | +| `pending_orders_json` | String | 待处理订单数组 JSON | HXOPS 工作台 / 联调观察 | +| `non_shipping_orders_json` | String | 已忽略非发货内容数组 JSON | 审计排查 | +| `raw_json` | String | 完整 Tool 结果 | 审计排查 | +| `error_message` | String | 失败原因;成功为空 | 失败回复 | + +代码: + +```python +import json + + +def _integer(value): + try: + return max(int(value or 0), 0) + except (TypeError, ValueError): + return 0 + + +def main(text: str = ""): + raw = str(text or "").strip() + try: + data = json.loads(raw) if raw else {} + except json.JSONDecodeError: + data = {} + if not isinstance(data, dict): + data = {} + + created = data.get("created") if isinstance(data.get("created"), list) else [] + opened = data.get("opened_existing") if isinstance(data.get("opened_existing"), list) else [] + pending = data.get("pending_orders") if isinstance(data.get("pending_orders"), list) else [] + non_shipping = data.get("non_shipping_orders") if isinstance(data.get("non_shipping_orders"), list) else [] + batch_no = str(data.get("batch_no") or "").strip() + message = str(data.get("message") or "").strip() + submit_ok = str(data.get("status") or "").strip() == "ok" and bool(message) + error_message = "" if submit_ok else str( + data.get("message") or "订单抽取结果提交失败,请重新发送;本次未确认创建任务。" + ) + return { + "submit_ok": submit_ok, + "message": message, + "batch_no": batch_no, + "batch_line": f"批次:{batch_no}" if batch_no else "", + "created_count": _integer(data.get("created_count")), + "opened_existing_count": _integer(data.get("opened_existing_count")), + "pending_count": _integer(data.get("pending_count")), + "non_shipping_count": _integer(data.get("non_shipping_count")), + "created_with_missing_fields_count": _integer(data.get("created_with_missing_fields_count")), + "auto_created_count": _integer(data.get("auto_created_count")), + "idempotent_replay": bool(data.get("idempotent_replay")), + "created_json": json.dumps(created, ensure_ascii=False), + "opened_existing_json": json.dumps(opened, ensure_ascii=False), + "pending_orders_json": json.dumps(pending, ensure_ascii=False), + "non_shipping_orders_json": json.dumps(non_shipping, ensure_ascii=False), + "raw_json": json.dumps(data, ensure_ascii=False), + "error_message": error_message, + } +``` + +说明: + +- 不在 Code 节点根据 `created[]` 数量重算业务结论;用户文案以 HXOPS `message` 为准。 +- `idempotent_replay=true` 是正常成功结果,不应提示重复错误,也不得再次调用提交 Tool。 + +##### 节点:提交结果是否有效 + +类型:`If-Else` + +条件配置(直接照填): + +```text +左值:订单抽取提交结果标准化.submit_ok +运算符:is +右值:true +``` + +| 分支 | 下游节点 | +| --- | --- | +| true | `订单抽取结果回复` | +| false | `订单抽取提交失败回复` | + +##### 节点:订单抽取提交失败回复 + +类型:`Answer` + +内容: + +```text +{{#订单抽取提交结果标准化.error_message#}} +``` + +说明:本节点不得声明“未创建任何任务”为绝对事实,因为 Tool 超时可能发生在 HXOPS 已提交之后;用户重新发送时由 Tool 幂等机制回放真实结果。 + +##### 节点:订单抽取结果回复 + +类型:`Answer` + +输入来源: + +| 变量 | 来源 | 类型 | +| --- | --- | --- | +| `message` | `订单抽取提交结果标准化.message` | String | +| `batch_line` | `订单抽取提交结果标准化.batch_line` | String | + +内容: + +```text +{{#订单抽取提交结果标准化.message#}} +{{#订单抽取提交结果标准化.batch_line#}} +``` + +说明: + +- 本节点直接结束本轮,不再进入自由 Agent;避免 Agent 改写已建单数量、批次号或待处理数量。 +- `pending_count > 0` 时只使用 HXOPS `message` 说明订单需要补充信息或处理冲突;Candidate 明细由 HXOPS 工作台展示。 +- 不把 Candidate 称为用户必须先选择的“候选建单”,也不输出库存、匹配或上传已经完成。 + ##### 节点:用户意图预处理 输入映射: @@ -3224,7 +3968,23 @@ HXOPS 运行态上下文: ```text 开始 -> Tool 解析运行态上下文 Tool 解析运行态上下文 -> 运行态上下文标准化 -运行态上下文标准化 -> 用户意图预处理 +运行态上下文标准化 -> 顶层能力路由 + +顶层能力路由(order_extraction_path) -> Tool 读取订单抽取上下文 +Tool 读取订单抽取上下文 -> 订单抽取上下文标准化 +订单抽取上下文标准化 -> 订单抽取上下文是否有效 +订单抽取上下文是否有效(false) -> 订单抽取上下文失败回复 +订单抽取上下文是否有效(true) -> 订单完整抽取 LLM +订单完整抽取 LLM -> 订单抽取 JSON 标准化 +订单抽取 JSON 标准化 -> 抽取 JSON 是否有效 +抽取 JSON 是否有效(false) -> 订单抽取 JSON 失败回复 +抽取 JSON 是否有效(true) -> Tool 提交订单抽取 +Tool 提交订单抽取 -> 订单抽取提交结果标准化 +订单抽取提交结果标准化 -> 提交结果是否有效 +提交结果是否有效(false) -> 订单抽取提交失败回复 +提交结果是否有效(true) -> 订单抽取结果回复 + +顶层能力路由(normal_path) -> 用户意图预处理 用户意图预处理 -> 附件意图分类 附件意图分类 -> 分支调度 分支调度 -> 主路由分支节点 @@ -3291,6 +4051,7 @@ Agent 状态输入标准化 -> 货代续办 Agent - [ ] 已导入 `HXOPS Agent Runtime Context Tools` OpenAPI - [ ] 已导入 `Hxops Shipping Notice` OpenAPI - [ ] `parse_agent_runtime_context` 可在 Agent 节点中调用 +- [ ] `get_order_extraction_context` 与 `submit_order_extraction` 已随 `Hxops Shipping Notice` 导入 - [ ] Server URL 指向 Hxops `shipping-notice` API - [ ] 鉴权头配置正确 @@ -3298,7 +4059,21 @@ Agent 状态输入标准化 -> 货代续办 Agent - [ ] Start 节点只配置 `agent_runtime_context`,未配置 `hxops_context` - [ ] `Tool 解析运行态上下文` 已绑定 `parse_agent_runtime_context` -- [ ] `运行态上下文标准化` 代码正确 +- [ ] `Tool 解析运行态上下文.paths` 已包含 `refs.capability / refs.contract_version / refs.intake_nos` +- [ ] `运行态上下文标准化` 已输出 `capability / contract_version / intake_nos_json` +- [ ] `顶层能力路由` 同时判断 `order_extraction` 与 `shipping-order-extraction-v1` +- [ ] `order_extraction_path` 位于用户意图、任务读取、库存和 Agent 节点之前 +- [ ] `Tool 读取订单抽取上下文` 只传原始 `agent_runtime_context` +- [ ] `订单抽取上下文标准化` 正确解析 Tool `text`,并校验快照、documents 与 contract +- [ ] `订单完整抽取 LLM` 只读取 `context_json`,未读取 `sys.files` 或知识库 +- [ ] `订单完整抽取 LLM` Prompt 明确一附件可多订单、跨附件可合并、不得编造与最多 50 单 +- [ ] `订单抽取 JSON 标准化` 声明 `orders=Array[Object]`,并保留 `orders_json` 供联调 +- [ ] `orders=[]` 可正常调用 `submit_order_extraction`,不会被 If-Else 当作失败 +- [ ] `Tool 提交订单抽取` 原样透传同一 `agent_runtime_context` 与 `input_snapshot_hash` +- [ ] `订单抽取提交结果标准化` 只解释 HXOPS Tool 结果,支持 `idempotent_replay=true` +- [ ] 订单抽取成功与三个失败 Answer 均在本分支结束,不进入自由 Agent +- [ ] 订单抽取 Tool 的 Dify 输出按 `text` JSON 处理,未直接引用假定的 Tool 顶层字段 +- [ ] `运行态上下文标准化` 其余代码正确 - [ ] `用户意图预处理` 代码正确 - [ ] `附件意图分类` 代码正确 - [ ] `分支调度` 代码正确 @@ -3689,7 +4464,7 @@ API 层 ### 5.1 配置文件 - 路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`) -- **新增 Warehouse 只改 YAML**,不改 Python;字段含 `source_code`、`source_type`(`dsv360` / `crane_footprint`)、`site_id`(DSV 必填,如 `AWSBI` / `AWSDBU`;配置后发货 Excel 直接使用该值)、`warehouse_id`(DSV 部分站点需要具体仓库)、`navigation`、`parameters`、`match_aliases`。Crane 可不配置 `site_id`;无 `site_id` 时,发货 Excel 的 Warehouse ID 取实际库存 Excel 内的 Warehouse ID。 +- **新增 Warehouse 只改 YAML**,不改 Python;库存连接器字段含 `source_code`、`connector_type`(`dsv360` / `crane_footprint`)、`site_id`(DSV 必填,如 `AWSBI` / `AWSDBU`;配置后发货 Excel 直接使用该值)、`warehouse_id`(DSV 部分站点需要具体仓库)、`navigation`、`parameters`、`match_aliases`。Crane 可不配置 `site_id`;无 `site_id` 时,发货 Excel 的 Warehouse ID 取实际库存 Excel 内的 Warehouse ID。 - 环境变量: - `SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS`(默认 24) - `SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED`(默认 true) @@ -3704,7 +4479,7 @@ API 层 ### 5.3 批量 RPA(一次登录多 Warehouse) -- Trigger action:`inventory_export_batch`;按 `source_type` 分组,DSV/Crane 各登录一次 +- Trigger action:`inventory_export_batch`;按 `connector_type` 分组,DSV/Crane 各登录一次 - **每个 source 导出前**:DSV 调用 `_reset_dsv_export_entry`(goto entry + session 检测,不重复登录);Crane 调用 `_reset_crane_export_entry` - **按需单票**:`write_inventory_export_trigger_for_task`;batch 开启时包装为单源 batch trigger(与定时共用 worker 路径) - **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充 diff --git a/docs/funclist.md b/docs/funclist.md index 6a0ec75e..7ad1de6b 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -27,6 +27,7 @@ | --- | --- | --- | | Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 | | Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 | +| Chat 附件发送前预览与已发送回放 | 已实现 | 附件列表在发送前显示于输入框上方,展示文件类型、名称、真实大小和逐文件处理状态;发送成功后转为用户消息气泡上方的只读附件快照,并可随历史会话刷新恢复;支持输入区删除、上传中保护删除,发货通知保留解析重试与重复处理入口 | | 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 | | 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 | | 培训 HR 统计问答兜底 | 已实现 | “员工培训”聊天页中,HR 管理员提问参训人数、通过率、未完成名单、本月成绩统计及考试明细等固定统计问题时,优先走后端本地统计兜底;明细列表会把培训阶段映射为中文(观看视频/知识点复盘/逐题考试/结束),并统一把考试时间、完成时间格式化为年月日,避免当前 Dify 工作流 SQL 改写异常导致问答失败 | @@ -62,9 +63,10 @@ | EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 | | EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake,解析邮件正文/真实附件并派生 FileAsset/Document;上传阶段不调用 LLM、不生成 Candidate、不判订单重复;解析失败、超时、取消和资产引用补偿保持幂等 | | 点击发送完整订单抽取 | 已实现(Dify 画布待手工配置) | 前端通过普通 Chatflow 发送 `shipping_intake_nos`;`agent_runtime_context` 触发固定分支;两个 Tool 读取不可变快照、接收 orders[],支持一附件多订单、SKU/Qty 证据/置信度门禁与幂等重放 | -| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 | +| 订单识别生命周期反馈 | 已实现 | Handler 在 Dify 首帧前推送 `shipping_order_extraction_state=extracting`,terminal 后推送真实计数与失败状态;终态合并到 `ChatLog.payload`,聊天历史可恢复,处理中不伪造百分比 | +| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation 的 Task 停在自然对话补字段门禁,订单行 Source Type 仅作可选路由线索 | | 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | -| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | +| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;订单行 `source_type` 可选,连接器字段为 `connector_type` / `inventory_connector_type`;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | | 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | | 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 | | 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 | @@ -73,6 +75,13 @@ | 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` | | 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | | 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | +| 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` | +| 客户主数据与识别证据 | 已实现 | 工作台「货代发货 → 客户主数据」二级目录(仅管理员可见);维护标准客户、唯一简码、名称别名、邮箱/域名、模板指纹、审核与停用管理 | +| 期初客户导入与对账 | 已实现 | 标准 Excel 模板、上传暂存、预检查重、冲突决策、单事务发布、来源键幂等重导和 CSV 对账 | +| 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 | +| 客户人工确认与 Gate | 已实现 | `customer_review`;业务用户从标准客户主数据中确认,客户未稳定时阻断库存源、RPA、匹配、Excel 和上传 | +| 货代业务编号 | 已实现 | 客户确认后按 `Asia/Shanghai` 原子生成 `WYC26071501` 类业务号;每客户每日 `01-99`,修订继承、强制新建重新编号 | +| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认、历史回填和“原号作废 + 新号替代”纠错审计 | | 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) | ### 排程平台任务契约中心(schedule) diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json index fe137a42..b216f048 100644 --- a/docs/openapi/shipping_notice_tools.dify.json +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -3,11 +3,11 @@ "info": { "title": "Shipping Notice Tools", "version": "1.0.0", - "description": "货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:通知理解、字段修订、库存映射建议、人工确认收口与状态查询;不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,不要在自然语言正文列出按钮清单或“推荐下一步”动作列表;可点击按钮由宿主系统根据 action_buttons 统一渲染。鉴权:Authorization Bearer 或 X-Integration-Key。" + "description": "货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:通知理解、字段修订、库存映射建议、人工确认收口与状态查询;不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source、confirm_customer 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,不要在自然语言正文列出按钮清单或“推荐下一步”动作列表;可点击按钮由宿主系统根据 action_buttons 统一渲染。鉴权:Authorization Bearer 或 X-Integration-Key。" }, "servers": [ { - "url": "http://192.168.36.108:5052/api/shipping-notice" + "url": "http://192.168.100.192:8890/api/shipping-notice" } ], "paths": { @@ -54,7 +54,7 @@ "post": { "operationId": "submit_order_extraction", "summary": "提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单", - "description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID、Hub Code、Source Type 允许缺失。", + "description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,订单行 Source Type 是可选路由线索。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。", "parameters": [], "requestBody": { "required": true, @@ -164,13 +164,9 @@ "type": "string", "description": "可为空,缺失时 Task 停在补字段门禁" }, - "hub_code": { - "type": "string", - "description": "可为空,缺失时 Task 停在补字段门禁" - }, "source_type": { "type": "string", - "description": "可为空,缺失时 Task 停在补字段门禁" + "description": "可选订单路由线索;仅在原文有可靠证据时填写,不代表任务通知来源或已确认的库存连接器类型" } }, "additionalProperties": true @@ -252,7 +248,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "raw_text": { "type": "string", @@ -304,7 +300,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "fields": { "type": "object", @@ -353,7 +349,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "line_index": { "type": "integer", @@ -361,7 +357,7 @@ }, "patch": { "type": "object", - "description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/hub_code/source_type", + "description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type;source_type 仅作为可选订单路由线索", "additionalProperties": true }, "comment": { @@ -407,7 +403,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "line": { "type": "object", @@ -456,7 +452,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "line_index": { "type": "integer", @@ -504,7 +500,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" } }, "required": [ @@ -543,7 +539,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "map_json": { "type": "string", @@ -576,7 +572,7 @@ "post": { "operationId": "confirm_inventory_source", "summary": "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)", - "description": "库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。", + "description": "库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。", "parameters": [], "requestBody": { "required": true, @@ -587,7 +583,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "source_code": { "type": "string", @@ -616,6 +612,50 @@ } } }, + "/tools/confirm_customer": { + "post": { + "operationId": "confirm_customer", + "summary": "在客户人工检查点确认标准客户(仅提交 customer_id)", + "description": "仅在 customer_review 检查点且用户已经明确选择标准客户后调用。禁止根据邮件中的不稳定客户名称自行猜测 customer_id;客户确认成功后由 HXOPS 决定后续流程。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" + }, + "customer_id": { + "type": "integer", + "description": "用户从 HXOPS 标准客户列表中明确选择的客户 ID" + } + }, + "required": [ + "task_id", + "customer_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, "/tools/submit_decision": { "post": { "operationId": "submit_decision", @@ -631,7 +671,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "conversation_id": { "type": "string", @@ -681,8 +721,8 @@ "/tools/get_task_status": { "post": { "operationId": "get_task_status", - "summary": "查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构", - "description": "返回 inventory_source_code、inventory_source_type、inventory_site_id、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint、inventory_source_confirmed_by、inventory_source_confirmed_at,以及 step_payload.inventory_source_resolution.candidates。", + "summary": "查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构", + "description": "返回 inventory_source_code、inventory_connector_type、inventory_site_id、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint、inventory_source_confirmed_by、inventory_source_confirmed_at,以及 step_payload.inventory_source_resolution.candidates。", "parameters": [], "requestBody": { "required": true, @@ -693,7 +733,7 @@ "properties": { "task_id": { "type": "string", - "description": "发货任务编号(task id),如 SN-20260529-ABCD1234" + "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" }, "conversation_id": { "type": "string", @@ -758,4 +798,4 @@ } } } -} +} \ No newline at end of file diff --git a/docs/tec.md b/docs/tec.md index a9d56d31..841c0e79 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -20,15 +20,32 @@ ### 2.x 货代发货通知批次库存能力 +### 2.x 货代客户身份与业务编号架构 + +- **技术编号与业务编号分离**:`ShippingTask.task_no` 是内部不可变锚点;新增业务单聚合实体承载 `business_no`、标准客户、编号快照和任务版本链。同一修订链共用业务单,`force_create` 新建业务单。 +- **客户字段语义隔离**:现有 `ShippingTask.customer_name/customer_code` 保留为邮件/文件解析结果,继续兼容业务指纹和库存列映射;新增 `customer_id`/客户裁决状态作为标准客户真相源,禁止复用解析字段充当外键。 +- **确定性客户裁决**:LLM 只抽取名称、邮箱、域名、地址和模板特征等候选;后端按已审核识别证据裁决,输出 `resolved / user_confirmed / ambiguous / unmatched / conflicted`,并保存规则版本、候选、证据与身份指纹。 +- **客户硬 Gate**:复用库存源 Gate 架构,增加独立 `customer_review` 检查点和 `assert_customer_identity_gate()`;解析确认、后台续跑、重试、库存、匹配、导出、上传入口均须校验,避免单点校验被旁路绕过。 +- **原子编号服务**:业务编号格式固定为 `{customer_short_code}{YYMMDD}{sequence_2}`,例如 `WYC26071501`;日期使用 `Asia/Shanghai`。PostgreSQL 按 `(business_type, customer_id, business_date)` 原子递增两位流水,并由 `business_no` 唯一约束兜底;不得使用“查询最大值 + 1”。 +- **格式约束**:客户简码为全局唯一的 `2-6` 位大写英文字母(`^[A-Z]{2,6}$`);完整业务编号正则为 `^[A-Z]{2,6}\d{8}$`。 +- **容量与幂等**:单客户单日允许 `01-99`;第 100 票抛出明确业务错误。同一业务单重复确认直接返回原编号,不重复消耗流水。 +- **编号后纠错**:管理员必须填写原因;尚未上传货代时保留原业务号并标记作废,创建 `replaces_case_id` 指向原单的替代业务单并申请正确客户的新流水。旧号查询跟随替代链,已上传货代的任务须先完成外部作废流程。 +- **期初数据导入**:使用客户导入批次和导入行暂存表保存原文件哈希、原始值、标准化值、校验结果、处理决定和发布结果;正式发布前完成简码冲突、疑似重复、公共域名和标识歧义检查。 +- **渐进发布**:按 `off → shadow → manual_gate → auto_gate` 开启客户识别;影子阶段只记录候选不阻断生产,强规则质量达标后先启用人工 Gate,再开放有限自动确认。 +- **技术栈说明**:该能力继续在现有 Flask + SQLAlchemy 事务内实现,以保证客户绑定、业务号生成、任务状态迁移和审计事件原子提交;本期不拆分独立 FastAPI 服务。 + ### 2.x 多订单邮件 Candidate 架构 - 数据链路为 `FileAsset -> Intake -> Document[] --点击发送/Chatflow--> Candidate[] -> Batch -> Task[]`;上传阶段不调用 LLM、不生成 Candidate、不做订单级判重。 - 普通聊天继续走 `/api/chat/completions`,前端传 `shipping_intake_nos`;后端通过 `agent_runtime_context.refs` 注入 `capability=order_extraction`、`contract_version=shipping-order-extraction-v1` 与 Intake JSON 字符串。 - 现有 Chatflow 调用 `get_order_extraction_context` 获取不可变快照与全文,再调用 `submit_order_extraction` 提交 orders[];Tool 通过本地 ChatSession 反查用户,禁止信任 LLM 传入 user_id。 -- Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v2` 双层判重;内容版本覆盖单头、订单行、价格、分配与 Hub 字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。 +- Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v3` 双层判重;内容版本覆盖单头、订单行、价格与分配字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。 - Candidate 唯一键为 `(intake_id, candidate_key)`,支持一个 Document 产生多个 Candidate;Task 与 Candidate 一对一关联。 - 自动建单后若仍有未消费/待处理 Candidate,Intake 保持 `parsed + partially_completed`;全部处理后才 `consumed`。后补订单可创建新的 Batch,并继续关联原 Intake/Candidate。 - 本期不新增 Dify Workflow 或 `agent_runtime_bindings`;未来平台能力注册应由应用声明所需能力,管理端为能力配置 provider/API/key。 +- 聊天 executor 在返回惰性上游生成器前同步执行 `Handler.prepare_stream`,确保 preface 能读取已登记的 `extracting`;上游 terminal 后 Handler 依次推送订单识别终态与 `shipping_ui_state`。 +- `shipping_order_extraction_state` 是 HXOPS 领域 SSE,不由 Dify 正文推导;终态以 `request_id + session_id + intake_nos + user_id` 围栏读取 Intake submission 事实,并合并到对应 `ChatLog.payload` 供历史回放。 +- 订单完整抽取无法提供可信阶段百分比,前端只展示不确定进度;新建、打开已有、待补充、非发货和缺流程字段均使用 HXOPS Tool 的真实计数。 ### 2.x 发货通知字段契约与后端裁决 @@ -42,7 +59,7 @@ - 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。 - 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。 - `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。 -- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 +- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;订单行 `source_type` 仅作为可选路由线索,库存连接器配置/API 分别使用 `connector_type` / `inventory_connector_type`,不得复用 `ShippingTask.source_type`;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 - **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。 ### 2.1 已有聊天路由能力 diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md index 1a1e647b..91a0a26f 100644 --- a/docs/test_plan_matrix.md +++ b/docs/test_plan_matrix.md @@ -39,7 +39,8 @@ | **发货通知** | **点击发送进入现有 Chatflow** | 已预处理 Intake 点击发送走普通 `/api/chat/completions`,携带 `shipping_intake_nos`,不调用本地建批 Action。 | `useChatShippingSendHandler.spec.ts` / chat runtime context 测试 | 空文本或自然语言 + parsed Intake | 使用默认/用户 query 调 `sendMessage`;上下文含 Intake;SSE 后仅清理 consumed 附件。 | | **发货通知** | **一附件多订单与部分成功** | 一个 Document 可形成多个 Candidate;高置信订单自动建 Task,低置信订单保留。 | `test_shipping_notice_order_extraction.py::test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 2 Candidate、1 Task、1 pending;Intake=`partially_completed`;重放不重复建单。 | | **发货通知** | **订单抽取快照与权限** | Tool 从 agent_runtime_context 会话反查用户;附件来源变化后拒绝旧 LLM 结果。 | `test_shipping_notice_order_extraction.py` | 合法上下文、修改 Document 文本后的旧 snapshot | 合法上下文可读取;漂移返回 `CANDIDATE_SOURCE_CHANGED`;不创建 Candidate。 | -| **发货通知** | **自动建单与流程字段门禁** | 分类、SKU/Qty 置信度与原文证据达标即建 Task;缺 Reservation/Source Type/Hub Code 仍建单但禁止库存链。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 SKU+Qty,流程字段为空 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel。 | +| **发货通知** | **自动建单与流程字段门禁** | 分类、SKU/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;订单行 Source Type 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 SKU+Qty,Reservation 为空、Source Type 可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;Source Type 缺失不单独阻断。 | +| **发货通知** | **库存连接器 API 命名** | 连接器候选使用 `connector_type`,任务 API 使用 `inventory_connector_type`;不得返回旧 `inventory_source_type`。 | `test_shipping_notice_openapi_contract.py` | 获取动态 OpenAPI 与静态 Dify 快照 | 订单行保留可选 `source_type` 且不暴露废弃路由字段;状态查询说明仅含 `inventory_connector_type`。 | | **发货通知** | **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;合法幂等重放不受影响。 | diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index 3a5393e8..cd23cb28 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -145,6 +145,13 @@ export const adminRoutes: RouteRecordRaw[] = [ }, }, + { + path: "shipping-customers", + name: "AdminShippingCustomers", + redirect: "/workspace/shipping-notice/customers", + meta: { requiresAdmin: true, title: "货代客户主数据" }, + }, + { path: "announcements", name: "AdminAnnouncements", diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index 22658559..3a6c7d91 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -49,9 +49,19 @@ export const workspaceRoutes: RouteRecordRaw[] = [ }, { path: 'shipping-notice', - name: 'workspace-shipping-notice', + redirect: '/workspace/shipping-notice/tasks', + }, + { + path: 'shipping-notice/customers', + name: 'workspace-shipping-customers', + component: () => import('@/features/admin/modules/shipping-customers/ShippingCustomersPage.vue'), + meta: { title: '货代客户主数据', requiresAdmin: true }, + }, + { + path: 'shipping-notice/tasks', + name: 'workspace-shipping-tasks', component: () => import('@/features/workspace/pages/ShippingNoticePage.vue'), - meta: { title: '货代发货' }, + meta: { title: '货代发货任务' }, }, { path: 'feedback', diff --git a/frontend/src/constants/shippingNoticeActions.ts b/frontend/src/constants/shippingNoticeActions.ts index 337e9acf..519957a4 100644 --- a/frontend/src/constants/shippingNoticeActions.ts +++ b/frontend/src/constants/shippingNoticeActions.ts @@ -14,6 +14,7 @@ export const SHIPPING_ACTION_IDS = [ 'rematch', 'retry_rpa', 'confirm_inventory_source', + 'confirm_customer', 'retry_resolve_inventory_source', 'upload_inventory_file', 'retry_upload', @@ -54,6 +55,7 @@ export const SHIPPING_INTERNAL_STATUS_TOKENS = [ 'upload_req', 'inventory_pending', 'inventory_source_review', + 'customer_review', 'inventory_source_unresolved', 'map_ok', 'parse_ok', diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index c97ee905..b0bd8a88 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -1,9 +1,11 @@ /** * features/admin/api/admin.api.ts - * 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。 + * 用途:管理后台用户、部门、Agent、货代客户、权限、报表等 HTTP API。 + * 依赖:requestJson、getAuthHeaders、各管理域类型。 + * 逻辑:JSON 接口统一走 requestJson;模板与对账二进制下载沿用认证 fetch 并抛 BusinessError。 */ import { getAuthHeaders } from '@/shared/utils/auth'; -import { requestJson } from '@/shared/api/client'; +import { BusinessError, requestJson, resolveLocalizedErrorMessage } from '@/shared/api/client'; import type { AdminUserRow } from '../types/admin.types'; import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types'; import type { PaginatedResult } from '@/shared/types/pagination.types'; @@ -15,10 +17,131 @@ import type { UsageReport, UsageRangeKey, } from '../types/report.types'; +import type { + ShippingCustomerIdentifier, + ShippingCustomerImportBatch, + ShippingCustomerPage, + ShippingCustomerRow, + ShippingCustomerShadowItem, + ShippingCustomerShadowReport, + ShippingIdentifierFormState, +} from '../types/shipping-customer.types'; const auth = () => ({ headers: getAuthHeaders() }); const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); +/** 下载管理端二进制文件,并将标准错误 envelope 保留为 BusinessError。 */ +const downloadAdminFile = async (url: string, fallbackName: string): Promise => { + const response = await fetch(url, { headers: getAuthHeaders() }); + if (!response.ok) { + const payload = await response.json().catch(() => null); + const code = payload?.error?.code || 'SYSTEM.HTTP_ERROR'; + throw new BusinessError({ + message: resolveLocalizedErrorMessage(code, payload?.error?.message || `HTTP ${response.status}`), + code, + details: payload?.error?.details || {}, + requestId: payload?.request_id, + status: response.status, + }); + } + const blob = await response.blob(); + const disposition = response.headers.get('Content-Disposition') || ''; + const encodedName = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]; + const plainName = disposition.match(/filename="?([^";]+)"?/i)?.[1]; + const filename = encodedName ? decodeURIComponent(encodedName) : plainName || fallbackName; + const objectUrl = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = objectUrl; + anchor.download = filename; + anchor.click(); + URL.revokeObjectURL(objectUrl); +}; + +// Shipping customers +export interface ListShippingCustomersParams { + q?: string; + status?: string; + page?: number; + pageSize?: number; +} + +/** 分页查询货代标准客户。 */ +export const listShippingCustomers = (params: ListShippingCustomersParams = {}) => { + const qs = new URLSearchParams(); + if (params.q?.trim()) qs.set('q', params.q.trim()); + if (params.status) qs.set('status', params.status); + qs.set('page', String(params.page || 1)); + qs.set('page_size', String(params.pageSize || 20)); + return requestJson(`/api/admin/shipping-customers?${qs.toString()}`, auth()); +}; + +export const getShippingCustomer = (id: number) => + requestJson(`/api/admin/shipping-customers/${id}`, auth()); + +export const createShippingCustomer = (payload: Record) => + requestJson('/api/admin/shipping-customers', { + method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), + }); + +export const updateShippingCustomer = (id: number, payload: Record) => + requestJson(`/api/admin/shipping-customers/${id}`, { + method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), + }); + +export const deactivateShippingCustomer = (id: number) => + requestJson(`/api/admin/shipping-customers/${id}/deactivate`, { + method: 'POST', ...auth(), + }); + +export const createShippingCustomerIdentifier = (customerId: number, payload: ShippingIdentifierFormState) => + requestJson(`/api/admin/shipping-customers/${customerId}/identifiers`, { + method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), + }); + +export const updateShippingCustomerIdentifier = (identifierId: number, payload: Record) => + requestJson(`/api/admin/shipping-customer-identifiers/${identifierId}`, { + method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), + }); + +export const uploadShippingCustomerImport = (file: File, sourceSystem: string) => { + const body = new FormData(); + body.append('file', file); + body.append('source_system', sourceSystem); + return requestJson('/api/admin/shipping-customer-imports', { + method: 'POST', headers: getAuthHeaders(), body, + }); +}; + +export const decideShippingCustomerImportRow = ( + rowId: number, + payload: { action: string; target_customer_id?: number; note?: string }, +) => requestJson(`/api/admin/shipping-customer-import-rows/${rowId}/decision`, { + method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), +}); + +export const publishShippingCustomerImport = (batchId: number) => + requestJson(`/api/admin/shipping-customer-imports/${batchId}/publish`, { + method: 'POST', ...auth(), + }); + +export const downloadShippingCustomerImportTemplate = () => + downloadAdminFile('/api/admin/shipping-customers/import-template', 'shipping_customer_import_template.xlsx'); + +export const downloadShippingCustomerReconciliation = (batchId: number, batchNo: string) => + downloadAdminFile( + `/api/admin/shipping-customer-imports/${batchId}/reconciliation`, + `${batchNo}_reconciliation.csv`, + ); + +export const getShippingCustomerShadowReport = (limit = 100) => + requestJson(`/api/admin/shipping-customer-shadow-report?limit=${limit}`, auth()); + +export const labelShippingCustomerShadowResolution = (resolutionId: number, customerId: number) => + requestJson( + `/api/admin/shipping-customer-shadow-resolutions/${resolutionId}/label`, + { method: 'PUT', ...jsonAuth(), body: JSON.stringify({ customer_id: customerId }) }, + ); + // Users export const listAdminUsers = () => requestJson('/api/admin/users', auth()); diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts index 4c2e3788..2a39ea19 100644 --- a/frontend/src/features/admin/constants/modules.ts +++ b/frontend/src/features/admin/constants/modules.ts @@ -46,6 +46,7 @@ export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [ export const LEGACY_MODULE_QUERY_TO_PATH: Record = {}; export const adminModulePath = (moduleId: AdminModuleId | string): string => { + if (moduleId === 'shipping_customers') return '/workspace/shipping-notice/customers'; if (moduleId === 'reports') return '/admin/reports'; const meta = ADMIN_MODULE_METAS.find((m) => m.id === moduleId); if (meta) return `/admin/${meta.path}`; diff --git a/frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue b/frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue new file mode 100644 index 00000000..6bb138d4 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue @@ -0,0 +1,86 @@ + + + + diff --git a/frontend/src/features/admin/modules/shipping-customers/components/CustomerFormModal.vue b/frontend/src/features/admin/modules/shipping-customers/components/CustomerFormModal.vue new file mode 100644 index 00000000..1ac61bcb --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-customers/components/CustomerFormModal.vue @@ -0,0 +1,54 @@ + + + +