From e9bdd81f1a53a99b39268143c702234378b3042f Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Sat, 18 Jul 2026 11:41:02 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E4=B8=B4=E6=97=B6=E5=BA=93=E5=AD=98=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=88=9B=E5=BB=BA=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E3=80=81=E8=8E=B7=E5=8F=96=E5=88=86=E6=9E=90=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E5=8F=8A=E5=AD=97=E6=AE=B5=E6=98=A0=E5=B0=84=E5=BB=BA?= =?UTF-8?q?=E8=AE=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.dev | 121 +- .env.prod | 73 +- .env.shared | 148 +- .env.test | 132 +- AGENTS.md | 10 + backend/app/api/admin/__init__.py | 2 + backend/app/api/admin/shipping_customers.py | 133 +- backend/app/api/admin/shipping_inventory.py | 492 ++++++ .../app/api/admin/shipping_order_schema.py | 193 +++ backend/app/api/chat.py | 16 +- backend/app/api/shipping_notice_tools.py | 78 +- backend/app/api/workspace/shipping_notice.py | 89 +- backend/app/core/config/settings.py | 115 +- backend/app/models/__init__.py | 62 +- backend/app/models/shipping.py | 62 +- backend/app/models/shipping_customer.py | 124 +- .../models/shipping_customer_resolution.py | 43 +- backend/app/models/shipping_excel_template.py | 77 + .../app/models/shipping_inventory_config.py | 317 ++++ .../models/shipping_order_customer_match.py | 59 + backend/app/models/shipping_order_schema.py | 311 ++++ .../models/shipping_temporary_inventory.py | 51 + backend/app/services/admin/__init__.py | 4 + .../admin/shipping_customer_import_service.py | 7 +- .../shipping_customer_lifecycle_service.py | 244 +++ .../admin/shipping_customer_merge_service.py | 227 +++ .../admin/shipping_customer_service.py | 259 ++- .../admin/shipping_inventory_service.py | 855 ++++++++++ .../services/agent_runtime_context/parser.py | 2 + backend/app/services/schedule/job_options.py | 12 +- .../shipping_inventory_rpa_archive.py | 8 +- .../shipping_inventory_rpa_finalize.py | 6 - .../schedule/shipping_inventory_rpa_job.py | 38 +- .../shipping_notice/batch_from_intakes.py | 3 +- .../shipping_notice/batch_orchestrator.py | 24 +- .../shipping_notice/business_case_service.py | 20 +- .../chat_action_extended_handlers.py | 131 +- .../shipping_notice/chat_action_handlers.py | 31 +- .../app/services/shipping_notice/constants.py | 25 - .../shipping_notice/context_adapter.py | 6 +- .../shipping_notice/credential_crypto.py | 82 + .../customer_auto_resolution.py | 167 +- .../shipping_notice/customer_identity_gate.py | 14 +- .../customer_shadow_resolution.py | 26 +- .../shipping_notice/decision_workflow.py | 263 +-- .../services/shipping_notice/dify_inputs.py | 49 +- .../document_candidate_persist.py | 6 + .../shipping_notice/excel_template.py | 358 ++++ .../app/services/shipping_notice/export.py | 592 ++++--- .../shipping_notice/export_archive.py | 129 ++ .../field_alignment_summary.py | 4 +- .../shipping_notice/fulfillment_workflow.py | 112 +- backend/app/services/shipping_notice/i18n.py | 57 +- .../inventory_configuration_test.py | 167 ++ .../inventory_external_mapping.py | 38 + .../inventory_field_catalog.py | 190 +++ .../inventory_file_identity.py | 62 +- .../shipping_notice/inventory_file_store.py | 112 +- .../shipping_notice/inventory_mapping.py | 179 +- .../inventory_mapping_store.py | 91 - .../inventory_mapping_workflow.py | 364 +--- .../inventory_parsing_profile.py | 208 +++ .../inventory_profile_matching.py | 74 + .../inventory_routing_engine.py | 113 ++ .../shipping_notice/inventory_rpa_workflow.py | 234 ++- .../shipping_notice/inventory_snapshot.py | 133 +- .../inventory_snapshot_store.py | 79 +- .../shipping_notice/inventory_source_gate.py | 90 +- .../inventory_source_identity.py | 153 +- .../inventory_source_repository.py | 148 ++ .../shipping_notice/inventory_source_rules.py | 645 +++----- .../shipping_notice/inventory_sources.py | 457 ------ .../inventory_structure_analysis.py | 426 +++++ .../inventory_structure_drift.py | 92 ++ .../inventory_structure_fingerprint.py | 71 + .../inventory_temporary_session.py | 553 +++++++ .../shipping_notice/inventory_upload.py | 63 +- .../inventory_warehouse_resolution.py | 70 + .../shipping_notice/inventory_workflow.py | 509 +----- backend/app/services/shipping_notice/match.py | 77 +- .../shipping_notice/match_rule_desc.py | 71 +- .../services/shipping_notice/openapi_spec.py | 175 +- .../order_customer_matching.py | 246 +++ .../shipping_notice/order_extraction.py | 178 +- .../shipping_notice/order_schema/__init__.py | 11 + .../shipping_notice/order_schema/diff.py | 114 ++ .../shipping_notice/order_schema/registry.py | 74 + .../shipping_notice/order_schema/runtime.py | 423 +++++ .../shipping_notice/order_schema/service.py | 876 ++++++++++ .../shipping_notice/progress_workflow.py | 59 +- .../services/shipping_notice/query_service.py | 31 +- .../shipping_notice/reference_context.py | 1 - .../services/shipping_notice/routing_facts.py | 64 + .../shipping_notice/routing_operators.py | 62 + backend/app/services/shipping_notice/rpa.py | 43 +- .../shipping_notice/runtime_context.py | 14 + .../services/shipping_notice/state_machine.py | 97 +- .../services/shipping_notice/tool_common.py | 20 + backend/app/services/shipping_notice/tools.py | 31 +- .../app/services/shipping_notice/ui_state.py | 19 +- .../shipping_notice/user_facing_status.py | 4 - .../config/shipping_inventory_sources.yaml | 58 +- backend/init_local_db.py | 142 +- backend/local_test.db | Bin 430080 -> 1912832 bytes ...7a_add_shipping_inventory_configuration.py | 162 ++ ...f7a8b_remove_shipping_inventory_site_id.py | 79 + ..._dynamic_inventory_snapshot_idempotency.py | 38 + ..._shipping_customer_lifecycle_foundation.py | 129 ++ ...0c1d_shipping_customer_merge_foundation.py | 70 + ...2a_add_inventory_source_business_config.py | 43 + ...3f_rename_rpa_operation_to_login_config.py | 32 + .../9b0c1d2e3f4a_add_shipping_order_schema.py | 268 +++ ...amic_order_fields_for_inventory_routing.py | 42 + ...b17e3d4c5a60_inventory_parsing_profiles.py | 39 + .../c27e3d4c5a61_shipping_excel_templates.py | 81 + ...ename_erp_mappings_to_external_mappings.py | 120 ++ ...d8e_add_shipping_order_customer_matches.py | 100 ++ ...8d9e0a_add_schema_version_field_enabled.py | 28 + ...9e0f1a_add_inventory_structure_analyses.py | 41 + ...2b_add_inventory_structure_fingerprints.py | 44 + ...c_add_inventory_configuration_test_runs.py | 27 + ...3e_add_shipping_inventory_field_catalog.py | 43 + ...4f_unify_shipping_order_schema_versions.py | 101 ++ ...d_shipping_temporary_inventory_sessions.py | 48 + ...add_temporary_inventory_analysis_source.py | 31 + ...hipping_order_extraction_audit_snapshot.py | 27 + ...2d3e4f_remove_inventory_field_core_flag.py | 22 + ...a_remove_legacy_inventory_mapping_cache.py | 51 + .../import_shipping_inventory_sources.py | 167 ++ backend/tests/conftest.py | 154 +- ...est_shipping_customer_lifecycle_service.py | 280 ++++ .../test_shipping_customer_merge_service.py | 185 +++ .../admin/test_shipping_customer_service.py | 76 +- .../admin/test_shipping_inventory_service.py | 402 +++++ .../tests/test_admin_shipping_customers.py | 225 ++- .../tests/test_admin_shipping_inventory.py | 178 ++ ...est_admin_shipping_order_schema_history.py | 101 ++ backend/tests/test_chat_turn_runtime.py | 44 + backend/tests/test_crane_report_export.py | 29 +- backend/tests/test_crane_session.py | 10 +- backend/tests/test_dsv_export_batch_smoke.py | 74 - backend/tests/test_dsv_report_parameters.py | 4 +- backend/tests/test_freight_rpa_heartbeat.py | 10 +- backend/tests/test_freight_rpa_worker.py | 192 ++- ...est_freight_rpa_worker_inventory_params.py | 21 +- backend/tests/test_init_local_db.py | 78 + backend/tests/test_internal_jobs_registry.py | 2 +- .../test_inventory_configuration_test.py | 238 +++ backend/tests/test_inventory_field_catalog.py | 68 + .../tests/test_inventory_parsing_profile.py | 214 +++ .../tests/test_inventory_profile_matching.py | 105 ++ .../test_inventory_structure_analysis.py | 170 ++ .../tests/test_inventory_structure_drift.py | 173 ++ ...acy_inventory_mapping_removal_migration.py | 71 + backend/tests/test_rpa_worker_heartbeat.py | 16 +- .../tests/test_rpa_worker_heartbeat_alert.py | 4 +- backend/tests/test_schedule_platform_tasks.py | 51 +- .../test_shipping_customer_auto_resolution.py | 79 +- .../test_shipping_customer_identity_gate.py | 17 +- .../test_shipping_customer_migrations.py | 12 +- ...est_shipping_customer_shadow_resolution.py | 3 + backend/tests/test_shipping_excel_template.py | 490 ++++++ backend/tests/test_shipping_export_archive.py | 146 ++ .../test_shipping_inventory_configuration.py | 337 ++++ .../test_shipping_inventory_routing_engine.py | 136 ++ backend/tests/test_shipping_notice_batches.py | 205 ++- .../test_shipping_notice_business_case.py | 21 +- .../test_shipping_notice_inventory_aws.py | 63 +- ...t_shipping_notice_inventory_rpa_archive.py | 16 +- ..._shipping_notice_inventory_rpa_workflow.py | 361 +++- ...test_shipping_notice_inventory_schedule.py | 122 +- ...hipping_notice_inventory_snapshot_reuse.py | 233 --- ...t_shipping_notice_inventory_source_gate.py | 1214 -------------- ...hipping_notice_inventory_sources_config.py | 199 --- .../test_shipping_notice_match_rule_desc.py | 24 +- .../test_shipping_notice_openapi_contract.py | 19 +- .../test_shipping_notice_order_extraction.py | 206 ++- .../test_shipping_notice_query_service.py | 30 +- .../test_shipping_notice_reservation_id.py | 14 +- ...st_shipping_notice_rpa_trigger_for_task.py | 25 +- backend/tests/test_shipping_notice_tools.py | 1035 +++++------- .../test_shipping_order_customer_matching.py | 161 ++ backend/tests/test_shipping_order_schema.py | 445 +++++ .../tests/test_shipping_order_schema_diff.py | 147 ++ ...shipping_order_schema_enabled_migration.py | 55 + .../test_shipping_order_schema_migration.py | 73 + .../test_shipping_order_schema_runtime.py | 144 ++ ...est_shipping_order_schema_runtime_audit.py | 189 +++ ...ng_order_schema_runtime_audit_migration.py | 49 + ...der_schema_version_governance_migration.py | 97 ++ .../test_shipping_template_migrations.py | 78 + .../tests/test_temporary_inventory_session.py | 371 +++++ docs/convention/env_loading_priority.md | 8 + docs/convention/环境变量规则.md | 8 + docs/demand.md | 52 +- docs/features/shipping-notice/business.md | 176 +- .../shipping-notice/inventory_source_plan.md | 272 ++- docs/features/shipping-notice/technical.md | 1460 ++++++++++------- docs/funclist.md | 36 +- .../agent_runtime_context_tools.dify.json | 2 + docs/openapi/shipping_notice_tools.dify.json | 468 ++++-- .../shipping-inventory-config-prototype.html | 317 ++++ docs/tec.md | 31 +- docs/test_plan_matrix.md | 25 +- docs/新人环境搭建与配置文档.md | 12 + .../src/app/router/routes/admin.routes.ts | 10 +- .../src/app/router/routes/workspace.routes.ts | 2 +- frontend/src/config.ts | 1 + .../src/constants/shippingNoticeActions.ts | 6 - frontend/src/features/admin/api/admin.api.ts | 287 ++-- .../admin/api/shipping-order-schema.api.ts | 124 ++ .../features/admin/components/AdminNav.vue | 3 +- .../src/features/admin/constants/modules.ts | 4 +- .../ShippingInventoryPage.vue | 1219 ++++++++++++++ .../ShippingOrderSchemaPage.vue | 828 ++++++++++ .../components/SchemaAuditTimeline.vue | 50 + .../SchemaExtractionAuditDrawer.vue | 45 + .../components/SchemaVersionDiffDrawer.vue | 67 + .../components/SchemaVersionHistoryDrawer.vue | 153 ++ .../components/SchemaVersionUsageDrawer.vue | 46 + .../src/features/admin/types/admin.types.ts | 1 + .../types/shipping-order-schema.types.ts | 173 ++ .../src/features/chat/api/shipping.api.ts | 43 +- .../features/chat/components/ChatInputBar.vue | 2 +- .../chat/components/ChatMessageList.vue | 4 +- .../chat/components/ChatViewContent.vue | 2 +- .../ShippingBatchWorkspaceDrawer.vue | 11 +- .../ShippingNoticeCandidateReview.vue | 35 + .../components/messages/ChatMessageBubble.vue | 14 +- .../ShippingInventoryMappingMessage.vue | 122 -- .../messages/shippingMessageHandlers.ts | 18 + .../src/features/chat/composables/useChat.ts | 4 +- .../features/chat/composables/useChatPage.ts | 8 +- .../chat/composables/useChatShipping.ts | 65 +- .../src/features/chat/constants/shipping.ts | 3 - .../chat/page/useChatPageConversation.spec.ts | 1 - .../chat/page/useChatPageHandlerBundles.ts | 22 +- .../chat/page/useChatPageMarkdown.spec.ts | 1 - .../features/chat/page/useChatPageMarkdown.ts | 3 - .../src/features/chat/page/useChatPageSend.ts | 4 +- frontend/src/features/chat/shipping/index.ts | 2 - .../shipping/shippingDecisionFormat.spec.ts | 30 +- .../chat/shipping/shippingDecisionFormat.ts | 32 +- .../chat/shipping/shippingIntents.spec.ts | 29 - .../features/chat/shipping/shippingIntents.ts | 39 +- .../features/chat/shipping/shippingMapping.ts | 62 - .../features/chat/shipping/shippingMenu.ts | 8 +- .../features/chat/shipping/shippingStepper.ts | 3 - .../features/chat/shipping/shippingText.ts | 26 - .../chat/shipping/shippingTurnActions.ts | 21 - .../chat/shipping/shippingUploadPrompt.ts | 63 +- .../shipping/useChatShippingDecision.spec.ts | 19 +- .../chat/shipping/useChatShippingDecision.ts | 21 +- .../useChatShippingMappingForm.spec.ts | 98 -- .../shipping/useChatShippingMappingForm.ts | 174 -- .../useChatShippingMenuHandler.spec.ts | 1 - .../shipping/useChatShippingMenuHandler.ts | 14 - .../useChatShippingSendHandler.spec.ts | 34 + .../shipping/useChatShippingSendHandler.ts | 56 +- .../useChatShippingUploadHandler.spec.ts | 56 +- .../shipping/useChatShippingUploadHandler.ts | 93 +- .../shipping/useShippingNoticeIntakes.spec.ts | 20 + .../chat/shipping/useShippingNoticeIntakes.ts | 34 +- .../src/features/chat/types/chat.types.ts | 2 +- .../features/chat/types/shipping.api.types.ts | 29 +- .../src/features/chat/types/shipping.types.ts | 22 +- .../chat/utils/attachmentCard.utils.spec.ts | 8 +- .../chat/utils/attachmentCard.utils.ts | 8 +- .../api/customer-master.api.ts | 180 ++ .../customers}/ShippingCustomersPage.vue | 16 +- .../components/CustomerDeleteDialog.vue | 81 + .../components/CustomerFormModal.vue | 10 +- .../components/CustomerIdentifiersPanel.vue | 51 +- .../components/CustomerImportDialog.vue | 6 +- .../components/CustomerLifecyclePanel.vue | 59 + .../components/CustomerMergeDialog.vue | 66 + .../components/CustomerShadowQualityPanel.vue | 18 +- .../composables/useShippingCustomersAdmin.ts | 196 ++- .../shippingI18nParity.spec.ts | 63 + .../types/customer-master.types.ts} | 116 +- .../utils/exportSelection.spec.ts | 30 + .../shipping-notice/utils/exportSelection.ts | 43 + .../workspace/shippingTaskStatuses.spec.ts | 32 + .../workspace/shippingTaskStatuses.ts | 21 + .../workspace/views/ShippingNoticeView.vue | 156 +- frontend/src/locales/en/admin.json | 405 ++++- frontend/src/locales/en/chat.json | 52 +- frontend/src/locales/en/errors.json | 113 +- frontend/src/locales/en/workspace.json | 7 +- frontend/src/locales/th/admin.json | 390 ++++- frontend/src/locales/th/chat.json | 52 +- frontend/src/locales/th/errors.json | 113 +- frontend/src/locales/th/workspace.json | 7 +- frontend/src/locales/zh-CN/admin.json | 450 ++++- frontend/src/locales/zh-CN/chat.json | 52 +- frontend/src/locales/zh-CN/errors.json | 117 +- frontend/src/locales/zh-CN/workspace.json | 7 +- frontend/src/locales/zh-TW/admin.json | 414 ++++- frontend/src/locales/zh-TW/chat.json | 52 +- frontend/src/locales/zh-TW/errors.json | 113 +- frontend/src/locales/zh-TW/workspace.json | 7 +- scripts/rpa/README.md | 136 +- scripts/rpa/crane_export_smoke.py | 115 -- scripts/rpa/crane_login_smoke.py | 22 +- scripts/rpa/crane_navigation.py | 6 +- scripts/rpa/crane_report_export.py | 87 +- scripts/rpa/crane_session.py | 10 +- scripts/rpa/dsv_auth.py | 16 +- scripts/rpa/dsv_auth_login_flow.py | 16 +- scripts/rpa/dsv_export_batch_smoke.py | 282 ---- scripts/rpa/dsv_export_smoke.py | 150 -- scripts/rpa/dsv_login_smoke.py | 22 +- scripts/rpa/dsv_navigation.py | 4 +- scripts/rpa/dsv_report_export.py | 47 +- scripts/rpa/freight_rpa_heartbeat.py | 18 +- scripts/rpa/freight_rpa_worker.py | 305 ++-- scripts/rpa/rpa_common.py | 90 +- scripts/rpa/run_inventory_batch_trigger.py | 183 +-- scripts/rpa/set_rpa_worker_env.ps1 | 86 +- scripts/start_local.ps1 | 2 +- 320 files changed, 28361 insertions(+), 10487 deletions(-) create mode 100644 backend/app/api/admin/shipping_inventory.py create mode 100644 backend/app/api/admin/shipping_order_schema.py create mode 100644 backend/app/models/shipping_excel_template.py create mode 100644 backend/app/models/shipping_inventory_config.py create mode 100644 backend/app/models/shipping_order_customer_match.py create mode 100644 backend/app/models/shipping_order_schema.py create mode 100644 backend/app/models/shipping_temporary_inventory.py create mode 100644 backend/app/services/admin/shipping_customer_lifecycle_service.py create mode 100644 backend/app/services/admin/shipping_customer_merge_service.py create mode 100644 backend/app/services/admin/shipping_inventory_service.py create mode 100644 backend/app/services/shipping_notice/credential_crypto.py create mode 100644 backend/app/services/shipping_notice/excel_template.py create mode 100644 backend/app/services/shipping_notice/export_archive.py create mode 100644 backend/app/services/shipping_notice/inventory_configuration_test.py create mode 100644 backend/app/services/shipping_notice/inventory_external_mapping.py create mode 100644 backend/app/services/shipping_notice/inventory_field_catalog.py delete mode 100644 backend/app/services/shipping_notice/inventory_mapping_store.py create mode 100644 backend/app/services/shipping_notice/inventory_parsing_profile.py create mode 100644 backend/app/services/shipping_notice/inventory_profile_matching.py create mode 100644 backend/app/services/shipping_notice/inventory_routing_engine.py create mode 100644 backend/app/services/shipping_notice/inventory_source_repository.py delete mode 100644 backend/app/services/shipping_notice/inventory_sources.py create mode 100644 backend/app/services/shipping_notice/inventory_structure_analysis.py create mode 100644 backend/app/services/shipping_notice/inventory_structure_drift.py create mode 100644 backend/app/services/shipping_notice/inventory_structure_fingerprint.py create mode 100644 backend/app/services/shipping_notice/inventory_temporary_session.py create mode 100644 backend/app/services/shipping_notice/inventory_warehouse_resolution.py create mode 100644 backend/app/services/shipping_notice/order_customer_matching.py create mode 100644 backend/app/services/shipping_notice/order_schema/__init__.py create mode 100644 backend/app/services/shipping_notice/order_schema/diff.py create mode 100644 backend/app/services/shipping_notice/order_schema/registry.py create mode 100644 backend/app/services/shipping_notice/order_schema/runtime.py create mode 100644 backend/app/services/shipping_notice/order_schema/service.py create mode 100644 backend/app/services/shipping_notice/routing_facts.py create mode 100644 backend/app/services/shipping_notice/routing_operators.py create mode 100644 backend/migrations/versions/2b3c4d5e6f7a_add_shipping_inventory_configuration.py create mode 100644 backend/migrations/versions/3c4d5e6f7a8b_remove_shipping_inventory_site_id.py create mode 100644 backend/migrations/versions/4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency.py create mode 100644 backend/migrations/versions/5d6e7f8a9b0c_shipping_customer_lifecycle_foundation.py create mode 100644 backend/migrations/versions/6e7f8a9b0c1d_shipping_customer_merge_foundation.py create mode 100644 backend/migrations/versions/7f8e9d0c1b2a_add_inventory_source_business_config.py create mode 100644 backend/migrations/versions/8a9b0c1d2e3f_rename_rpa_operation_to_login_config.py create mode 100644 backend/migrations/versions/9b0c1d2e3f4a_add_shipping_order_schema.py create mode 100644 backend/migrations/versions/a0b1c2d3e4f5_dynamic_order_fields_for_inventory_routing.py create mode 100644 backend/migrations/versions/b17e3d4c5a60_inventory_parsing_profiles.py create mode 100644 backend/migrations/versions/c27e3d4c5a61_shipping_excel_templates.py create mode 100644 backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py create mode 100644 backend/migrations/versions/e49a5b6c7d8e_add_shipping_order_customer_matches.py create mode 100644 backend/migrations/versions/f61b7c8d9e0a_add_schema_version_field_enabled.py create mode 100644 backend/migrations/versions/f72c8d9e0f1a_add_inventory_structure_analyses.py create mode 100644 backend/migrations/versions/f83d9e0f1a2b_add_inventory_structure_fingerprints.py create mode 100644 backend/migrations/versions/f94e0f1a2b3c_add_inventory_configuration_test_runs.py create mode 100644 backend/migrations/versions/f95a0b1c2d3e_add_shipping_inventory_field_catalog.py create mode 100644 backend/migrations/versions/f96b1c2d3e4f_unify_shipping_order_schema_versions.py create mode 100644 backend/migrations/versions/f97c2d3e4f5a_add_shipping_temporary_inventory_sessions.py create mode 100644 backend/migrations/versions/f98d3e4f5a6b_add_temporary_inventory_analysis_source.py create mode 100644 backend/migrations/versions/f99e4f5a6b7c_add_shipping_order_extraction_audit_snapshot.py create mode 100644 backend/migrations/versions/fa0b1c2d3e4f_remove_inventory_field_core_flag.py create mode 100644 backend/migrations/versions/fb1c2d3e4f5a_remove_legacy_inventory_mapping_cache.py create mode 100644 backend/scripts/import_shipping_inventory_sources.py create mode 100644 backend/tests/services/admin/test_shipping_customer_lifecycle_service.py create mode 100644 backend/tests/services/admin/test_shipping_customer_merge_service.py create mode 100644 backend/tests/services/admin/test_shipping_inventory_service.py create mode 100644 backend/tests/test_admin_shipping_inventory.py create mode 100644 backend/tests/test_admin_shipping_order_schema_history.py delete mode 100644 backend/tests/test_dsv_export_batch_smoke.py create mode 100644 backend/tests/test_init_local_db.py create mode 100644 backend/tests/test_inventory_configuration_test.py create mode 100644 backend/tests/test_inventory_field_catalog.py create mode 100644 backend/tests/test_inventory_parsing_profile.py create mode 100644 backend/tests/test_inventory_profile_matching.py create mode 100644 backend/tests/test_inventory_structure_analysis.py create mode 100644 backend/tests/test_inventory_structure_drift.py create mode 100644 backend/tests/test_legacy_inventory_mapping_removal_migration.py create mode 100644 backend/tests/test_shipping_excel_template.py create mode 100644 backend/tests/test_shipping_export_archive.py create mode 100644 backend/tests/test_shipping_inventory_configuration.py create mode 100644 backend/tests/test_shipping_inventory_routing_engine.py delete mode 100644 backend/tests/test_shipping_notice_inventory_snapshot_reuse.py delete mode 100644 backend/tests/test_shipping_notice_inventory_source_gate.py delete mode 100644 backend/tests/test_shipping_notice_inventory_sources_config.py create mode 100644 backend/tests/test_shipping_order_customer_matching.py create mode 100644 backend/tests/test_shipping_order_schema.py create mode 100644 backend/tests/test_shipping_order_schema_diff.py create mode 100644 backend/tests/test_shipping_order_schema_enabled_migration.py create mode 100644 backend/tests/test_shipping_order_schema_migration.py create mode 100644 backend/tests/test_shipping_order_schema_runtime.py create mode 100644 backend/tests/test_shipping_order_schema_runtime_audit.py create mode 100644 backend/tests/test_shipping_order_schema_runtime_audit_migration.py create mode 100644 backend/tests/test_shipping_order_schema_version_governance_migration.py create mode 100644 backend/tests/test_shipping_template_migrations.py create mode 100644 backend/tests/test_temporary_inventory_session.py create mode 100644 docs/prototype/shipping-inventory-config-prototype.html create mode 100644 frontend/src/features/admin/api/shipping-order-schema.api.ts create mode 100644 frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-schema/components/SchemaAuditTimeline.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionDiffDrawer.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionHistoryDrawer.vue create mode 100644 frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue create mode 100644 frontend/src/features/admin/types/shipping-order-schema.types.ts delete mode 100644 frontend/src/features/chat/components/messages/ShippingInventoryMappingMessage.vue create mode 100644 frontend/src/features/chat/components/messages/shippingMessageHandlers.ts delete mode 100644 frontend/src/features/chat/shipping/shippingIntents.spec.ts delete mode 100644 frontend/src/features/chat/shipping/shippingMapping.ts delete mode 100644 frontend/src/features/chat/shipping/useChatShippingMappingForm.spec.ts delete mode 100644 frontend/src/features/chat/shipping/useChatShippingMappingForm.ts create mode 100644 frontend/src/features/shipping-notice/api/customer-master.api.ts rename frontend/src/features/{admin/modules/shipping-customers => shipping-notice/customers}/ShippingCustomersPage.vue (76%) create mode 100644 frontend/src/features/shipping-notice/customers/components/CustomerDeleteDialog.vue rename frontend/src/features/{admin/modules/shipping-customers => shipping-notice/customers}/components/CustomerFormModal.vue (81%) rename frontend/src/features/{admin/modules/shipping-customers => shipping-notice/customers}/components/CustomerIdentifiersPanel.vue (56%) rename frontend/src/features/{admin/modules/shipping-customers => shipping-notice/customers}/components/CustomerImportDialog.vue (97%) create mode 100644 frontend/src/features/shipping-notice/customers/components/CustomerLifecyclePanel.vue create mode 100644 frontend/src/features/shipping-notice/customers/components/CustomerMergeDialog.vue rename frontend/src/features/{admin/modules/shipping-customers => shipping-notice/customers}/components/CustomerShadowQualityPanel.vue (83%) rename frontend/src/features/{admin/modules/shipping-customers => shipping-notice/customers}/composables/useShippingCustomersAdmin.ts (57%) create mode 100644 frontend/src/features/shipping-notice/shippingI18nParity.spec.ts rename frontend/src/features/{admin/types/shipping-customer.types.ts => shipping-notice/types/customer-master.types.ts} (59%) create mode 100644 frontend/src/features/shipping-notice/utils/exportSelection.spec.ts create mode 100644 frontend/src/features/shipping-notice/utils/exportSelection.ts create mode 100644 frontend/src/features/workspace/shippingTaskStatuses.spec.ts create mode 100644 frontend/src/features/workspace/shippingTaskStatuses.ts delete mode 100644 scripts/rpa/crane_export_smoke.py delete mode 100644 scripts/rpa/dsv_export_batch_smoke.py delete mode 100644 scripts/rpa/dsv_export_smoke.py diff --git a/.env.dev b/.env.dev index 2a0a1e9b..fbd88f08 100644 --- a/.env.dev +++ b/.env.dev @@ -3,24 +3,31 @@ # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments # ============================================================================= + +# --- 1. 环境与应用标识 --- ENV_NAME=dev FLASK_ENV=development -DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops -ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client -ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31 -LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client -# 是否启用 JWT 认证 -AUTH_JWT_REQUIRED=true +# --- 2. 应用运行与进程 --- +TASK_EXECUTION_MODE=sync +# Gunicorn配置 +GUNICORN_WORKERS=10 -AUTH_LOGIN_MODE=password +# --- 3. 公共地址与网络入口 --- +# 知识库 Dify 对接 +PUBLIC_BASE_URL=http://192.168.100.192:8890 +# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠) +HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890 + +# --- 4. 安全、认证与身份源 --- # 如果需要用户密码登录,修改该值为password #AUTH_LOGIN_MODE=casdoor - +AUTH_LOGIN_MODE=password +# 是否启用 JWT 认证 +AUTH_JWT_REQUIRED=true AUTH_JWT_ISSUER=http://ait.well-trust.com:8872 AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks - # Casdoor CASDOOR_BASE_URL=http://192.168.100.192:8870 # 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用) @@ -32,18 +39,14 @@ CASDOOR_SCOPE=openid profile email CASDOOR_ORGANIZATION=organization_HX # Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可) CASDOOR_WECOM_PROVIDER_HINT=wecom - -# 知识库 Dify 对接 -PUBLIC_BASE_URL=http://192.168.100.192:8890 -DIFY_API_BASE=http://192.168.100.192:8882/v1 -DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF DEFAULT_ADMIN_USERNAME=admin DEFAULT_ADMIN_PASSWORD=admin123456 -TASK_EXECUTION_MODE=sync - -# Gunicorn配置 -GUNICORN_WORKERS=10 +# --- 5. 数据库与基础设施 --- +DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops +ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client +ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31 +LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client # MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO) # 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000 # 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致 @@ -53,67 +56,61 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx MINIO_SECURE=false MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 +# --- 6. AI 平台、模型与内部工具 --- +DIFY_API_BASE=http://192.168.100.192:8882/v1 +DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF # 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE) # RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠) HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890 -# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠) -HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890 -# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) -SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8 - -# 文件存储(相对 backend/ 根目录) -SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice - -# 解析与文本上限 -SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8 -SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8 -SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 -SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml -SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true -SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000 - -# 字段对齐确认(生产建议 true;测试可设 false) -SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true +# --- 9. 业务模块 --- # 自动推进(auto_progress) SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3 -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true # 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4) SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true -SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 -SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 -SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx - -# RPA 目录(相对 backend/ 根目录) -FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers -FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers -FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile - -# 发货 Excel 模板(可选) -FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx - -# AWS 库存列映射(可选 JSON 字符串) -# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} - +SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 # Dify Chatflow(seed_shipping_notice_agents.py) SHIPPING_NOTICE_CHAT_DIFY_APP_ID= SHIPPING_NOTICE_CHAT_DIFY_API_KEY= -SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 - +# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) +SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8 +# 文件存储(相对 backend/ 根目录) +SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice +# 解析与文本上限 +SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8 +SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8 +SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 +SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000 +SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml +SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 +# 字段对齐确认(生产建议 true;测试可设 false) +SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true +SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 +SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx +# RPA 目录(相对 backend/ 根目录) +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers +SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile +# 发货 Excel 模板(可选) +FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx +# AWS 库存列映射(可选 JSON 字符串) +# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} # 本地 RPA(scripts/rpa/freight_rpa_worker.py) -FREIGHT_RPA_MOCK=false -# FREIGHT_RPA_POLL_SECONDS=3 -# FREIGHT_RPA_SAMPLE_INVENTORY= - +SHIPPING_NOTICE_RPA_WORKER_MOCK=false +# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 +# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= +# --- 10. 运维、告警与维护工具 --- # 设备维保助手后端工具调用密钥 MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu diff --git a/.env.prod b/.env.prod index 9813397f..4e5f81a9 100644 --- a/.env.prod +++ b/.env.prod @@ -3,24 +3,31 @@ # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments # ============================================================================= + +# --- 1. 环境与应用标识 --- ENV_NAME=prod FLASK_ENV=production -DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db -ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client -ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31 -LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client -# 是否启用 JWT 认证 -AUTH_JWT_REQUIRED=true +# --- 2. 应用运行与进程 --- +TASK_EXECUTION_MODE=rq +# Gunicorn配置 +GUNICORN_WORKERS=20 +# --- 3. 公共地址与网络入口 --- +# 知识库 Dify 对接 +PUBLIC_BASE_URL=http://192.168.100.230:8891 +# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠) +HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com + +# --- 4. 安全、认证与身份源 --- # AUTH_LOGIN_MODE=casdoor # 如果需要用户密码登录,修改该值为password AUTH_LOGIN_MODE=password - +# 是否启用 JWT 认证 +AUTH_JWT_REQUIRED=true AUTH_JWT_ISSUER=http://ai.well-trust.com:8870 AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks - # Casdoor CASDOOR_BASE_URL=https://auth.well-trust.com # 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致 @@ -34,23 +41,14 @@ CASDOOR_SCOPE=openid profile email CASDOOR_ORGANIZATION=organization_HX # Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo CASDOOR_WECOM_PROVIDER_HINT=wecom - -# 知识库 Dify 对接 -PUBLIC_BASE_URL=http://192.168.100.230:8891 -DIFY_API_BASE=http://192.168.100.230:8882/v1 -DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF DEFAULT_ADMIN_USERNAME=admin DEFAULT_ADMIN_PASSWORD=admin123456 -TASK_EXECUTION_MODE=rq - -# Gunicorn配置 -GUNICORN_WORKERS=20 - -# 企业微信通知配置(如果不使用企业微信通知,留空即可) -# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL -WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/ -WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com +# --- 5. 数据库与基础设施 --- +DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db +ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client +ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31 +LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client # MinIO(知识库文档清洗图片托管,容器 minio-app) # MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1) MINIO_ENDPOINT=host.docker.internal:9000 @@ -60,37 +58,44 @@ MINIO_SECURE=false # MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问 MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000 +# --- 6. AI 平台、模型与内部工具 --- +DIFY_API_BASE=http://192.168.100.230:8882/v1 +DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF # RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠) HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890 -# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠) -HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com -# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥) -SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh +# --- 7. 企业系统集成 --- +WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com +# 企业微信通知配置(如果不使用企业微信通知,留空即可) +# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL +WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/ + +# --- 9. 业务模块 --- # 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享) SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥) +SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers -FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致) SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data +SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 - +SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers # 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv - - +# --- 10. 运维、告警与维护工具 --- # 设备维保助手后端工具调用密钥 MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu diff --git a/.env.shared b/.env.shared index 69832033..9c84875a 100644 --- a/.env.shared +++ b/.env.shared @@ -1,11 +1,38 @@ # Shared environment variables for all environments (dev/test/prod) # Keep only values that are truly identical across all environments. +# --- 1. 环境与应用标识 --- # Runtime selector fallback (actual deployment still sets ENV_NAME explicitly) ENV_NAME=dev # Common runtime defaults FLASK_APP=run.py +# --- 3. 公共地址与网络入口 --- +# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖) +HXOPS_PUBLIC_BASE_URL= + +# --- 4. 安全、认证与身份源 --- +SECRET_KEY=hxops-dify +AUTH_JWT_REQUIRED=true +# 是否保留本地密码登录/本地TWT兼容 +AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true +AUTH_ALLOW_LOCAL_JWT=true +AUTH_LOCAL_JWT_ISSUER=hxops-backend +AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend +AUTH_LOCAL_JWT_EXPIRES_HOURS=12 +# Common auth defaults +AUTH_LEGACY_HEADER_ENABLED=true + +# --- 5. 数据库与基础设施 --- +# MinIO:按环境配置见 .env.dev / .env.test / .env.prod +# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export) +# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service) +MINIO_KB_IMAGE_BUCKET=image-hosting-service +MINIO_AGENT_GUIDES_BUCKET=agent-guides + +# --- 6. AI 平台、模型与内部工具 --- +# Common integration defaults +INTEGRATION_API_MODE=local # 知识库管理(后续需要修改此地址) # 查「Dify 文档对应原始源文件下载地址」时,要连的那台 Integration API 的根 URL INTEGRATION_API_BASE=http://192.168.100.230:8891 @@ -13,41 +40,17 @@ INTEGRATION_API_BASE=http://192.168.100.230:8891 INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh # 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致 FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh +DIFY_API_BASE=https://api.dify.ai/v1 +# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖) +HXOPS_TOOLS_API_BASE= +GJL_API_BASE=https://api.siliconflow.cn/v1 +# 硅基流动相关 +GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu +GJL_MODEL=deepseek-ai/DeepSeek-V3 +# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR +ASR_MODEL=FunAudioLLM/SenseVoiceSmall -SECRET_KEY=hxops-dify - -# Knowledge base runtime -# KB_STORAGE_ROOT=backend/data/kb -KB_TASK_EXECUTION_MODE=worker -KB_WORKER_POLL_SECONDS=2 -KB_WORKER_CONCURRENCY=3 -# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径) -EDKB_SOFFICE=/usr/bin/soffice -# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右 -EDKB_SOFFICE_TIMEOUT_SEC=600 -# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽 -EDKB_WORD_TIMEOUT_SEC=300 -# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker -EDKB_FILE_TIMEOUT_SEC=300 -# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC -EDKB_WORD_FILE_TIMEOUT_SEC=420 -# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时 -KB_JOB_RUNNING_TIMEOUT_SECONDS=900 - -# chat回答的评分与评论 -FEEDBACK_ENABLED=true - -# Common auth defaults -AUTH_LEGACY_HEADER_ENABLED=true -AUTH_JWT_REQUIRED=true - -# 是否保留本地密码登录/本地TWT兼容 -AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true -AUTH_ALLOW_LOCAL_JWT=true -AUTH_LOCAL_JWT_ISSUER=hxops-backend -AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend -AUTH_LOCAL_JWT_EXPIRES_HOURS=12 - +# --- 7. 企业系统集成 --- # WeCom WECOM_ENABLED=true WECOM_CORP_ID=ww1ada6c11b684783e @@ -75,29 +78,6 @@ WECOM_FEEDBACK_NOTIFY_ENABLED=true WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881 # 企业微信群机器人 webhook,按环境写入 .env. 或部署平台变量;不要提交真实 URL。 WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498 - - -# Common integration defaults -INTEGRATION_API_MODE=local -DIFY_API_BASE=https://api.dify.ai/v1 -# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖) -HXOPS_TOOLS_API_BASE= -# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖) -HXOPS_PUBLIC_BASE_URL= - -# MinIO:按环境配置见 .env.dev / .env.test / .env.prod -# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export) -# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service) -MINIO_KB_IMAGE_BUCKET=image-hosting-service -MINIO_AGENT_GUIDES_BUCKET=agent-guides - -# 硅基流动相关 -GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu -GJL_API_BASE=https://api.siliconflow.cn/v1 -GJL_MODEL=deepseek-ai/DeepSeek-V3 -# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR -ASR_MODEL=FunAudioLLM/SenseVoiceSmall - # HR SQL Server Configuration HR_SQLSERVER_HOST=192.168.100.191 HR_SQLSERVER_PORT=1433 @@ -108,14 +88,12 @@ HR_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server HR_SQLSERVER_ENCRYPT=no HR_SQLSERVER_TRUST_CERT=yes HR_SQLSERVER_TIMEOUT=10 - # PLM Oracle PLM_ORACLE_HOST=192.168.0.11 PLM_ORACLE_PORT=1521 PLM_ORACLE_SID=orcl PLM_ORACLE_USERNAME=PLM PLM_ORACLE_PASSWORD=PLM - # SRM SQL Server Configuration SRM_SQLSERVER_HOST=192.168.55.106 SRM_SQLSERVER_PORT=1433 @@ -126,23 +104,33 @@ SRM_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server SRM_SQLSERVER_ENCRYPT=no SRM_SQLSERVER_TRUST_CERT=yes SRM_SQLSERVER_TIMEOUT=10 - # ERP ERP_DB_DSN=192.168.8.24:1521/topprod TEXT2SQL_SCHEMA_PATH= -# 固资履历共享盘 -FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 -FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 -FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv +# --- 8. 知识库与文件处理 --- +# Knowledge base runtime +# KB_STORAGE_ROOT=backend/data/kb +KB_TASK_EXECUTION_MODE=worker +KB_WORKER_POLL_SECONDS=2 +KB_WORKER_CONCURRENCY=3 +# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时 +KB_JOB_RUNNING_TIMEOUT_SECONDS=900 +# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径) +EDKB_SOFFICE=/usr/bin/soffice +# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右 +EDKB_SOFFICE_TIMEOUT_SEC=600 +# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽 +EDKB_WORD_TIMEOUT_SEC=300 +# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker +EDKB_FILE_TIMEOUT_SEC=300 +# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC +EDKB_WORD_FILE_TIMEOUT_SEC=420 -# 固资图片文档库 -FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login -FIXED_ASSET_IMAGE_USERNAME=26040006 -FIXED_ASSET_IMAGE_PASSWORD=26040006 -FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8 -FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3 +# --- 9. 业务模块 --- +# chat回答的评分与评论 +FEEDBACK_ENABLED=true # 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表) # 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置 FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过) @@ -158,13 +146,25 @@ FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相 FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效 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 # 订单行双写/切读:dual 写 + shadow 观察;全量 verify 零差异且观察窗口通过后切 table。 # 回滚:将 READ_MODE 改回 json(或 shadow)即可,本期不删 lines_json。 SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow +# RPA Profile Fernet master key; inject through Jenkins/Secret/system environment, never commit a real value. +SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= +# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。 +SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300 +# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. +SHIPPING_NOTICE_RPA_WORKER_MOCK=false +# 固资履历共享盘 +FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 +FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 +FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv +# 固资图片文档库 +FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login +FIXED_ASSET_IMAGE_USERNAME=26040006 +FIXED_ASSET_IMAGE_PASSWORD=26040006 +FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8 +FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3 diff --git a/.env.test b/.env.test index f9ad0fd6..5853d8ca 100644 --- a/.env.test +++ b/.env.test @@ -3,24 +3,30 @@ # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments # ============================================================================= + +# --- 1. 环境与应用标识 --- ENV_NAME=test FLASK_ENV=test -DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing -ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client -ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26 -LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client -# 是否启用 JWT 认证 -AUTH_JWT_REQUIRED=true +# --- 2. 应用运行与进程 --- +TASK_EXECUTION_MODE=rq +# Gunicorn配置 +GUNICORN_WORKERS=6 -AUTH_LOGIN_MODE=casdoor +# --- 3. 公共地址与网络入口 --- +# 知识库 Dify 对接 +PUBLIC_BASE_URL=http://192.168.100.192:8891 +HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com + +# --- 4. 安全、认证与身份源 --- # 如果需要用户密码登录,修改该值为password #AUTH_LOGIN_MODE=casdoor - +AUTH_LOGIN_MODE=casdoor +# 是否启用 JWT 认证 +AUTH_JWT_REQUIRED=true AUTH_JWT_ISSUER=http://ait.well-trust.com:8872 AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4 AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks - # Casdoor CASDOOR_BASE_URL=https://autht.well-trust.com # 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致 @@ -34,24 +40,14 @@ CASDOOR_SCOPE=openid profile email CASDOOR_ORGANIZATION=organization_HX # Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo CASDOOR_WECOM_PROVIDER_HINT=wecom - -# 知识库 Dify 对接 -PUBLIC_BASE_URL=http://192.168.100.192:8891 -DIFY_API_BASE=http://192.168.100.192:8882/v1 -DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF DEFAULT_ADMIN_USERNAME=admin DEFAULT_ADMIN_PASSWORD=admin123456 -TASK_EXECUTION_MODE=rq - -# Gunicorn配置 -GUNICORN_WORKERS=6 - -# 企业微信通知配置(如果不使用企业微信通知,留空即可) -# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL -WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/ -WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com -HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com +# --- 5. 数据库与基础设施 --- +DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing +ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client +ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26 +LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client # MinIO(知识库文档清洗图片托管,容器 minio-app) # MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1) # 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致 @@ -62,51 +58,56 @@ MINIO_SECURE=false # MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问 MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 +# --- 6. AI 平台、模型与内部工具 --- +DIFY_API_BASE=http://192.168.100.192:8882/v1 +DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF # 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE) # RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致) HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890 # Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh -# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥) -SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er -# 文件存储(相对 backend/ 根目录) -SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice +# --- 7. 企业系统集成 --- +WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com +# 企业微信通知配置(如果不使用企业微信通知,留空即可) +# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL +WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/ -# 解析与文本上限 -SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8 -SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8 -SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 -SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml -SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true -SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000 - -# 字段对齐确认(生产建议 true;测试可设 false) -SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true +# --- 9. 业务模块 --- # 自动推进(auto_progress) SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3 -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false # 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4) SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true -SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 -SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 -SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx - -# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享) -FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers -FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers +SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 +# Dify Chatflow(seed_shipping_notice_agents.py) +SHIPPING_NOTICE_CHAT_DIFY_APP_ID= +SHIPPING_NOTICE_CHAT_DIFY_API_KEY= +# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥) +SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er +# 文件存储(相对 backend/ 根目录) +SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice +# 解析与文本上限 +SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8 +SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8 +SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 +SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000 +SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml +SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 +# 字段对齐确认(生产建议 true;测试可设 false) +SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐) SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data +SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 +SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 两者皆无则告警只写日志、不会发企微 @@ -114,29 +115,26 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true # 企微发送中短锁秒数(发送失败过期后可重试,默认 120) SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 - +SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 +SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx +# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享) +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers # 发货 Excel 模板(可选) FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx - +# AWS 库存列映射(可选 JSON 字符串) +# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} +# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选) +# SHIPPING_NOTICE_RPA_WORKER_MOCK=true +# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 +# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= # 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv - -# AWS 库存列映射(可选 JSON 字符串) -# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} - -# Dify Chatflow(seed_shipping_notice_agents.py) -SHIPPING_NOTICE_CHAT_DIFY_APP_ID= -SHIPPING_NOTICE_CHAT_DIFY_API_KEY= -SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 - -# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选) -# FREIGHT_RPA_MOCK=true -# FREIGHT_RPA_POLL_SECONDS=3 -# FREIGHT_RPA_SAMPLE_INVENTORY= - - +# --- 10. 运维、告警与维护工具 --- # 设备维保助手后端工具调用密钥 MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu diff --git a/AGENTS.md b/AGENTS.md index 39f8d43a..8fbba1da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -157,6 +157,16 @@ docker compose logs -f hxops-backend - ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。 - ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。 +### 8.1 环境变量文件与排序规则 + +- **文件职责**:`.env.shared` 仅放 dev/test/prod 完全一致的共享项;`.env.dev`、`.env.test`、`.env.prod` 仅放环境差异项;`.env.local` 仅放开发者个人覆盖项且不得提交。高优先级文件只写需要覆盖的变量,不完整复制低优先级文件。 +- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。 +- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。 +- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。 +- **RPA 命名空间(强制)**:货代发货通知 RPA 统一使用 `SHIPPING_NOTICE_RPA_*`。后端业务参数使用 `SHIPPING_NOTICE_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,平台凭据主密钥使用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`;历史名称只能存在于兼容映射和迁移说明中。 +- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。 +- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。 + 合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。 --- diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index 5aa19161..7cbeef34 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -20,5 +20,7 @@ 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 +import app.api.admin.shipping_inventory # noqa: F401 +import app.api.admin.shipping_order_schema # noqa: F401 __all__ = ['admin_bp'] diff --git a/backend/app/api/admin/shipping_customers.py b/backend/app/api/admin/shipping_customers.py index 8fe1ef3c..2ee0d43f 100644 --- a/backend/app/api/admin/shipping_customers.py +++ b/backend/app/api/admin/shipping_customers.py @@ -15,14 +15,17 @@ 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.admin import ( + shipping_customer_import_service, + shipping_customer_lifecycle_service, + shipping_customer_merge_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, ) @@ -55,6 +58,77 @@ def get_shipping_customer(customer_id: int): return jsonify(shipping_customer_service.get_customer(customer_id)) +@admin_bp.route('/shipping-customers//lifecycle-impact', methods=['GET']) +@require_admin +def get_shipping_customer_lifecycle_impact(customer_id: int): + """预览永久删除的阻断引用与可级联识别证据,不执行删除。""" + return jsonify(shipping_customer_lifecycle_service.get_customer_lifecycle_impact(customer_id)) + + +@admin_bp.route('/shipping-customers//lifecycle-timeline', methods=['GET']) +@require_admin +def get_shipping_customer_lifecycle_timeline(customer_id: int): + """查询客户创建、变更、证据、归并和删除相关的治理时间线。""" + try: + limit = int(request.args.get('limit') or 100) + except (TypeError, ValueError) as exc: + raise ValidationError('Invalid timeline limit') from exc + return jsonify(shipping_customer_lifecycle_service.get_customer_lifecycle_timeline(customer_id, limit=limit)) + + +@admin_bp.route('/shipping-customers/governance-quality', methods=['GET']) +@require_admin +def get_shipping_customer_governance_quality(): + """查询客户识别质量、自动确认门禁和生命周期治理汇总。""" + try: + limit = int(request.args.get('limit') or 100) + except (TypeError, ValueError) as exc: + raise ValidationError('Invalid report limit') from exc + return jsonify(shipping_customer_lifecycle_service.get_customer_governance_quality(limit=limit)) + + +@admin_bp.route('/shipping-customers/', methods=['DELETE']) +@require_admin +def delete_shipping_customer(customer_id: int): + """受控永久删除无生命周期引用的误建客户,必须二次确认简码和原因。""" + data = request.get_json(silent=True) or {} + return jsonify(shipping_customer_lifecycle_service.delete_customer( + customer_id, + confirmation_short_code=data.get('confirmation_short_code'), + reason=data.get('reason'), + actor_id=_actor_id(), + )) + + +@admin_bp.route('/shipping-customers//merge-impact', methods=['GET']) +@require_admin +def get_shipping_customer_merge_impact(customer_id: int): + """预览将源客户归并到目标客户时保留的历史引用和可迁移配置。""" + try: + target_customer_id = int(request.args.get('target_customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('Target customer id is required', code='SHIPPING.CUSTOMER_MERGE_TARGET_REQUIRED') from exc + return jsonify(shipping_customer_merge_service.get_customer_merge_impact(customer_id, target_customer_id)) + + +@admin_bp.route('/shipping-customers//merge', methods=['POST']) +@require_admin +def merge_shipping_customer(customer_id: int): + """受控归并重复客户;历史业务与审计不迁移,仅归并未来配置。""" + data = request.get_json(silent=True) or {} + try: + target_customer_id = int(data.get('target_customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('Target customer id is required', code='SHIPPING.CUSTOMER_MERGE_TARGET_REQUIRED') from exc + return jsonify(shipping_customer_merge_service.merge_customer( + customer_id, + target_customer_id=target_customer_id, + confirmation_short_code=data.get('confirmation_short_code'), + reason=data.get('reason'), + actor_id=_actor_id(), + )) + + @admin_bp.route('/shipping-customers', methods=['POST']) @require_admin def create_shipping_customer(): @@ -77,7 +151,12 @@ def update_shipping_customer(customer_id: int): @require_admin def deactivate_shipping_customer(customer_id: int): """停用标准客户并保留历史引用。""" - return jsonify(shipping_customer_service.deactivate_customer(customer_id, actor_id=_actor_id())) + data = request.get_json(silent=True) or {} + return jsonify(shipping_customer_service.deactivate_customer( + customer_id, + reason=data.get('reason'), + actor_id=_actor_id(), + )) @admin_bp.route('/shipping-customers//identifiers', methods=['POST']) @@ -102,6 +181,33 @@ def update_shipping_customer_identifier(identifier_id: int): )) +@admin_bp.route('/shipping-customers//external-refs', methods=['POST']) +@require_admin +def create_shipping_customer_external_ref(customer_id: int): + """维护来源系统客户编码,供 Bill-to 精确匹配。""" + return jsonify(shipping_customer_service.create_external_ref( + customer_id, request.get_json(silent=True) or {}, + )), 201 + + +@admin_bp.route('/shipping-customers//sites', methods=['POST']) +@require_admin +def create_shipping_customer_site(customer_id: int): + """新增客户送货站点,供 Ship-to 匹配。""" + return jsonify(shipping_customer_service.create_site( + customer_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + )), 201 + + +@admin_bp.route('/shipping-customer-sites//identifiers', methods=['POST']) +@require_admin +def create_shipping_customer_site_identifier(site_id: int): + """新增站点名称别名、地址或外部 Ship-to Code。""" + return jsonify(shipping_customer_service.create_site_identifier( + site_id, request.get_json(silent=True) or {}, + )), 201 + + @admin_bp.route('/shipping-customers/import-template', methods=['GET']) @require_admin def download_shipping_customer_import_template(): @@ -183,25 +289,6 @@ def get_shipping_customer_shadow_report(): 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(): diff --git a/backend/app/api/admin/shipping_inventory.py b/backend/app/api/admin/shipping_inventory.py new file mode 100644 index 00000000..33331ed6 --- /dev/null +++ b/backend/app/api/admin/shipping_inventory.py @@ -0,0 +1,492 @@ +""" +api/admin/shipping_inventory.py + +用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。 +依赖:admin blueprint、require_admin、shipping_inventory_service。 +逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。 +""" + +from __future__ import annotations + +import json + +from flask import g, request, send_file + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.errors import ConflictError +from app.core.response import ok +from app.services.admin import shipping_inventory_service +from app.services.shipping_notice.order_schema import service as order_schema_service +from app.services.shipping_notice import inventory_parsing_profile +from app.services.shipping_notice import excel_template +from app.services.shipping_notice import inventory_field_catalog +from app.services.shipping_notice import inventory_structure_analysis + + +def _actor_id() -> int | None: + """取得 require_admin 已写入请求上下文的管理员 ID。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _ok(data, *, status: int = 200): + """按平台统一 envelope 返回管理 API 成功结果。""" + return ok(data, request_id=getattr(g, 'request_id', None), status=status) + + +@admin_bp.route('/shipping-notice/excel-templates', methods=['GET']) +@require_admin +def list_shipping_excel_templates(): + """列出版本化发货 Excel 模板。""" + return _ok(excel_template.list_templates()) + + +@admin_bp.route('/shipping-notice/excel-templates', methods=['POST']) +@require_admin +def create_shipping_excel_template(): + """上传 xlsx 并创建模板草稿版本。""" + try: + definition = json.loads(request.form.get('definition') or '{}') + except json.JSONDecodeError as exc: + from app.core.errors import ValidationError + raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc + data = { + 'template_code': request.form.get('template_code'), + 'display_name': request.form.get('display_name'), + 'definition': definition, + } + return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/excel-templates/', methods=['PUT']) +@require_admin +def update_shipping_excel_template(template_id: int): + """更新 Excel 模板草稿定义。""" + return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {})) + + +@admin_bp.route('/shipping-notice/excel-templates//layout', methods=['GET']) +@require_admin +def get_shipping_excel_template_layout(template_id: int): + """读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。""" + return _ok(excel_template.get_layout(template_id)) + + +@admin_bp.route('/shipping-notice/excel-templates//new-version', methods=['POST']) +@require_admin +def create_shipping_excel_template_version(template_id: int): + """复制现有模板文件和映射定义,创建新的草稿版本。""" + return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/excel-templates//publish', methods=['POST']) +@require_admin +def publish_shipping_excel_template(template_id: int): + """校验工作簿和字段映射后发布模板。""" + return _ok(excel_template.publish(template_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/excel-templates//retire', methods=['POST']) +@require_admin +def retire_shipping_excel_template(template_id: int): + """退役没有启用库存源引用的模板。""" + return _ok(excel_template.retire(template_id)) + + +@admin_bp.route('/shipping-notice/excel-templates/', methods=['DELETE']) +@require_admin +def delete_shipping_excel_template(template_id: int): + """删除从未发布且未使用的模板草稿。""" + excel_template.delete_draft(template_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET']) +@require_admin +def list_shipping_rpa_profiles(): + """列出脱敏后的 RPA Profile 配置。""" + return _ok(shipping_inventory_service.list_profiles()) + + +@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST']) +@require_admin +def create_shipping_rpa_profile(): + """创建 RPA Profile;明文凭据仅在本次请求内用于加密。""" + return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/rpa-profiles/', methods=['PUT']) +@require_admin +def update_shipping_rpa_profile(profile_id: int): + """更新 RPA Profile;未提交密码字段时保留既有密文。""" + return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id)) + + +@admin_bp.route('/shipping-notice/rpa-profiles/', methods=['DELETE']) +@require_admin +def delete_shipping_rpa_profile(profile_id: int): + """删除没有库存源引用的错误连接配置。""" + shipping_inventory_service.delete_profile(profile_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/sources', methods=['GET']) +@require_admin +def list_shipping_inventory_sources(): + """列出库存业务来源。""" + return _ok(shipping_inventory_service.list_sources()) + + +@admin_bp.route('/shipping-notice/sources', methods=['POST']) +@require_admin +def create_shipping_inventory_source(): + """保存停用的库存站点基础配置;正式启用由独立接口控制。""" + return _ok(shipping_inventory_service.save_source( + request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False, + ), status=201) + + +@admin_bp.route('/shipping-notice/sources/', methods=['PUT']) +@require_admin +def update_shipping_inventory_source(source_id: int): + """更新库存站点业务配置;不能借由普通保存绕过启用门禁。""" + return _ok(shipping_inventory_service.save_source( + request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id, + allow_enable_transition=False, + )) + + +@admin_bp.route('/shipping-notice/sources//activate', methods=['POST']) +@require_admin +def activate_shipping_inventory_source(source_id: int): + """仅在库存站点完成测试与必需绑定后启用正式运行。""" + return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/sources//deactivate', methods=['POST']) +@require_admin +def deactivate_shipping_inventory_source(source_id: int): + """停用库存站点而不删除已有配置和运行审计。""" + return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/sources/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_source(source_id: int): + """删除无运行/路由引用的错误库存源。""" + shipping_inventory_service.delete_source(source_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/sources//test-export', methods=['POST']) +@require_admin +def start_shipping_inventory_configuration_test(source_id: int): + """为停用库存站点发起异步测试导出,不产生生产库存快照。""" + from app.services.shipping_notice import inventory_configuration_test + + return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202) + + +@admin_bp.route('/shipping-notice/sources//test-export/', methods=['GET']) +@require_admin +def get_shipping_inventory_configuration_test(source_id: int, run_no: str): + """读取库存站点测试导出的异步执行状态与结构识别结果。""" + from app.services.shipping_notice import inventory_configuration_test + + return _ok(inventory_configuration_test.get_test_run(source_id, run_no)) + + +@admin_bp.route('/shipping-notice/sources//test-export//confirm-profile', methods=['POST']) +@require_admin +def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str): + """确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。""" + from app.services.shipping_notice import inventory_configuration_test + + payload = request.get_json(silent=True) or {} + return _ok(inventory_configuration_test.confirm_test_profile( + source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(), + )) + + +@admin_bp.route('/shipping-notice/snapshots', methods=['GET']) +@require_admin +def list_shipping_inventory_snapshots(): + """列出库存快照的管理端只读记录。""" + return _ok(shipping_inventory_service.list_snapshots()) + + +@admin_bp.route('/shipping-notice/snapshots//download', methods=['GET']) +@require_admin +def download_shipping_inventory_snapshot(snapshot_id: int): + """下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。""" + path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id) + return send_file(path, as_attachment=True, download_name=filename) + + +@admin_bp.route('/shipping-notice/export-records', methods=['GET']) +@require_admin +def list_shipping_inventory_export_records(): + """列出 RPA 导出结果;失败后应修复配置并重新创建运行。""" + return _ok(shipping_inventory_service.list_export_records()) + + +@admin_bp.route('/shipping-notice/routing-rules', methods=['GET']) +@require_admin +def list_shipping_inventory_rules(): + """列出库存源路由规则及条件。""" + return _ok(shipping_inventory_service.list_rules()) + + +@admin_bp.route('/shipping-notice/routing-fields', methods=['GET']) +@require_admin +def list_shipping_inventory_routing_fields(): + """返回已发布订单字段与受控系统事实;未发布时保留页面可加载的空目录。""" + try: + contract = order_schema_service.get_published_contract() + order_fields = contract['fields'] + published = True + except ConflictError as exc: + if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED': + raise + order_fields = [] + published = False + from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS + return _ok({ + 'order_fields': order_fields, + 'system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS), + 'order_schema_published': published, + }) + + +@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET']) +@require_admin +def list_shipping_inventory_fields(): + """列出库存统一业务字段;管理工作区可查看已停用字段。""" + return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true')) + + +@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST']) +@require_admin +def create_shipping_inventory_field(): + """创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。""" + return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/inventory-fields/', methods=['PUT']) +@require_admin +def update_shipping_inventory_field(field_id: int): + """更新库存业务字段的名称、说明、格式和展示顺序。""" + return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/inventory-fields//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_field(field_id: int): + """停用无引用的扩展库存字段,核心字段始终由服务层保护。""" + return _ok(inventory_field_catalog.retire_field(field_id)) + + +@admin_bp.route('/shipping-notice/inventory-fields/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_field(field_id: int): + """删除未被配置引用的扩展库存字段。""" + inventory_field_catalog.delete_field(field_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET']) +@require_admin +def get_shipping_inventory_configuration_catalog(): + """返回 Profile、模板和路由编辑器共用的后端受控字段目录。""" + from app.services.shipping_notice.excel_template import ( + ALLOWED_FORMATTERS, + ALLOWED_ROW_MODES, + ALLOWED_SOURCE_KINDS, + ALLOWED_SYSTEM_FACTS, + ) + from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS + + try: + contract = order_schema_service.get_published_contract() + order_fields = contract['fields'] + published = True + except ConflictError as exc: + if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED': + raise + order_fields = [] + published = False + return _ok({ + 'order_fields': order_fields, + 'order_schema_published': published, + 'routing_system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS), + 'inventory_fields': inventory_field_catalog.list_fields(), + 'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS), + 'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS), + 'template_row_modes': sorted(ALLOWED_ROW_MODES), + 'template_formatters': sorted(ALLOWED_FORMATTERS), + }) + + +@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET']) +@require_admin +def list_shipping_inventory_parsing_profiles(): + """列出可复用库存解析 Profile 版本。""" + return _ok(inventory_parsing_profile.list_profiles()) + + +@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST']) +@require_admin +def create_shipping_inventory_parsing_profile(): + """创建库存解析 Profile 草稿。""" + return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/parsing-profiles/', methods=['PUT']) +@require_admin +def update_shipping_inventory_parsing_profile(profile_id: int): + """更新库存解析 Profile 草稿。""" + return _ok(inventory_parsing_profile.save_draft( + request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id, + )) + + +@admin_bp.route('/shipping-notice/parsing-profiles//publish', methods=['POST']) +@require_admin +def publish_shipping_inventory_parsing_profile(profile_id: int): + """发布库存解析 Profile。""" + return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/parsing-profiles//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_parsing_profile(profile_id: int): + """退役无库存源引用的已发布解析 Profile。""" + return _ok(inventory_parsing_profile.retire(profile_id)) + + +@admin_bp.route('/shipping-notice/parsing-profiles/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_parsing_profile(profile_id: int): + """删除从未发布的解析 Profile 草稿。""" + inventory_parsing_profile.delete_draft(profile_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST']) +@require_admin +def create_shipping_inventory_structure_analysis(): + """上传库存样本并返回后端分析出的工作表、表头、栏位和建议。""" + return _ok(inventory_structure_analysis.create_sample_upload( + request.files.get('file'), actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/inventory-structure-analyses/', methods=['GET']) +@require_admin +def get_shipping_inventory_structure_analysis(analysis_id: int): + """读取库存样本结构分析结果,供管理端继续配置解析方案。""" + return _ok(inventory_structure_analysis.get_analysis(analysis_id)) + + +@admin_bp.route('/shipping-notice/inventory-structure-analyses//create-profile-draft', methods=['POST']) +@require_admin +def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int): + """使用确认后的真实表头和匹配键创建库存文件解析方案草稿。""" + return _ok(inventory_structure_analysis.create_profile_draft( + analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/inventory-structure-analyses//adopt-profile', methods=['POST']) +@require_admin +def adopt_shipping_inventory_parsing_profile(analysis_id: int): + """确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。""" + payload = request.get_json(silent=True) or {} + return _ok(inventory_structure_analysis.adopt_published_profile( + analysis_id, int(payload.get('profile_id') or 0), + )) + + +@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET']) +@require_admin +def list_confirmed_shipping_temporary_inventory_sessions(): + """列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。""" + from app.services.shipping_notice import inventory_temporary_session + + return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions()) + + +@admin_bp.route('/shipping-notice/temporary-inventory-sessions//create-profile-draft', methods=['POST']) +@require_admin +def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str): + """管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。""" + from app.services.shipping_notice import inventory_temporary_session + + return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session( + session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/routing-rules', methods=['POST']) +@require_admin +def create_shipping_inventory_rule(): + """创建草稿路由规则。""" + return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/routing-rules/', methods=['PUT']) +@require_admin +def update_shipping_inventory_rule(rule_id: int): + """更新草稿规则;已发布规则由服务层拒绝原地修改。""" + return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id)) + + +@admin_bp.route('/shipping-notice/routing-rules//publish', methods=['POST']) +@require_admin +def publish_shipping_inventory_rule(rule_id: int): + """发布草稿规则并写入不可变定义快照。""" + return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/routing-rules//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_rule(rule_id: int): + """归档已发布规则,保留其审计版本但停止新路由使用。""" + return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/routing-rules/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_rule(rule_id: int): + """删除从未发布的草稿规则。""" + shipping_inventory_service.delete_draft_rule(rule_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/external-mappings', methods=['GET']) +@require_admin +def list_shipping_inventory_external_mappings(): + """列出库存源到外部系统仓库映射。""" + return _ok(shipping_inventory_service.list_external_mappings()) + + +@admin_bp.route('/shipping-notice/external-mappings', methods=['POST']) +@require_admin +def create_shipping_inventory_external_mapping(): + """创建精确或 Source 默认外部系统映射。""" + return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/external-mappings/', methods=['PUT']) +@require_admin +def update_shipping_inventory_external_mapping(mapping_id: int): + """更新外部系统映射,不参与任何调拨动作。""" + return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id)) + + +@admin_bp.route('/shipping-notice/external-mappings/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_external_mapping(mapping_id: int): + """删除错误的外部系统仓库映射。""" + shipping_inventory_service.delete_external_mapping(mapping_id) + return '', 204 diff --git a/backend/app/api/admin/shipping_order_schema.py b/backend/app/api/admin/shipping_order_schema.py new file mode 100644 index 00000000..5bfcabac --- /dev/null +++ b/backend/app/api/admin/shipping_order_schema.py @@ -0,0 +1,193 @@ +""" +backend/app/api/admin/shipping_order_schema.py + +用途:提供唯一货代订单 Schema、字段目录和版本发布的管理 API。 +依赖:admin blueprint、require_admin、order_schema.service。 +逻辑:路由只读取参数和管理员身份;字段校验、不可变性与事务由领域服务完成。 +""" + +from __future__ import annotations + +from flask import g, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.response import ok +from app.services.shipping_notice.order_schema import service + + +def _actor_id() -> int | None: + """读取 require_admin 写入请求上下文的管理员 ID。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _ok(data, *, status: int = 200): + """按平台统一 envelope 返回管理 API 成功结果。""" + return ok(data, request_id=getattr(g, 'request_id', None), status=status) + + +@admin_bp.route('/shipping-order-schema', methods=['GET']) +@require_admin +def get_shipping_order_schema(): + """读取订单 Schema 管理状态和受控字段能力目录。""" + return _ok(service.get_state()) + + +@admin_bp.route('/shipping-order-schema', methods=['POST']) +@require_admin +def initialize_shipping_order_schema(): + """初始化全局唯一订单 Schema。""" + return _ok(service.initialize_schema(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-order-schema/fields', methods=['POST']) +@require_admin +def create_shipping_order_field(): + """创建稳定订单字段身份。""" + return _ok(service.save_field( + request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None), + ), status=201) + + +@admin_bp.route('/shipping-order-schema/fields/', methods=['PUT']) +@require_admin +def update_shipping_order_field(field_id: str): + """更新尚未发布的字段 code/scope/type;发布后服务层限制身份变更。""" + return _ok(service.save_field( + request.get_json(silent=True) or {}, actor_id=_actor_id(), field_id=field_id, + request_id=getattr(g, 'request_id', None), + )) + + +@admin_bp.route('/shipping-order-schema/fields//retire', methods=['POST']) +@require_admin +def retire_shipping_order_field(field_id: str): + """退役订单字段,保留历史发布版本中的不可变定义。""" + return _ok(service.retire_field( + field_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None), + )) + + +@admin_bp.route('/shipping-order-schema/fields/', methods=['DELETE']) +@require_admin +def delete_shipping_order_field(field_id: str): + """按字段是否存在历史引用自动物理删除或归档,并同步移出当前草稿。""" + return _ok(service.delete_field( + field_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None), + )) + + +@admin_bp.route('/shipping-order-schema/versions', methods=['POST']) +@require_admin +def create_shipping_order_schema_version(): + """创建下一订单 Schema 草稿,可复制已有版本。""" + return _ok(service.create_draft( + request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None), + ), status=201) + + +@admin_bp.route('/shipping-order-schema/versions', methods=['GET']) +@require_admin +def list_shipping_order_schema_versions(): + """分页读取订单 Schema 全部版本概要,供历史抽屉按需加载。""" + try: + page = int(request.args.get('page', '1')) + page_size = int(request.args.get('page_size', '20')) + version_number = request.args.get('version_number') + parsed_version_number = int(version_number) if version_number is not None else None + except ValueError as exc: + raise service.ValidationError('page must be an integer') from exc + return _ok(service.list_versions( + page=page, page_size=page_size, version_number=parsed_version_number, + )) + + +@admin_bp.route('/shipping-order-schema/versions/', methods=['GET']) +@require_admin +def get_shipping_order_schema_version(version_id: int): + """读取一个版本的完整只读快照,供历史查看和后续版本比较使用。""" + return _ok(service.get_version_detail(version_id)) + + +@admin_bp.route('/shipping-order-schema/versions//diff', methods=['GET']) +@require_admin +def get_shipping_order_schema_version_diff(version_id: int): + """返回两个版本之间由服务端计算的字段级语义差异。""" + try: + against_version_id = int(request.args['against_version_id']) + except (KeyError, ValueError) as exc: + raise service.ValidationError( + 'against_version_id is required', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID', + ) from exc + return _ok(service.get_version_diff(version_id, against_version_id=against_version_id)) + + +@admin_bp.route('/shipping-order-schema/audit-events', methods=['GET']) +@require_admin +def list_shipping_order_schema_audit_events(): + """分页读取订单 Schema 的只读配置审计时间线。""" + try: + page = int(request.args.get('page', '1')) + page_size = int(request.args.get('page_size', '20')) + version_id = request.args.get('version_id') + parsed_version_id = int(version_id) if version_id is not None else None + except ValueError as exc: + raise service.ValidationError('page must be an integer') from exc + return _ok(service.list_audit_events(page=page, page_size=page_size, version_id=parsed_version_id)) + + +@admin_bp.route('/shipping-order-schema/versions//usage', methods=['GET']) +@require_admin +def get_shipping_order_schema_version_usage(version_id: int): + """分页返回实际使用该版本的订单解析及状态汇总。""" + try: + page = int(request.args.get('page', '1')) + page_size = int(request.args.get('page_size', '20')) + except ValueError as exc: + raise service.ValidationError('page must be an integer') from exc + return _ok(service.get_version_usage(version_id, page=page, page_size=page_size)) + + +@admin_bp.route('/shipping-order-schema/order-extractions/', methods=['GET']) +@require_admin +def get_shipping_order_schema_extraction_audit(extraction_id: int): + """读取一次订单解析的完整只读审计详情与证据链。""" + return _ok(service.get_extraction_audit(extraction_id)) + + +@admin_bp.route('/shipping-order-schema/versions/', methods=['PUT']) +@require_admin +def update_shipping_order_schema_version(version_id: int): + """整体替换草稿字段配置。""" + return _ok(service.save_draft( + version_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + request_id=getattr(g, 'request_id', None), + )) + + +@admin_bp.route('/shipping-order-schema/versions/', methods=['DELETE']) +@require_admin +def delete_shipping_order_schema_version(version_id: int): + """删除错误草稿,已发布和退役版本由服务层保护。""" + service.delete_draft( + version_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None), + ) + return '', 204 + + +@admin_bp.route('/shipping-order-schema/versions//publish', methods=['POST']) +@require_admin +def publish_shipping_order_schema_version(version_id: int): + """发布草稿并自动退役上一当前版本。""" + data = request.get_json(silent=True) or {} + return _ok(service.publish( + version_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'), + request_id=getattr(g, 'request_id', None), + )) + + +@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET']) +@require_admin +def get_published_shipping_order_contract(): + """读取当前发布的精简字段契约,供配置验证和 Dify 文档维护使用。""" + return _ok(service.get_published_contract()) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 42c240c0..034b723f 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -142,6 +142,8 @@ def _build_chat_adapter_hints( shipping_task_id: str | None = None, shipping_batch_no: str | None = None, shipping_intake_nos: list[str] | None = None, + shipping_temporary_inventory_asset_no: str | None = None, + shipping_temporary_inventory_session_no: str | None = None, ) -> dict | None: """ 构建聊天入口分发给领域 adapter 的提示字典。 @@ -152,14 +154,18 @@ def _build_chat_adapter_hints( task_id = str(shipping_task_id or '').strip() batch_no = str(shipping_batch_no or '').strip() intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()}) - if not task_id and not batch_no and not intake_nos: + temporary_asset_no = str(shipping_temporary_inventory_asset_no or '').strip().upper() + temporary_session_no = str(shipping_temporary_inventory_session_no or '').strip().upper() + if not task_id and not batch_no and not intake_nos and not temporary_asset_no and not temporary_session_no: return None return { 'shipping_notice': { 'task_id': task_id or None, 'batch_no': batch_no or None, 'intake_nos': intake_nos, - 'capability': 'order_extraction' if intake_nos else None, + 'capability': 'temporary_inventory' if temporary_asset_no else ('order_extraction' if intake_nos else None), + 'temporary_inventory_asset_no': temporary_asset_no or None, + 'temporary_inventory_session_no': temporary_session_no or None, } } @@ -1385,6 +1391,8 @@ def chat_completions(): conversation_id = data.get('conversation_id') shipping_task_id = str(data.get('task_id') or '').strip() shipping_batch_no = str(data.get('batch_no') or '').strip() + shipping_temporary_inventory_asset_no = str(data.get('shipping_temporary_inventory_asset_no') or '').strip().upper() + shipping_temporary_inventory_session_no = str(data.get('shipping_temporary_inventory_session_no') or '').strip().upper() raw_shipping_intakes = data.get('shipping_intake_nos') if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list): raise ValidationError('shipping_intake_nos must be a list') @@ -1532,6 +1540,8 @@ def chat_completions(): shipping_task_id=shipping_task_id, shipping_batch_no=shipping_batch_no, shipping_intake_nos=shipping_intake_nos, + shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no, + shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no, ), shipping_task_id=shipping_task_id, shipping_batch_no=shipping_batch_no, @@ -1575,6 +1585,8 @@ def chat_completions(): shipping_task_id=shipping_task_id, shipping_batch_no=shipping_batch_no, shipping_intake_nos=shipping_intake_nos, + shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no, + shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no, ), ), ) diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index dad7b020..c3e20b1c 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -157,6 +157,42 @@ def tool_submit_order_extraction(): """ return jsonify(shipping_tools.submit_order_extraction(_payload())) + +@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST']) +def tool_create_temporary_inventory_session(): + """ + 创建对话上传库存候选会话。 + 【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。 + """ + return jsonify(shipping_tools.create_temporary_inventory_session(_payload())) + + +@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST']) +def tool_get_temporary_inventory_session(): + """ + 读取临时库存候选的脱敏分析结果。 + 【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。 + """ + return jsonify(shipping_tools.get_temporary_inventory_session(_payload())) + + +@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST']) +def tool_submit_temporary_inventory_mapping_suggestion(): + """ + 保存临时库存字段映射建议。 + 【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。 + """ + return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload())) + + +@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST']) +def tool_confirm_temporary_inventory_use(): + """ + 确认本次对话临时库存文件的使用。 + 【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。 + """ + return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload())) + @shipping_notice_bp.route('/tools/create_batch', methods=['POST']) def tool_create_batch(): """ @@ -215,40 +251,6 @@ def tool_remove_notice_line(): """ return jsonify(shipping_tools.remove_notice_line(_payload())) -@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST']) -def tool_parse_inventory(): - """ - 解析库存内容。 - 【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。 - """ - return jsonify(shipping_tools.parse_inventory(_payload())) - -@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST']) -def tool_upload_inventory_file(): - """ - 服务器侧接收库存 Excel 并解析。 - 【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。 - """ - task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip() - upload = request.files.get('file') - return jsonify(shipping_tools.upload_inventory_file(task_id, upload)) - -@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST']) -def tool_get_inventory_schema_preview(): - """ - 获取库存表头预览。 - 【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。 - """ - return jsonify(shipping_tools.get_inventory_schema_preview(_payload())) - -@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST']) -def tool_apply_inventory_mapping(): - """ - 应用库存字段映射。 - 【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。 - """ - return jsonify(shipping_tools.apply_inventory_mapping(_payload())) - @shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST']) def tool_ensure_inventory(): """ @@ -391,6 +393,14 @@ def rpa_inventory_batch_ready(): """RPA 批量库存导出回调:按 Warehouse 写入库存快照。""" return jsonify(shipping_tools.rpa_report_inventory_batch(_payload())) + +@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST']) +def rpa_inventory_configuration_test_ready(): + """RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。""" + from app.services.shipping_notice import inventory_configuration_test + + return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())}) + @shipping_notice_bp.route('/tasks//repair-inventory-attachment', methods=['POST']) def repair_task_inventory_attachment(task_no: str): """ diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index f95b4859..a9ec6b0f 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -15,13 +15,12 @@ from app import db from app.core.auth.jwt import get_current_user from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError from app.core.response import ok -from app.models import ShippingBatch, ShippingTask +from app.models import ShippingBatch, ShippingNoticeIntake, ShippingOrderExtraction, ShippingTask from app.services.shipping_notice.chat_actions import build_chat_actions_payload from app.services.shipping_notice.constants import ( AUTO_CHAIN_FALLBACK, CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, - MAP_JSON, ) from app.services.shipping_notice.tool_common import switch_batch_focus from app.services.shipping_notice.query_service import ( @@ -44,6 +43,7 @@ from app.services.shipping_notice.customer_identity_gate import ( confirm_task_customer, list_customer_options, ) +from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) @@ -84,6 +84,23 @@ def workspace_shipping_batches(): return jsonify(list_batches_for_user(user.id, limit=limit)) +@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST']) +def workspace_shipping_export_archive(): + """按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。""" + user = _require_user() + data = request.get_json(silent=True) or {} + task_nos = data.get('task_nos') + if task_nos is not None and not isinstance(task_nos, list): + raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + from app.services.shipping_notice.export_archive import build_export_archive + stream, filename, _manifest = build_export_archive( + user_id=user.id, batch_no=str(data.get('batch_no') or '').strip() or None, task_nos=task_nos, + ) + response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip') + response.call_on_close(stream.close) + return response + + @workspace_shipping_notice_bp.route('/shipping-customers', methods=['GET']) def workspace_shipping_customers(): """列出可供当前业务用户确认的启用标准客户。""" @@ -115,6 +132,47 @@ def workspace_confirm_shipping_customer(task_no: str): 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-order-extractions//customer-matches//confirm', + methods=['POST'], +) +def workspace_confirm_order_customer_match(extraction_id: int, role: str): + """确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。""" + user = _require_user() + extraction = ( + db.session.query(ShippingOrderExtraction) + .join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingOrderExtraction.intake_id) + .filter( + ShippingOrderExtraction.id == extraction_id, + ShippingNoticeIntake.user_id == user.id, + ) + .one_or_none() + ) + if extraction is None: + raise NotFoundError( + 'Order extraction not found', + code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', + ) + data = request.get_json(silent=True) or {} + try: + customer_id = int(data.get('customer_id')) + site_id = int(data['site_id']) if data.get('site_id') is not None else None + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Customer id is required', + code='SHIPPING.ORDER_CUSTOMER_REQUIRED', + details={'field': 'customer_id'}, + ) from exc + result = confirm_order_customer_match( + extraction.id, + role=role, + customer_id=customer_id, + site_id=site_id, + actor_id=user.id, + ) + return _ok(result) + @workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) def workspace_shipping_conversation_batch_workspace(conversation_id: str): """返回一个 Agent 会话下的多批次执行工作台快照。""" @@ -385,17 +443,6 @@ def workspace_retry_shipping_task(task_no: str): payload['comment'] = comment return jsonify(shipping_tools.retry_task(payload)) -@workspace_shipping_notice_bp.route('/shipping-tasks//upload-inventory', methods=['POST']) -def workspace_upload_shipping_inventory(task_no: str): - """用户态上传库存 Excel,并在服务端完成解析。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - upload = request.files.get('file') - from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload)) - @workspace_shipping_notice_bp.route('/shipping-tasks//confirm-inventory-source', methods=['POST']) def workspace_confirm_shipping_inventory_source(task_no: str): """确认当前任务的库存 RPA 来源,并继续触发库存导出。""" @@ -414,22 +461,6 @@ def workspace_confirm_shipping_inventory_source(task_no: str): '_trusted_user_id': user.id, })) -@workspace_shipping_notice_bp.route('/shipping-tasks//apply-inventory-mapping', methods=['POST']) -def workspace_apply_inventory_mapping(task_no: str): - """提交库存字段映射,并允许在工作台侧自动回退到下一步。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - data = request.get_json(silent=True) or {} - map_json = data.get(MAP_JSON) - if not isinstance(map_json, dict) or not map_json: - raise ValidationError(f'{MAP_JSON} is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True} - return jsonify(shipping_tools.apply_inventory_mapping(payload)) - @workspace_shipping_notice_bp.route('/shipping-tasks//submit-decision', methods=['POST']) def workspace_submit_shipping_decision(task_no: str): """以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index d0fe8706..cfac042a 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -6,6 +6,7 @@ backend/app/core/config/settings.py 逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。 """ import os +import warnings from pathlib import Path from dotenv import dotenv_values @@ -13,6 +14,18 @@ from dotenv import dotenv_values _BACKEND_DIR = Path(__file__).resolve().parents[3] _ROOT_DIR = _BACKEND_DIR.parent +_WARNED_LEGACY_RPA_ENV: set[str] = set() + +_RPA_LEGACY_TO_CANONICAL = { + 'SHIPPING_RPA_CREDENTIAL_KEY': 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY', + 'FREIGHT_INVENTORY_DROP_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', + 'FREIGHT_RPA_INVENTORY_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', + 'FREIGHT_UPLOAD_QUEUE_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', + 'FREIGHT_RPA_UPLOAD_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', + 'FREIGHT_RPA_BROWSER_PROFILE_DIR': 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', + 'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR': 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', + 'FREIGHT_RPA_MOCK': 'SHIPPING_NOTICE_RPA_WORKER_MOCK', +} def _normalize_env_name(raw: str | None) -> str: @@ -75,6 +88,58 @@ def _backend_path(env_key: str, *parts: str) -> str: return resolve_backend_relative_path(os.getenv(env_key), default) +def _rpa_env(canonical_name: str, default: str | None = None) -> str | None: + """ + 读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。 + + 核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的 + 历史变量,并按进程对每个旧名称最多发出一次弃用警告。 + + Args: + canonical_name: 统一后的规范环境变量名。 + default: 新旧变量均未设置时返回的默认值。 + + Returns: + str | None: 环境变量值或默认值。 + """ + value = os.getenv(canonical_name) + if value is not None: + return value + legacy_name = next( + (legacy for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items() if canonical == canonical_name), + None, + ) + if legacy_name: + value = os.getenv(legacy_name) + if value is not None: + if legacy_name not in _WARNED_LEGACY_RPA_ENV: + warnings.warn( + f'{legacy_name} is deprecated; use {canonical_name}', + DeprecationWarning, + stacklevel=2, + ) + _WARNED_LEGACY_RPA_ENV.add(legacy_name) + return value + return default + + +def _rpa_data_path(canonical_name: str, *parts: str) -> str: + """ + 解析 RPA 数据目录,并兼容历史环境变量名称。 + + Args: + canonical_name: 统一后的 RPA 目录环境变量名。 + *parts: 未配置时相对 `backend/data` 的默认路径片段。 + + Returns: + str: 解析后的绝对或后端相对兼容路径。 + """ + from app.path_utils import resolve_backend_relative_path + + default = _BACKEND_DIR.joinpath('data', *parts) + return resolve_backend_relative_path(_rpa_env(canonical_name), default) + + class Config: SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.getenv('SECRET_KEY') @@ -127,6 +192,10 @@ class Config: # 货代发货通知 Agent Tool API SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY') + # RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。 + SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') + # 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。 + SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY # 文件检核 Chatflow Tool API FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY') @@ -161,6 +230,13 @@ class Config: SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = ( os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'false').lower() == 'true' ) + # 自动确认必须同时满足人工标注样本量和准确率门禁,避免仅凭开关放大解析误识别。 + SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES = int( + os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES') or '20' + ) + SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float( + os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98' + ) SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = ( os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true' ) @@ -221,9 +297,6 @@ class Config: SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int( os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000' ) - SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path( - 'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml' - ) SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int( os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24' ) @@ -242,27 +315,33 @@ class Config: ).strip().lower() SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS') FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP') - FREIGHT_INVENTORY_DROP_DIR = _data_path( - "FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop" + SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path( + 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop' ) - FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path( - "FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers" + SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path( + 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers' ) - FREIGHT_UPLOAD_QUEUE_DIR = _data_path( - "FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue" + SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path( + 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue' ) - FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path( - "FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers" + SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path( + 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'upload_triggers' ) - FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path( - "FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile" + SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path( + 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', 'shipping_notice', 'freight_rpa', 'browser_profile' ) - FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path( - "FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives" - ) - FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path( - "FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx" + SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( + 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives' ) + SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false') + # 旧 Flask config 属性仅用于过渡期测试和外部扩展兼容。 + FREIGHT_INVENTORY_DROP_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR + FREIGHT_RPA_INVENTORY_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR + FREIGHT_UPLOAD_QUEUE_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR + FREIGHT_RPA_UPLOAD_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR + FREIGHT_RPA_BROWSER_PROFILE_DIR = SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR + FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR + FREIGHT_RPA_MOCK = SHIPPING_NOTICE_RPA_WORKER_MOCK # WeCom (企业微信) 登录配置 WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true' diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index d3f6c4bb..5ddbbdc5 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -20,7 +20,6 @@ from app.models.file_asset import FileAsset from app.models.shipping import ( ShippingBatch, ShippingInventoryFile, - ShippingInventoryMapping, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, @@ -29,15 +28,45 @@ from app.models.shipping import ( ShippingTaskInventoryLink, ) from app.models.shipping_task_line import ShippingTaskFieldConflict, ShippingTaskLine +from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact +from app.models.shipping_order_schema import ( + ShippingOrderExtraction, + ShippingOrderSchemaAuditEvent, + ShippingOrderField, + ShippingOrderFieldDecision, + ShippingOrderFieldObservation, + ShippingOrderFieldValue, + ShippingOrderLine, + ShippingOrderSchema, + ShippingOrderSchemaVersion, +) +from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch +from app.models.shipping_inventory_config import ( + ShippingInventoryField, + ShippingInventoryExternalMapping, + ShippingInventoryConfigurationTestRun, + ShippingInventoryParsingProfile, + ShippingInventoryRoutingRule, + ShippingInventoryRoutingRuleCondition, + ShippingInventoryRoutingRuleVersion, + ShippingInventorySource, + ShippingInventoryStructureAnalysis, + ShippingRpaProfile, +) +from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession from app.models.shipping_customer import ( ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingCustomerExternalRef, ShippingCustomerIdentifier, + ShippingCustomerLifecycleEvent, + ShippingCustomerMerge, + ShippingCustomerSite, + ShippingCustomerSiteIdentifier, ) from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow -from app.models.shipping_customer_resolution import ShippingCustomerShadowResolution +from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution from app.models.training import TrainingRecord from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit @@ -78,18 +107,45 @@ __all__ = [ 'ShippingTask', 'ShippingTaskLine', 'ShippingTaskFieldConflict', + 'ShippingOrderSchema', + 'ShippingOrderSchemaVersion', + 'ShippingOrderSchemaAuditEvent', + 'ShippingOrderField', + 'ShippingOrderExtraction', + 'ShippingOrderLine', + 'ShippingOrderFieldObservation', + 'ShippingOrderFieldDecision', + 'ShippingOrderFieldValue', + 'ShippingOrderCustomerMatch', 'ShippingCustomer', 'ShippingCustomerIdentifier', 'ShippingCustomerExternalRef', + 'ShippingCustomerLifecycleEvent', + 'ShippingCustomerMerge', + 'ShippingCustomerSite', + 'ShippingCustomerSiteIdentifier', 'ShippingCustomerImportBatch', 'ShippingCustomerImportRow', 'ShippingCase', 'ShippingBusinessSequence', 'ShippingCustomerShadowResolution', + 'ShippingCustomerShadowMatch', 'ShippingTaskEvent', 'ShippingInventoryFile', 'ShippingTaskInventoryLink', - 'ShippingInventoryMapping', + 'ShippingRpaProfile', + 'ShippingInventorySource', + 'ShippingInventoryField', + 'ShippingInventoryStructureAnalysis', + 'ShippingInventoryRoutingRule', + 'ShippingInventoryRoutingRuleCondition', + 'ShippingInventoryRoutingRuleVersion', + 'ShippingInventoryExternalMapping', + 'ShippingInventoryConfigurationTestRun', + 'ShippingInventoryParsingProfile', + 'ShippingTemporaryInventorySession', + 'ShippingExcelTemplate', + 'ShippingExportArtifact', 'ShippingNoticeIntake', 'ShippingNoticeDocument', 'ShippingNoticeCandidate', diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 8c511be3..9d1defde 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -67,7 +67,6 @@ class ShippingBatch(Base): process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, 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) - tasks: Mapped[List['ShippingTask']] = relationship( 'ShippingTask', back_populates='batch', @@ -85,7 +84,6 @@ class ShippingTask(Base): Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'), Index('ix_shipping_tasks_upload_status', 'upload_status'), Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'), - Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'), Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'), Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'), Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'), @@ -160,7 +158,6 @@ class ShippingTask(Base): warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), 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) inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) @@ -186,6 +183,15 @@ class ShippingTask(Base): server_default=text("'pending'"), nullable=False, ) + current_order_extraction_id: Mapped[Optional[int]] = mapped_column( + ForeignKey( + 'shipping_order_extractions.id', + name='fk_shipping_tasks_current_order_extraction_id', + use_alter=True, + ), + nullable=True, + index=True, + ) process_status: Mapped[str] = mapped_column(String(32), default='created', index=True) current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -215,7 +221,6 @@ class ShippingTask(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - batch: Mapped[Optional['ShippingBatch']] = relationship( 'ShippingBatch', back_populates='tasks', @@ -273,25 +278,38 @@ class ShippingInventoryFile(Base): 'exported_at', ), Index( - 'ix_shipping_inventory_files_source_site_wh', + 'ix_shipping_inventory_files_source_warehouse', 'source_code', - 'site_id', 'warehouse_id', ), Index( 'uq_shipping_inventory_files_rpa_identity_ready', 'rpa_run_no', 'source_code', - 'site_id', 'warehouse_id', unique=True, postgresql_where=text( "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " - "AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL" + "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" ), sqlite_where=text( "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " - "AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL" + "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" + ), + ), + # 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。 + Index( + 'uq_shipping_inventory_files_rpa_dynamic_source_ready', + 'rpa_run_no', + 'source_code', + unique=True, + postgresql_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NULL" + ), + sqlite_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NULL" ), ), ) @@ -311,7 +329,6 @@ class ShippingInventoryFile(Base): share_mode: Mapped[str] = mapped_column(String(32), default='task_only') warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) @@ -344,7 +361,6 @@ class ShippingTaskInventoryLink(Base): 'ix_shipping_task_inventory_links_task_source', 'task_id', 'matched_source_code', - 'matched_site_id', ), ) @@ -357,7 +373,6 @@ class ShippingTaskInventoryLink(Base): link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) @@ -442,8 +457,6 @@ class ShippingNoticeIntake(Base): expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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) - - class ShippingNoticeDocument(Base): """ 发货通知文档单元:邮件正文或单个附件(阶段二)。 @@ -493,8 +506,6 @@ class ShippingNoticeDocument(Base): order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - - class ShippingNoticeCandidate(Base): """ 订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。 @@ -572,22 +583,3 @@ class ShippingNoticeCandidate(Base): ) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - - -class ShippingInventoryMapping(Base): - """客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。""" - - __tablename__ = 'shipping_inventory_mappings' - __table_args__ = ( - UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'), - Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - customer_code: Mapped[str] = mapped_column(String(64), nullable=False) - header_hash: Mapped[str] = mapped_column(String(64), nullable=False) - headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) - last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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, index=True) diff --git a/backend/app/models/shipping_customer.py b/backend/app/models/shipping_customer.py index af2be75a..9fd88f70 100644 --- a/backend/app/models/shipping_customer.py +++ b/backend/app/models/shipping_customer.py @@ -11,7 +11,7 @@ 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 import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base @@ -39,6 +39,11 @@ class ShippingCustomer(Base): 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') + merged_into_customer_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_customers.id'), + nullable=True, + index=True, + ) 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) @@ -51,6 +56,21 @@ class ShippingCustomer(Base): cascade='all, delete-orphan', ) cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer') + merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship( + 'ShippingCustomer', + remote_side='ShippingCustomer.id', + back_populates='merged_source_customers', + ) + external_refs: Mapped[List['ShippingCustomerExternalRef']] = relationship( + 'ShippingCustomerExternalRef', back_populates='customer', cascade='all, delete-orphan', + ) + sites: Mapped[List['ShippingCustomerSite']] = relationship( + 'ShippingCustomerSite', back_populates='customer', cascade='all, delete-orphan', + ) + merged_source_customers: Mapped[List['ShippingCustomer']] = relationship( + 'ShippingCustomer', + back_populates='merged_into_customer', + ) class ShippingCustomerIdentifier(Base): @@ -108,7 +128,65 @@ class ShippingCustomerExternalRef(Base): 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') + customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='external_refs') + + +class ShippingCustomerSite(Base): + """标准客户下的送货/收货站点;Ship-to 匹配指向站点而不是复制一条账款客户。""" + + __tablename__ = 'shipping_customer_sites' + __table_args__ = ( + UniqueConstraint('customer_id', 'site_code', name='uq_shipping_customer_sites_customer_code'), + Index('ix_shipping_customer_sites_status_name', 'status', 'site_name'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True) + site_name: Mapped[str] = mapped_column(String(200), nullable=False) + site_code: Mapped[str] = mapped_column(String(64), nullable=False) + address: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + country: Mapped[Optional[str]] = mapped_column(String(64), nullable=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) + + customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='sites') + identifiers: Mapped[List['ShippingCustomerSiteIdentifier']] = relationship( + 'ShippingCustomerSiteIdentifier', back_populates='site', cascade='all, delete-orphan', + ) + + +class ShippingCustomerSiteIdentifier(Base): + """送货站点的名称、外部站点编码或地址别名,用于 Ship-to 确定性匹配。""" + + __tablename__ = 'shipping_customer_site_identifiers' + __table_args__ = ( + UniqueConstraint( + 'site_id', 'identifier_type', 'source_system', 'normalized_value', + name='uq_shipping_customer_site_identifiers_value', + ), + Index( + 'ix_shipping_customer_site_identifiers_lookup', + 'identifier_type', 'source_system', 'normalized_value', 'status', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + site_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=False, index=True) + identifier_type: Mapped[str] = mapped_column(String(32), nullable=False) + source_system: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + raw_value: Mapped[str] = mapped_column(String(500), nullable=False) + normalized_value: Mapped[str] = mapped_column(String(500), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='approved', server_default='approved') + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers') class ShippingCase(Base): @@ -174,3 +252,45 @@ class ShippingBusinessSequence(Base): 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) + + +class ShippingCustomerLifecycleEvent(Base): + """客户生命周期审计;只保存客户快照,不能反向阻断受控删除。""" + + __tablename__ = 'shipping_customer_lifecycle_events' + __table_args__ = ( + Index('ix_shipping_customer_lifecycle_events_customer_created', 'customer_id_snapshot', 'created_at'), + Index('ix_shipping_customer_lifecycle_events_event_created', 'event_type', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + event_type: Mapped[str] = mapped_column(String(32), nullable=False) + customer_id_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) + actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + + +class ShippingCustomerMerge(Base): + """客户身份归并审计;仅存快照,不给历史审计链增加客户外键依赖。""" + + __tablename__ = 'shipping_customer_merges' + __table_args__ = ( + UniqueConstraint('source_customer_id_snapshot', name='uq_shipping_customer_merges_source_snapshot'), + Index('ix_shipping_customer_merges_target_created', 'target_customer_id_snapshot', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False) + source_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False) + source_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False) + target_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False) + target_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False) + target_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False) + actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + reason: Mapped[str] = mapped_column(Text, nullable=False) + detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) diff --git a/backend/app/models/shipping_customer_resolution.py b/backend/app/models/shipping_customer_resolution.py index c39953c8..d8bb39de 100644 --- a/backend/app/models/shipping_customer_resolution.py +++ b/backend/app/models/shipping_customer_resolution.py @@ -9,10 +9,10 @@ backend/app/models/shipping_customer_resolution.py from __future__ import annotations from datetime import datetime -from typing import Optional +from typing import List, Optional -from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, JSON, String -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base @@ -52,3 +52,40 @@ class ShippingCustomerShadowResolution(Base): 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) + + matches: Mapped[List['ShippingCustomerShadowMatch']] = relationship( + 'ShippingCustomerShadowMatch', + back_populates='resolution', + cascade='all, delete-orphan', + order_by='ShippingCustomerShadowMatch.match_rank', + ) + + +class ShippingCustomerShadowMatch(Base): + """影子识别候选的规范化关联,供删除资格与合并可靠反查。""" + + __tablename__ = 'shipping_customer_shadow_matches' + __table_args__ = ( + UniqueConstraint('resolution_id', 'customer_id', name='uq_shipping_customer_shadow_matches_resolution_customer'), + Index('ix_shipping_customer_shadow_matches_customer', 'customer_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + resolution_id: Mapped[int] = mapped_column( + ForeignKey('shipping_customer_shadow_resolutions.id', ondelete='CASCADE'), + nullable=False, + index=True, + ) + customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False) + match_rank: Mapped[int] = mapped_column(Integer, nullable=False) + score: Mapped[float] = mapped_column(Float, nullable=False) + standard_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False) + short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False) + reasons_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + resolution: Mapped['ShippingCustomerShadowResolution'] = relationship( + 'ShippingCustomerShadowResolution', + back_populates='matches', + ) diff --git a/backend/app/models/shipping_excel_template.py b/backend/app/models/shipping_excel_template.py new file mode 100644 index 00000000..81571e1e --- /dev/null +++ b/backend/app/models/shipping_excel_template.py @@ -0,0 +1,77 @@ +""" +models/shipping_excel_template.py + +用途:定义版本化发货 Excel 模板及不可变任务导出产物。 +依赖:models.base.Base、库存源、订单 Schema、发货任务与库存快照模型。 +逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingExcelTemplate(Base): + """可跨库存源复用的发货 Excel 模板版本。""" + + __tablename__ = 'shipping_excel_templates' + __table_args__ = ( + UniqueConstraint('template_code', 'version', name='uq_shipping_excel_templates_code_version'), + Index('ix_shipping_excel_templates_status', 'status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + template_code: Mapped[str] = mapped_column(String(64), nullable=False) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + storage_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='minio', server_default='minio') + storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) + storage_key: Mapped[str] = mapped_column(String(512), nullable=False) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + file_checksum: Mapped[str] = mapped_column(String(64), nullable=False) + definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + definition_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template') + + +class ShippingExportArtifact(Base): + """一次任务导出的不可变产物及生成输入快照。""" + + __tablename__ = 'shipping_export_artifacts' + __table_args__ = ( + UniqueConstraint('artifact_no', name='uq_shipping_export_artifacts_no'), + Index('ix_shipping_export_artifacts_task_created', 'task_id', 'created_at'), + Index('ix_shipping_export_artifacts_batch_created', 'batch_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + artifact_no: Mapped[str] = mapped_column(String(64), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False, index=True) + batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True) + template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False) + order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) + order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False) + inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False) + inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) + input_checksum: Mapped[str] = mapped_column(String(64), nullable=False) + file_path: Mapped[str] = mapped_column(String(500), nullable=False) + file_name: Mapped[str] = mapped_column(String(255), nullable=False) + file_checksum: Mapped[str] = mapped_column(String(64), nullable=False) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready') + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + template: Mapped[ShippingExcelTemplate] = relationship() + task: Mapped['ShippingTask'] = relationship() diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/shipping_inventory_config.py new file mode 100644 index 00000000..610cb5fe --- /dev/null +++ b/backend/app/models/shipping_inventory_config.py @@ -0,0 +1,317 @@ +""" +models/shipping_inventory_config.py + +用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。 +依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。 +逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置, + 外部系统映射仅供后端内部复用,不承载调拨决策。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingInventoryField(Base): + """用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。""" + + __tablename__ = 'shipping_inventory_fields' + __table_args__ = ( + UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'), + UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'), + CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'), + CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'), + CheckConstraint( + "usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')", + name='ck_shipping_inventory_fields_usage_type', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + # Internal stable code supports runtime contracts; it is deliberately not exposed in the business UI. + field_code: Mapped[str] = mapped_column(String(64), nullable=False) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + value_type: Mapped[str] = mapped_column(String(16), nullable=False, default='text', server_default='text') + usage_type: Mapped[str] = mapped_column(String(32), nullable=False, default='general', server_default='general') + status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') + sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=100, server_default='100') + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + +class ShippingRpaProfile(Base): + """货代库存登录连接配置;凭据字段始终保存密文。""" + + __tablename__ = 'shipping_rpa_profiles' + __table_args__ = ( + UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'), + CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + profile_code: Mapped[str] = mapped_column(String(64), nullable=False) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + connector_type: Mapped[str] = mapped_column(String(32), nullable=False) + login_url: Mapped[str] = mapped_column(String(500), nullable=False) + username_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + password_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + login_config_json: Mapped[dict[str, Any]] = mapped_column( + JSON, default=lambda: {'auth_mode': 'password'}, nullable=False, + ) + enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) + config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + credential_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile') + + +class ShippingInventorySource(Base): + """库存业务来源;固定仓或库存行动态解析 Warehouse。""" + + __tablename__ = 'shipping_inventory_sources' + __table_args__ = ( + UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'), + CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'), + CheckConstraint( + "(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) " + "OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)", + name='ck_shipping_inventory_sources_warehouse_mode', + ), + CheckConstraint( + "enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)", + name='ck_shipping_inventory_sources_enabled_bindings', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + connector_type: Mapped[str] = mapped_column(String(32), nullable=False) + rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True) + parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True) + excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True) + warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False) + fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + # 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。 + report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False) + query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False) + match_aliases_json: Mapped[list[str]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False) + snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False) + enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) + config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources') + parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources') + excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources') + external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship( + back_populates='inventory_source', cascade='all, delete-orphan' + ) + + +class ShippingInventoryParsingProfile(Base): + """可跨库存源复用的库存文件结构与订单匹配配置。""" + + __tablename__ = 'shipping_inventory_parsing_profiles' + __table_args__ = ( + UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'), + Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'), + Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + profile_code: Mapped[str] = mapped_column(String(64), nullable=False) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + file_format: Mapped[str] = mapped_column(String(16), nullable=False, default='xlsx', server_default='xlsx') + definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + structure_definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile') + + +class ShippingInventoryStructureAnalysis(Base): + """库存文件结构分析记录;保存受控样例与建议,不承载正式库存快照。""" + + __tablename__ = 'shipping_inventory_structure_analyses' + __table_args__ = ( + Index('ix_inv_structure_analysis_file_hash', 'file_checksum'), + Index('ix_inv_structure_analysis_created', 'created_at'), + Index('ix_inv_structure_analysis_exact_fp', 'exact_structure_fingerprint'), + Index('ix_inv_structure_analysis_compat_fp', 'compatibility_fingerprint'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload') + source_file_name: Mapped[str] = mapped_column(String(255), nullable=False) + storage_path: Mapped[str] = mapped_column(String(500), nullable=False) + file_checksum: Mapped[str] = mapped_column(String(64), nullable=False) + file_format: Mapped[str] = mapped_column(String(16), nullable=False) + analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready') + structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list) + exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + match_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class ShippingInventoryConfigurationTestRun(Base): + """库存站点配置测试的异步 RPA 运行;测试文件不能进入生产库存池。""" + + __tablename__ = 'shipping_inventory_configuration_test_runs' + __table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),) + + id: Mapped[int] = mapped_column(primary_key=True) + run_no: Mapped[str] = mapped_column(String(64), nullable=False) + inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + source_config_version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa') + stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker') + analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True) + result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + +class ShippingInventoryRoutingRule(Base): + """可版本化的库存源路由决策表;仅产出受控 Source 候选。""" + + __tablename__ = 'shipping_inventory_routing_rules' + __table_args__ = ( + UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'), + CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'), + CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'), + CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + rule_code: Mapped[str] = mapped_column(String(64), nullable=False) + rule_name: Mapped[str] = mapped_column(String(128), nullable=False) + scope: Mapped[str] = mapped_column(String(16), nullable=False) + priority: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False) + match_mode: Mapped[str] = mapped_column(String(16), default='all', server_default=text("'all'"), nullable=False) + status: Mapped[str] = mapped_column(String(16), default='draft', server_default=text("'draft'"), nullable=False) + action_type: Mapped[str] = mapped_column(String(64), nullable=False) + action_payload_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False) + version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship( + back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence' + ) + + +class ShippingInventoryRoutingRuleCondition(Base): + """库存源路由条件;订单字段引用稳定 field_id,系统事实使用受控 key。""" + + __tablename__ = 'shipping_inventory_routing_rule_conditions' + __table_args__ = ( + UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'), + CheckConstraint( + "(source_kind = 'order_field' AND order_field_id IS NOT NULL AND system_fact_key IS NULL) OR " + "(source_kind = 'system_fact' AND order_field_id IS NULL AND system_fact_key IS NOT NULL)", + name='ck_inventory_routing_condition_source', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) + condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field') + order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True) + system_fact_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + operator: Mapped[str] = mapped_column(String(32), nullable=False) + expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) + sequence: Mapped[int] = mapped_column(Integer, nullable=False) + + rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions') + + +class ShippingInventoryRoutingRuleVersion(Base): + """已发布路由规则的不可变定义快照,供任务审计回放使用。""" + + __tablename__ = 'shipping_inventory_routing_rule_versions' + __table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),) + + id: Mapped[int] = mapped_column(primary_key=True) + rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) + version: Mapped[int] = mapped_column(Integer, nullable=False) + definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False) + published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class ShippingInventoryExternalMapping(Base): + """货代库存身份到外部系统仓库的单向映射;不承载调拨规则。""" + + __tablename__ = 'shipping_inventory_external_mappings' + __table_args__ = ( + Index( + 'uq_shipping_inventory_external_mappings_source_default_enabled', + 'inventory_source_id', + unique=True, + postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'), + sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'), + ), + Index( + 'uq_shipping_inventory_external_mappings_source_warehouse_enabled', + 'inventory_source_id', + 'freight_warehouse_id', + unique=True, + postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'), + sqlite_where=text('freight_warehouse_id IS NOT NULL AND enabled = 1'), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + external_system_code: Mapped[str] = mapped_column(String(32), nullable=False) + external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False) + external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False) + enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) + version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings') diff --git a/backend/app/models/shipping_order_customer_match.py b/backend/app/models/shipping_order_customer_match.py new file mode 100644 index 00000000..85f2ed3a --- /dev/null +++ b/backend/app/models/shipping_order_customer_match.py @@ -0,0 +1,59 @@ +""" +backend/app/models/shipping_order_customer_match.py + +用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。 +依赖:ShippingOrderExtraction、ShippingCustomer、users。 +逻辑:动态订单字段保留原文客户名称;本表按角色保存候选、确认客户及名称/简称快照,供复核和导出读取。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingOrderCustomerMatch(Base): + """一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。""" + + __tablename__ = 'shipping_order_customer_matches' + __table_args__ = ( + UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'), + CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'), + CheckConstraint( + "status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')", + name='ck_shipping_order_customer_matches_status', + ), + Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + extraction_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True, + ) + role: Mapped[str] = mapped_column(String(16), nullable=False) + raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) + source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched') + customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True) + site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True) + customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True) + candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) + resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + + extraction = relationship('ShippingOrderExtraction') + customer = relationship('ShippingCustomer') + site = relationship('ShippingCustomerSite') diff --git a/backend/app/models/shipping_order_schema.py b/backend/app/models/shipping_order_schema.py new file mode 100644 index 00000000..5b01a7dc --- /dev/null +++ b/backend/app/models/shipping_order_schema.py @@ -0,0 +1,311 @@ +""" +backend/app/models/shipping_order_schema.py + +用途:定义货代订单唯一 Schema、不可变版本、配置审计及动态订单解析结果。 +依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。 +逻辑:草稿和发布版本统一保存完整 JSON 定义;写操作追加审计事件;解析链锁定发布版本并保存裁决结果。 +""" + +from __future__ import annotations + +import uuid +from datetime import date, datetime +from decimal import Decimal +from typing import Any, Optional + +from sqlalchemy import ( + Boolean, + CheckConstraint, + Date, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + Numeric, + String, + Text, + UniqueConstraint, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +def _uuid() -> str: + """生成跨 PostgreSQL/SQLite 通用的 UUID 字符串主键。""" + return str(uuid.uuid4()) + + +class ShippingOrderSchema(Base): + """全局唯一货代订单 Schema;当前业务只允许一个逻辑 Schema。""" + + __tablename__ = 'shipping_order_schemas' + __table_args__ = ( + CheckConstraint("schema_code = 'SHIPPING_ORDER'", name='ck_shipping_order_schemas_single_code'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) + display_name: Mapped[str] = mapped_column(String(128), nullable=False) + description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + fields: Mapped[list['ShippingOrderField']] = relationship( + back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderField.field_code' + ) + versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship( + back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version' + ) + + +class ShippingOrderField(Base): + """订单字段稳定身份;下游使用 field_id,版本快照冻结当时的名称和规则。""" + + __tablename__ = 'shipping_order_fields' + __table_args__ = ( + UniqueConstraint('schema_id', 'field_code', name='uq_shipping_order_fields_schema_code'), + CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'), + CheckConstraint( + "value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')", + name='ck_shipping_order_fields_value_type', + ), + CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'), + Index('ix_shipping_order_fields_schema_scope', 'schema_id', 'scope'), + ) + + id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid) + schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False) + field_code: Mapped[str] = mapped_column(String(64), nullable=False) + scope: Mapped[str] = mapped_column(String(16), nullable=False) + value_type: Mapped[str] = mapped_column(String(16), nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active') + published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false')) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='fields') + + +class ShippingOrderSchemaVersion(Base): + """订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。""" + + __tablename__ = 'shipping_order_schema_versions' + __table_args__ = ( + UniqueConstraint('schema_id', 'version', name='uq_shipping_order_schema_versions_schema_version'), + CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_order_schema_versions_status'), + Index( + 'uq_shipping_order_schema_one_published', + 'schema_id', + unique=True, + postgresql_where=text("status = 'published'"), + sqlite_where=text("status = 'published'"), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False) + version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft') + definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') + change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + source_version_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_schema_versions.id'), nullable=True + ) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='versions') + source_version: Mapped[Optional['ShippingOrderSchemaVersion']] = relationship( + remote_side='ShippingOrderSchemaVersion.id', foreign_keys=[source_version_id] + ) + + +class ShippingOrderSchemaAuditEvent(Base): + """订单 Schema 配置的追加式审计事件;保存操作前后快照且不提供修改入口。""" + + __tablename__ = 'shipping_order_schema_audit_events' + __table_args__ = ( + CheckConstraint( + "event_type IN ('draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', " + "'field_saved', 'field_retired', 'field_deleted')", + name='ck_shipping_order_schema_audit_event_type', + ), + Index('ix_shipping_order_schema_audit_version_created', 'version_id', 'created_at'), + Index('ix_shipping_order_schema_audit_schema_created', 'schema_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False) + version_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True + ) + event_type: Mapped[str] = mapped_column(String(32), nullable=False) + actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class ShippingOrderExtraction(Base): + """一次订单解析审计;锁定 Schema 和输入快照,承载 LLM 原始结果及最终状态。""" + + __tablename__ = 'shipping_order_extractions' + __table_args__ = ( + Index('ix_shipping_order_extractions_task_created', 'task_id', 'created_at'), + Index('ix_shipping_order_extractions_intake_created', 'intake_id', 'created_at'), + # Version history pages aggregate and paginate the runtime records that used a Schema snapshot. + Index('ix_shipping_order_extractions_schema_version_created', 'schema_version_id', 'created_at'), + CheckConstraint( + "status IN ('created', 'extracting', 'needs_review', 'accepted', 'failed', 'superseded')", + name='ck_shipping_order_extractions_status', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True) + intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=True) + schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) + input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False) + input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='created', server_default='created') + raw_llm_output_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + normalized_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + validation_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + schema_version: Mapped['ShippingOrderSchemaVersion'] = relationship() + lines: Mapped[list['ShippingOrderLine']] = relationship( + back_populates='extraction', cascade='all, delete-orphan', order_by='ShippingOrderLine.position' + ) + observations: Mapped[list['ShippingOrderFieldObservation']] = relationship( + back_populates='extraction', cascade='all, delete-orphan' + ) + decisions: Mapped[list['ShippingOrderFieldDecision']] = relationship( + back_populates='extraction', cascade='all, delete-orphan' + ) + values: Mapped[list['ShippingOrderFieldValue']] = relationship( + back_populates='extraction', cascade='all, delete-orphan' + ) + + +class ShippingOrderLine(Base): + """动态订单解析中的行身份;业务值全部位于 FieldValue。""" + + __tablename__ = 'shipping_order_lines' + __table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),) + + id: Mapped[int] = mapped_column(primary_key=True) + extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) + position: Mapped[int] = mapped_column(Integer, nullable=False) + line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines') + + +class ShippingOrderFieldObservation(Base): + """某字段来自某 Document/解析器的原始观察及可回查证据。""" + + __tablename__ = 'shipping_order_field_observations' + __table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),) + + id: Mapped[int] = mapped_column(primary_key=True) + extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) + line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True) + field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False) + source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=True) + source_type: Mapped[str] = mapped_column(String(32), nullable=False) + extractor: Mapped[str] = mapped_column(String(32), nullable=False) + raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) + normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) + evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True) + evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false')) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='observations') + + +class ShippingOrderFieldDecision(Base): + """后端对字段观察集合的最终裁决;下游只能消费 accepted 决定。""" + + __tablename__ = 'shipping_order_field_decisions' + __table_args__ = ( + Index( + 'uq_shipping_order_decisions_header_field', 'extraction_id', 'field_id', unique=True, + postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'), + ), + Index( + 'uq_shipping_order_decisions_line_field', 'extraction_id', 'line_id', 'field_id', unique=True, + postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'), + ), + CheckConstraint( + "decision_status IN ('accepted', 'corroborated', 'needs_review', 'blocked', 'missing')", + name='ck_shipping_order_decisions_status', + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) + line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True) + field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False) + decision_status: Mapped[str] = mapped_column(String(32), nullable=False) + selected_observation_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_order_field_observations.id'), nullable=True + ) + supporting_observation_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list) + resolved_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) + reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + decided_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='decisions') + + +class ShippingOrderFieldValue(Base): + """已接受订单字段的类型化查询投影,供路由、匹配和 Excel 模板稳定引用。""" + + __tablename__ = 'shipping_order_field_values' + __table_args__ = ( + Index( + 'uq_shipping_order_field_values_header_field', 'extraction_id', 'field_id', unique=True, + postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'), + ), + Index( + 'uq_shipping_order_field_values_line_field', 'extraction_id', 'line_id', 'field_id', unique=True, + postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'), + ), + Index('ix_shipping_order_field_values_field_text', 'field_id', 'value_text'), + Index('ix_shipping_order_field_values_field_decimal', 'field_id', 'value_decimal'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) + line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True) + field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False) + value_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + value_decimal: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True) + value_integer: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + value_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + value_boolean: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) + value_json: Mapped[Any] = mapped_column(JSON, nullable=True) + decision_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_field_decisions.id'), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='values') diff --git a/backend/app/models/shipping_temporary_inventory.py b/backend/app/models/shipping_temporary_inventory.py new file mode 100644 index 00000000..4ab1aff7 --- /dev/null +++ b/backend/app/models/shipping_temporary_inventory.py @@ -0,0 +1,51 @@ +""" +models/shipping_temporary_inventory.py + +用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续批次使用过程。 +依赖:Base、FileAsset、ChatSession、ShippingBatch/ShippingTask、库存结构分析记录。 +逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检; + 本表不代表库存站点配置,也不代表生产库存快照。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class ShippingTemporaryInventorySession(Base): + """对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。""" + + __tablename__ = 'shipping_temporary_inventory_sessions' + __table_args__ = ( + UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'), + Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'), + Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'), + Index('ix_shipping_temp_inventory_asset', 'asset_id'), + Index('ix_shipping_temp_inventory_status_expires', 'status', 'expires_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + session_no: Mapped[str] = mapped_column(String(64), nullable=False) + user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True) + conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True) + asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True) + analysis_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, + ) + batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True, index=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True, index=True) + declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate') + file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created') + status: Mapped[str] = mapped_column(String(32), nullable=False, default='created') + classification_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + candidate_source_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list) + result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False, index=True) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) diff --git a/backend/app/services/admin/__init__.py b/backend/app/services/admin/__init__.py index 88f85486..df3ccf1a 100644 --- a/backend/app/services/admin/__init__.py +++ b/backend/app/services/admin/__init__.py @@ -15,6 +15,8 @@ from . import ( permission_service, report_service, shipping_customer_import_service, + shipping_customer_lifecycle_service, + shipping_customer_merge_service, shipping_customer_service, user_service, wecom_admin_service, @@ -31,6 +33,8 @@ __all__ = [ 'permission_service', 'report_service', 'shipping_customer_import_service', + 'shipping_customer_lifecycle_service', + 'shipping_customer_merge_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 index b9578a29..7e01fd9a 100644 --- a/backend/app/services/admin/shipping_customer_import_service.py +++ b/backend/app/services/admin/shipping_customer_import_service.py @@ -497,8 +497,11 @@ def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]: 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: + target = db.session.get(ShippingCustomer, target_id) + if target is None: raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if target.status != 'active': + raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID') else: target_id = None row.decision_action = action @@ -586,6 +589,8 @@ def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, An 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 target.status != 'active': + raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID') if action == 'update': target.standard_name = data['standard_name'] target.short_code = data['short_code'] diff --git a/backend/app/services/admin/shipping_customer_lifecycle_service.py b/backend/app/services/admin/shipping_customer_lifecycle_service.py new file mode 100644 index 00000000..cbf63c6e --- /dev/null +++ b/backend/app/services/admin/shipping_customer_lifecycle_service.py @@ -0,0 +1,244 @@ +""" +services/admin/shipping_customer_lifecycle_service.py + +用途:统一计算货代客户生命周期影响和永久删除资格。 +依赖:客户、业务单、流水、导入、影子识别模型及统一 AppError。 +逻辑:所有删除入口先调用本服务;业务和识别审计引用均阻断删除,识别证据仅作为可级联配置数据。 +""" + +from __future__ import annotations + +from typing import Any + +from app import db +from sqlalchemy import select + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingBusinessSequence, + ShippingCase, + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerImportRow, + ShippingCustomerLifecycleEvent, + ShippingCustomerSite, + ShippingOrderCustomerMatch, + ShippingCustomerShadowMatch, + ShippingCustomerShadowResolution, +) + + +def _legacy_shadow_json_match_count(customer_id: int, *, matched_resolution_ids: set[int]) -> int: + """统计规范化迁移前 JSON 中仍未映射的候选,防止现存审计记录漏算。""" + count = 0 + rows = db.session.query( + ShippingCustomerShadowResolution.id, + ShippingCustomerShadowResolution.candidate_matches_json, + ).all() + for resolution_id, matches in rows: + if int(resolution_id) in matched_resolution_ids: + continue + for item in matches or []: + if not isinstance(item, dict): + continue + try: + if int(item.get('customer_id')) == customer_id: + count += 1 + break + except (TypeError, ValueError): + continue + return count + + +def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, Any]: + """按已锁定或已读取的客户对象统计删除资格,保证各删除入口使用同一口径。""" + matched_resolution_ids = { + int(row[0]) + for row in db.session.query(ShippingCustomerShadowMatch.resolution_id) + .filter_by(customer_id=customer.id) + .all() + } + shadow_normalized = len(matched_resolution_ids) + blockers = { + 'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(), + 'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(), + 'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(), + 'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(), + 'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(), + 'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(), + 'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(), + 'shadow_manual_labels': db.session.query(ShippingCustomerShadowResolution.id).filter_by(manual_customer_id=customer.id).count(), + 'shadow_candidate_matches': shadow_normalized + _legacy_shadow_json_match_count( + customer.id, + matched_resolution_ids=matched_resolution_ids, + ), + 'merged_source_customers': db.session.query(ShippingCustomer.id).filter_by( + merged_into_customer_id=customer.id, + ).count(), + 'merged_into_customer': int(customer.merged_into_customer_id is not None), + } + return { + 'customer': { + 'id': customer.id, + 'standard_name': customer.standard_name, + 'short_code': customer.short_code, + 'status': customer.status, + }, + 'can_delete': not any(blockers.values()), + 'blockers': blockers, + 'cascade': { + 'identifiers': db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=customer.id).count(), + 'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).count(), + }, + } + + +def get_customer_lifecycle_impact(customer_id: int) -> dict[str, Any]: + """ + 返回客户永久删除前必须检查的全部引用和可级联配置数据。 + + Args: + customer_id: 标准客户主键。 + Returns: + 客户快照、can_delete、阻断引用计数和可级联识别证据数。 + """ + customer = db.session.get(ShippingCustomer, customer_id) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + + return _build_customer_lifecycle_impact(customer) + + +def get_customer_lifecycle_timeline(customer_id: int, *, limit: int = 100) -> dict[str, Any]: + """返回客户关键治理操作的倒序时间线,事件只含快照而不依赖客户外键。""" + customer = db.session.get(ShippingCustomer, customer_id) + rows = ( + db.session.query(ShippingCustomerLifecycleEvent) + .filter_by(customer_id_snapshot=customer_id) + .order_by(ShippingCustomerLifecycleEvent.id.desc()) + .limit(max(1, min(int(limit), 500))) + .all() + ) + if customer is None and not rows: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + # 受控删除后主表已不存在;以最近生命周期快照继续提供审计回放。 + customer_snapshot = _build_customer_lifecycle_impact(customer)['customer'] if customer is not None else { + 'id': customer_id, + 'standard_name': rows[0].customer_name_snapshot, + 'short_code': rows[0].customer_short_code_snapshot, + 'status': 'deleted', + } + return { + 'customer': customer_snapshot, + 'items': [{ + 'id': row.id, + 'event_type': row.event_type, + 'actor_id': row.actor_id, + 'reason': row.reason, + 'detail': row.detail_json or {}, + 'created_at': row.created_at.isoformat() if row.created_at else None, + } for row in rows], + } + + +def get_customer_governance_quality(*, limit: int = 100) -> dict[str, Any]: + """汇总影子识别、自动确认门禁和生命周期事件,供管理端持续治理。""" + from app.services.shipping_notice.customer_shadow_resolution import get_shadow_quality_report + from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics + + report = get_shadow_quality_report(limit=limit) + report['auto_resolution'] = get_auto_resolution_metrics() + event_counts = dict( + db.session.query(ShippingCustomerLifecycleEvent.event_type, db.func.count()) + .group_by(ShippingCustomerLifecycleEvent.event_type) + .all() + ) + return { + 'shadow_quality': report, + 'lifecycle_event_counts': event_counts, + } + + +def delete_customer( + customer_id: int, + *, + confirmation_short_code: object, + reason: object, + actor_id: int | None, +) -> dict[str, Any]: + """ + 受控永久删除未进入任何业务或审计链的误建客户。 + + Args: + customer_id: 待删除的标准客户主键。 + confirmation_short_code: 管理员二次输入的客户简码,忽略首尾空格并按大写比对。 + reason: 必填删除原因,写入不可反向引用客户的生命周期审计。 + actor_id: 当前管理员主键。 + Returns: + 已删除客户的快照、级联删除证据数与审计事件主键。 + Raises: + ValidationError: 删除原因或二次确认简码不合法。 + ConflictError: 锁定后发现存在任一阻断引用。 + NotFoundError: 客户不存在。 + """ + confirmed_code = str(confirmation_short_code or '').strip().upper() + delete_reason = str(reason or '').strip() + if not delete_reason: + raise ValidationError( + 'Customer deletion reason is required', + code='SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED', + details={'field': 'reason'}, + ) + + try: + # 锁住客户行后再统计引用,避免预检与提交之间出现可删除的错误判断。 + customer = db.session.execute( + select(ShippingCustomer) + .where(ShippingCustomer.id == customer_id) + .with_for_update() + ).scalar_one_or_none() + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if confirmed_code != customer.short_code: + raise ValidationError( + 'Customer deletion confirmation short code is invalid', + code='SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID', + details={'field': 'confirmation_short_code'}, + ) + + impact = _build_customer_lifecycle_impact(customer) + if not impact['can_delete']: + raise ConflictError( + 'Customer deletion is blocked by lifecycle references', + code='SHIPPING.CUSTOMER_DELETE_BLOCKED', + details={'blockers': impact['blockers']}, + ) + + event = ShippingCustomerLifecycleEvent( + event_type='deleted', + customer_id_snapshot=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + actor_id=actor_id, + reason=delete_reason, + detail_json={ + 'cascade': impact['cascade'], + }, + ) + customer_snapshot = impact['customer'] + db.session.add(event) + db.session.flush() + db.session.delete(customer) + db.session.commit() + return { + 'deleted_customer': customer_snapshot, + 'cascade': impact['cascade'], + 'lifecycle_event_id': event.id, + } + except (ConflictError, NotFoundError, ValidationError): + db.session.rollback() + raise + except Exception: + db.session.rollback() + raise diff --git a/backend/app/services/admin/shipping_customer_merge_service.py b/backend/app/services/admin/shipping_customer_merge_service.py new file mode 100644 index 00000000..b56173b0 --- /dev/null +++ b/backend/app/services/admin/shipping_customer_merge_service.py @@ -0,0 +1,227 @@ +""" +services/admin/shipping_customer_merge_service.py + +用途:执行货代标准客户的受控身份归并。 +依赖:客户、识别证据、外部来源键、生命周期审计与统一业务异常。 +逻辑:历史业务、编号、导入和影子审计保持指向源客户;仅将未来识别配置归并至目标客户。 +""" + +from __future__ import annotations + +from typing import Any + +from sqlalchemy import select + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerLifecycleEvent, + ShippingCustomerMerge, + ShippingCustomerSite, +) +from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact + + +def _load_customers_for_merge(source_customer_id: int, target_customer_id: int) -> tuple[ShippingCustomer, ShippingCustomer]: + """按主键固定顺序锁住源和目标客户,避免两个反向合并请求产生死锁。""" + if source_customer_id == target_customer_id: + raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER') + ids = sorted({int(source_customer_id), int(target_customer_id)}) + records = db.session.execute( + select(ShippingCustomer) + .where(ShippingCustomer.id.in_(ids)) + .order_by(ShippingCustomer.id.asc()) + .with_for_update() + ).scalars().all() + by_id = {int(record.id): record for record in records} + source = by_id.get(int(source_customer_id)) + target = by_id.get(int(target_customer_id)) + if source is None or target is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + return source, target + + +def _assert_merge_allowed(source: ShippingCustomer, target: ShippingCustomer) -> None: + """校验合并两端均处于可操作状态,禁止链式或循环归并。""" + if source.status == 'merged' or source.merged_into_customer_id is not None: + raise ConflictError('Source customer has already been merged', code='SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED') + if target.status != 'active' or target.merged_into_customer_id is not None: + raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID') + + +def get_customer_merge_impact(source_customer_id: int, target_customer_id: int) -> dict[str, Any]: + """预览归并的历史保留引用与可迁移配置,不执行任何数据修改。""" + if source_customer_id == target_customer_id: + raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER') + source = db.session.get(ShippingCustomer, source_customer_id) + target = db.session.get(ShippingCustomer, target_customer_id) + if source is None or target is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + _assert_merge_allowed(source, target) + target_identifiers = { + (item.identifier_type, item.normalized_value) + for item in db.session.query(ShippingCustomerIdentifier) + .filter_by(customer_id=target.id) + .all() + } + source_identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all() + duplicate_identifiers = sum( + (item.identifier_type, item.normalized_value) in target_identifiers + for item in source_identifiers + ) + return { + 'source': { + 'id': source.id, + 'standard_name': source.standard_name, + 'short_code': source.short_code, + 'status': source.status, + }, + 'target': { + 'id': target.id, + 'standard_name': target.standard_name, + 'short_code': target.short_code, + 'status': target.status, + }, + 'historical_references': get_customer_lifecycle_impact(source.id)['blockers'], + 'migrate': { + 'identifiers': len(source_identifiers) - duplicate_identifiers, + 'duplicate_identifiers': duplicate_identifiers, + 'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=source.id).count(), + 'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=source.id).count(), + }, + } + + +def merge_customer( + source_customer_id: int, + *, + target_customer_id: int, + confirmation_short_code: object, + reason: object, + actor_id: int | None, +) -> dict[str, Any]: + """ + 原子归并重复客户,不改写历史业务号及其引用。 + + Args: + source_customer_id: 待归并的源客户。 + target_customer_id: 承接未来识别配置的启用目标客户。 + confirmation_short_code: 必须匹配源客户当前简码。 + reason: 必填合并原因。 + actor_id: 当前管理员主键。 + Returns: + 源/目标快照、迁移统计与合并审计主键。 + """ + merge_reason = str(reason or '').strip() + confirmation = str(confirmation_short_code or '').strip().upper() + if not merge_reason: + raise ValidationError('Customer merge reason is required', code='SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED') + try: + source, target = _load_customers_for_merge(source_customer_id, target_customer_id) + _assert_merge_allowed(source, target) + if confirmation != source.short_code: + raise ValidationError( + 'Customer merge confirmation short code is invalid', + code='SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID', + details={'field': 'confirmation_short_code'}, + ) + + impact = get_customer_merge_impact(source.id, target.id) + target_identifier_keys = { + (item.identifier_type, item.normalized_value) + for item in db.session.query(ShippingCustomerIdentifier) + .filter_by(customer_id=target.id) + .all() + } + moved_identifiers = 0 + duplicates: list[ShippingCustomerIdentifier] = [] + identifiers_to_move: list[ShippingCustomerIdentifier] = [] + for identifier in db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all(): + key = (identifier.identifier_type, identifier.normalized_value) + if key in target_identifier_keys: + duplicates.append(identifier) + else: + identifiers_to_move.append(identifier) + target_identifier_keys.add(key) + # 先实际删除与目标重复的证据,再更新其余证据的外键,避免唯一约束瞬时冲突。 + for identifier in duplicates: + db.session.delete(identifier) + db.session.flush() + for identifier in identifiers_to_move: + identifier.customer_id = target.id + moved_identifiers += 1 + removed_duplicate_identifiers = len(duplicates) + + external_refs = db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=source.id).all() + for external_ref in external_refs: + external_ref.customer_id = target.id + + target_site_codes = { + item.site_code for item in db.session.query(ShippingCustomerSite).filter_by(customer_id=target.id).all() + } + source_sites = db.session.query(ShippingCustomerSite).filter_by(customer_id=source.id).all() + duplicate_site_codes = sorted({item.site_code for item in source_sites if item.site_code in target_site_codes}) + if duplicate_site_codes: + raise ConflictError( + 'Customer sites conflict during merge', + code='SHIPPING.CUSTOMER_MERGE_SITE_CONFLICT', + details={'site_codes': duplicate_site_codes}, + ) + for site in source_sites: + site.customer_id = target.id + + source_snapshot = impact['source'] + target_snapshot = impact['target'] + merge = ShippingCustomerMerge( + source_customer_id_snapshot=source.id, + source_name_snapshot=source.standard_name, + source_short_code_snapshot=source.short_code, + target_customer_id_snapshot=target.id, + target_name_snapshot=target.standard_name, + target_short_code_snapshot=target.short_code, + actor_id=actor_id, + reason=merge_reason, + detail_json={ + 'historical_references': impact['historical_references'], + 'migrate': { + 'identifiers': moved_identifiers, + 'duplicate_identifiers': removed_duplicate_identifiers, + 'external_references': len(external_refs), + 'sites': len(source_sites), + }, + }, + ) + source.status = 'merged' + source.merged_into_customer_id = target.id + source.updated_by_id = actor_id + db.session.add_all([ + merge, + ShippingCustomerLifecycleEvent( + event_type='merged_source', customer_id_snapshot=source.id, + customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code, + actor_id=actor_id, reason=merge_reason, + detail_json={'target': target_snapshot}, + ), + ShippingCustomerLifecycleEvent( + event_type='merged_target', customer_id_snapshot=target.id, + customer_name_snapshot=target.standard_name, customer_short_code_snapshot=target.short_code, + actor_id=actor_id, reason=merge_reason, + detail_json={'source': source_snapshot}, + ), + ]) + db.session.commit() + return { + 'source': source_snapshot, + 'target': target_snapshot, + 'migrate': merge.detail_json['migrate'], + 'merge_id': merge.id, + } + except (ConflictError, NotFoundError, ValidationError): + db.session.rollback() + raise + except Exception: + db.session.rollback() + raise diff --git a/backend/app/services/admin/shipping_customer_service.py b/backend/app/services/admin/shipping_customer_service.py index ea75743f..f40802d6 100644 --- a/backend/app/services/admin/shipping_customer_service.py +++ b/backend/app/services/admin/shipping_customer_service.py @@ -16,7 +16,15 @@ 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.models import ( + ShippingCase, + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerLifecycleEvent, + ShippingCustomerSite, + ShippingCustomerSiteIdentifier, +) from app.services.shipping_notice.customer_normalization import ( clean_text, is_public_email_domain, @@ -24,10 +32,54 @@ from app.services.shipping_notice.customer_normalization import ( normalize_short_code, ) -CUSTOMER_STATUSES = frozenset({'active', 'inactive'}) +CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'}) IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'}) +def _record_lifecycle_event( + customer: ShippingCustomer, + *, + event_type: str, + actor_id: int | None, + reason: str | None = None, + detail: dict[str, Any] | None = None, +) -> None: + """写入仅含客户快照的治理审计,避免生命周期日志反向阻断受控删除。""" + db.session.add(ShippingCustomerLifecycleEvent( + event_type=event_type, + customer_id_snapshot=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + actor_id=actor_id, + reason=reason, + detail_json=detail or {}, + )) + + +def _required_change_reason(data: dict[str, Any]) -> str: + """返回高风险客户变更的必填审计原因,缺失时拒绝提交。""" + reason = clean_text(data.get('reason')) + if not reason: + raise ValidationError( + 'Customer change reason is required', + code='SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED', + details={'field': 'reason'}, + ) + return reason + + +def _identifier_snapshot(record: ShippingCustomerIdentifier) -> dict[str, Any]: + """生成识别证据变更前后对比所需的最小审计快照。""" + return { + 'identifier_id': record.id, + 'identifier_type': record.identifier_type, + 'normalized_value': record.normalized_value, + 'status': record.status, + 'auto_match_allowed': bool(record.auto_match_allowed), + 'remark': record.remark, + } + + def _strict_bool(value: Any, *, field: str) -> bool: """只接受 JSON 布尔值,避免字符串 ``false`` 被 Python 判定为真。""" if isinstance(value, bool): @@ -83,6 +135,7 @@ def serialize_customer( 'standard_name': record.standard_name, 'short_code': record.short_code, 'status': record.status, + 'merged_into_customer_id': record.merged_into_customer_id, 'remark': record.remark, 'created_by_id': record.created_by_id, 'updated_by_id': record.updated_by_id, @@ -93,6 +146,8 @@ def serialize_customer( } if include_identifiers: payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers] + payload['external_refs'] = [serialize_external_ref(item) for item in record.external_refs] + payload['sites'] = [serialize_site(item) for item in record.sites] return payload @@ -204,7 +259,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, 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: + if status not in CUSTOMER_STATUSES - {'merged'}: raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID') record = ShippingCustomer( standard_name=standard_name, @@ -215,6 +270,13 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, updated_by_id=actor_id, ) db.session.add(record) + db.session.flush() + _record_lifecycle_event( + record, + event_type='created', + actor_id=actor_id, + detail={'after': {'standard_name': standard_name, 'short_code': short_code, 'status': status}}, + ) try: db.session.commit() except IntegrityError as exc: @@ -223,28 +285,81 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, return serialize_customer(record, include_identifiers=True) +def serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any]: + """序列化客户在外部系统中的稳定客户编码。""" + return { + 'id': record.id, 'customer_id': record.customer_id, + 'source_system': record.source_system, 'customer_code': record.legacy_customer_key, + } + + +def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]: + """序列化送货站点及其名称/外部编码标识。""" + return { + 'id': record.id, 'customer_id': record.customer_id, 'site_name': record.site_name, + 'site_code': record.site_code, 'address': record.address, 'city': record.city, + 'country': record.country, 'status': record.status, 'remark': record.remark, + 'identifiers': [{ + 'id': item.id, 'identifier_type': item.identifier_type, + 'source_system': item.source_system, 'raw_value': item.raw_value, + 'normalized_value': item.normalized_value, 'status': item.status, + } for item in record.identifiers], + } + + 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 record.status == 'merged': + raise ConflictError('Merged customer cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED') + before = { + 'standard_name': record.standard_name, + 'short_code': record.short_code, + 'status': record.status, + 'remark': record.remark, + } + next_name = before['standard_name'] + next_short_code = before['short_code'] + next_status = before['status'] + next_remark = before['remark'] 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 + next_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 + next_short_code = normalize_short_code(data.get('short_code')) + _assert_short_code_available(next_short_code, exclude_customer_id=customer_id) if 'status' in data: - status = clean_text(data.get('status')).lower() - if status not in CUSTOMER_STATUSES: + next_status = clean_text(data.get('status')).lower() + if next_status not in CUSTOMER_STATUSES - {'merged'}: 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 + next_remark = clean_text(data.get('remark')) or None + after = { + 'standard_name': next_name, + 'short_code': next_short_code, + 'status': next_status, + 'remark': next_remark, + } + changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]} + if changes: + high_risk_change = 'short_code' in changes or 'status' in changes + change_reason = _required_change_reason(data) if high_risk_change else clean_text(data.get('reason')) or None + record.standard_name = next_name + record.short_code = next_short_code + record.status = next_status + record.remark = next_remark + record.updated_by_id = actor_id + _record_lifecycle_event( + record, + event_type='updated', + actor_id=actor_id, + reason=change_reason, + detail={'changes': changes}, + ) try: db.session.commit() except IntegrityError as exc: @@ -253,9 +368,9 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N return serialize_customer(record, include_identifiers=True) -def deactivate_customer(customer_id: int, *, actor_id: int | None) -> dict[str, Any]: +def deactivate_customer(customer_id: int, *, reason: object = None, actor_id: int | None) -> dict[str, Any]: """停用客户;不物理删除,以保留业务单和识别审计。""" - return update_customer(customer_id, {'status': 'inactive'}, actor_id=actor_id) + return update_customer(customer_id, {'status': 'inactive', 'reason': reason}, actor_id=actor_id) def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: @@ -267,6 +382,8 @@ def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | customer = db.session.get(ShippingCustomer, customer_id) if customer is None: raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if customer.status == 'merged': + raise ConflictError('Merged customer cannot receive identifiers', code='SHIPPING.CUSTOMER_MERGED_LOCKED') 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) @@ -297,6 +414,13 @@ def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | confirmed_at=datetime.utcnow() if status == 'approved' else None, ) db.session.add(record) + db.session.flush() + _record_lifecycle_event( + customer, + event_type='identifier_created', + actor_id=actor_id, + detail={'identifier': _identifier_snapshot(record)}, + ) try: db.session.commit() except IntegrityError as exc: @@ -313,6 +437,10 @@ def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int record = db.session.get(ShippingCustomerIdentifier, identifier_id) if record is None: raise NotFoundError('Customer identifier not found', code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_FOUND') + customer = db.session.get(ShippingCustomer, record.customer_id) + if customer is None or customer.status == 'merged': + raise ConflictError('Merged customer identifier cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED') + before = _identifier_snapshot(record) next_status = record.status if 'status' in data: next_status = clean_text(data.get('status')).lower() @@ -331,12 +459,101 @@ def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int '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 + next_remark = clean_text(data.get('remark')) or None if 'remark' in data else record.remark + after = { + **before, + 'status': next_status, + 'auto_match_allowed': bool(next_allowed), + 'remark': next_remark, + } + changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]} + if changes: + requires_reason = 'status' in changes or 'auto_match_allowed' in changes + change_reason = _required_change_reason(data) if requires_reason else clean_text(data.get('reason')) or None + 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() + record.remark = next_remark + _record_lifecycle_event( + customer, + event_type='identifier_updated', + actor_id=actor_id, + reason=change_reason, + detail={'identifier_id': record.id, 'changes': changes}, + ) db.session.commit() return serialize_identifier(record) + + +def create_external_ref(customer_id: int, data: dict[str, Any]) -> dict[str, Any]: + """新增来源系统客户编码;同一来源和编码只能绑定一个标准客户。""" + customer = db.session.get(ShippingCustomer, customer_id) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + source_system = clean_text(data.get('source_system')).upper() + customer_code = clean_text(data.get('customer_code')).upper() + if not source_system or not customer_code: + raise ValidationError('Source system and customer code are required', code='SHIPPING.CUSTOMER_EXTERNAL_REF_INVALID') + record = ShippingCustomerExternalRef( + customer_id=customer.id, source_system=source_system, legacy_customer_key=customer_code, + ) + db.session.add(record) + try: + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise ConflictError('Customer external reference already exists', code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT') from exc + return serialize_external_ref(record) + + +def create_site(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """新增客户送货站点,站点编码在同一标准客户内唯一。""" + customer = db.session.get(ShippingCustomer, customer_id) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + site_name = clean_text(data.get('site_name')) + site_code = clean_text(data.get('site_code')).upper() + if not site_name or not site_code: + raise ValidationError('Site name and code are required', code='SHIPPING.CUSTOMER_SITE_INVALID') + record = ShippingCustomerSite( + customer_id=customer.id, site_name=site_name, site_code=site_code, + address=clean_text(data.get('address')) or None, city=clean_text(data.get('city')) or None, + country=clean_text(data.get('country')) or None, status='active', + 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 site already exists', code='SHIPPING.CUSTOMER_SITE_CONFLICT') from exc + return serialize_site(record) + + +def create_site_identifier(site_id: int, data: dict[str, Any]) -> dict[str, Any]: + """为送货站点新增名称别名、地址或带来源系统的外部站点编码。""" + site = db.session.get(ShippingCustomerSite, site_id) + if site is None: + raise NotFoundError('Customer site not found', code='SHIPPING.CUSTOMER_SITE_NOT_FOUND') + identifier_type = clean_text(data.get('identifier_type')).lower() + if identifier_type not in {'name_alias', 'external_code', 'address'}: + raise ValidationError('Site identifier type is invalid', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID') + raw_value = clean_text(data.get('identifier_value')) + source_system = clean_text(data.get('source_system')).upper() if identifier_type == 'external_code' else '' + if not raw_value or (identifier_type == 'external_code' and not source_system): + raise ValidationError('Site identifier is incomplete', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID') + normalized = normalize_identifier('name_alias', raw_value) if identifier_type == 'name_alias' else raw_value.upper() + record = ShippingCustomerSiteIdentifier( + site_id=site.id, identifier_type=identifier_type, source_system=source_system, + raw_value=raw_value, normalized_value=normalized, status='approved', + remark=clean_text(data.get('remark')) or None, + ) + db.session.add(record) + try: + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise ConflictError('Site identifier already exists', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_CONFLICT') from exc + return serialize_site(site) diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_inventory_service.py new file mode 100644 index 00000000..5b53d1c2 --- /dev/null +++ b/backend/app/services/admin/shipping_inventory_service.py @@ -0,0 +1,855 @@ +""" +services/admin/shipping_inventory_service.py + +用途:管理库存源、RPA Profile、路由规则和外部系统映射主数据。 +依赖:db、库存配置模型、凭据加密、Source/Profile 校验、统一 AppError。 +逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.extensions import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, + ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingTask, + ShippingOrderField, + ShippingInventoryParsingProfile, + ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis, + ShippingExcelTemplate, +) +from app.services.shipping_notice.credential_crypto import encrypt_credential +from app.services.shipping_notice.inventory_source_repository import validate_source_profile +from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS +from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS +from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS +from app.services.shipping_notice import inventory_parsing_profile + + +def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None: + value = str(data.get(field) or '').strip() + if required and not value: + raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field}) + return value or None + + +def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool: + value = data.get(field, default) + if not isinstance(value, bool): + raise ValidationError(f'{field} must be a boolean', details={'field': field}) + return value + + +def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]: + """读取并复制对象型 JSON 配置。 + + Args: + data: 管理 API 的请求载荷。 + field: 只允许 JSON object 的字段名。 + + Returns: + dict[str, Any]: 空值规范化为空对象后的可写入配置。 + + Raises: + ValidationError: 字段不是 JSON object。 + """ + value = data.get(field, {}) + if not isinstance(value, dict): + raise ValidationError(f'{field} must be an object', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + return dict(value) + + +def _json_string_list(data: dict[str, Any], field: str) -> list[str]: + """读取非空、去重的字符串列表,供 Source 别名等业务配置使用。""" + value = data.get(field, []) + if not isinstance(value, list) or any(not isinstance(item, str) for item in value): + raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + result: list[str] = [] + for item in value: + normalized = item.strip() + if normalized and normalized not in result: + result.append(normalized) + return result + + +def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]: + """校验连接级登录配置,不接收页面选择器或报表操作字段。""" + value = data.get('login_config_json', {}) + if not isinstance(value, dict) or set(value) - {'auth_mode'}: + raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID') + auth_mode = str(value.get('auth_mode') or 'password').strip().lower() + if auth_mode != 'password': + raise ValidationError( + 'Only password authentication is currently supported', + code='SHIPPING.RPA_PROFILE_CONFIG_INVALID', + ) + return {'auth_mode': auth_mode} + + +def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]: + """校验 DBS 四级报表路径,防止技术选择器混入业务配置。""" + allowed = {'program_group', 'program_label', 'report_group', 'report_name'} + if set(report_path) - allowed: + raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + normalized = {key: str(value or '').strip() for key, value in report_path.items()} + if connector_type == 'dbs': + missing = [key for key in allowed if not normalized.get(key)] + if missing: + raise ValidationError( + 'DBS inventory source requires a complete report path', + code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)}, + ) + elif normalized: + raise ValidationError( + 'Only DBS inventory sources can define report_path_json', + code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', + ) + return {key: normalized[key] for key in allowed if normalized.get(key)} + + +def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: + """校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。""" + raw = data.get('query_parameters_json', []) + if not isinstance(raw, list): + raise ValidationError('query_parameters_json must be a list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + result: list[dict[str, Any]] = [] + seen_names: set[str] = set() + allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'} + for index, item in enumerate(raw): + if not isinstance(item, dict) or set(item) - allowed: + raise ValidationError( + 'query parameter contains unsupported fields', + code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'index': index}, + ) + name = str(item.get('name') or '').strip() + mode = str(item.get('mode') or 'single').strip().lower() + values = item.get('values', []) + required = item.get('required', False) + select_all = item.get('select_all', False) + if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}: + raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + if not isinstance(values, list) or any(not isinstance(value, str) for value in values): + raise ValidationError('query parameter values must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + if not isinstance(required, bool) or not isinstance(select_all, bool): + raise ValidationError('query parameter flags must be boolean', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + normalized_values = [value.strip() for value in values if value.strip()] + if required and not normalized_values and not select_all: + raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + if select_all and mode != 'multi_select': + raise ValidationError('select_all only applies to multi_select', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + parameter: dict[str, Any] = { + 'name': name, 'mode': mode, 'values': normalized_values, + 'required': required, 'select_all': select_all, + } + if mode == 'multi_text': + joiner = str(item.get('joiner') or ',').strip() + if not joiner: + raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + parameter['joiner'] = joiner + seen_names.add(name.lower()) + result.append(parameter) + return result + + +def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]: + return { + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'connector_type': profile.connector_type, 'login_url': profile.login_url, + 'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled), + 'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext), + 'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at), + 'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at), + } + + +def _mask(ciphertext: str | None) -> str | None: + """凭据密文不支持反向展示;仅以配置状态提示管理员。""" + return 'configured' if ciphertext else None + + +def _iso(value: datetime | None) -> str | None: + return value.isoformat() if value else None + + +def list_profiles() -> list[dict[str, Any]]: + """列出 Profile 元数据,不返回可恢复的凭据。""" + return [_profile_payload(item) for item in ShippingRpaProfile.query.order_by(ShippingRpaProfile.profile_code).all()] + + +def delete_profile(profile_id: int) -> None: + """删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。""" + profile = db.session.get(ShippingRpaProfile, profile_id) + if profile is None: + raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + if ShippingInventorySource.query.filter_by(rpa_profile_id=profile.id).count(): + raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED') + db.session.delete(profile) + db.session.commit() + + +def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: + """创建或更新货代登录连接;密码留空表示保留既有密文。""" + profile = db.session.get(ShippingRpaProfile, profile_id) if profile_id else None + if profile_id and profile is None: + raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={}) + profile.profile_code = str(_text(data, 'profile_code', required=True)).upper() + profile.display_name = str(_text(data, 'display_name', required=True)) + profile.connector_type = str(_text(data, 'connector_type', required=True)).lower() + profile.login_url = str(_text(data, 'login_url', required=True)) + profile.login_config_json = _validate_profile_login_config(data) + profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True) + if not profile.enabled and any(source.enabled for source in profile.sources): + raise ConflictError( + 'Disable inventory sources before disabling their RPA Profile', + code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED', + ) + username = _text(data, 'username') + password = _text(data, 'password') + if username is not None: + profile.username_ciphertext = encrypt_credential(username) + if password is not None: + profile.password_ciphertext = encrypt_credential(password) + if username is not None or password is not None: + profile.credential_updated_at = datetime.utcnow() + profile.updated_by = actor_id + if profile_id: + profile.config_version += 1 + if not profile_id: + profile.created_by = actor_id + db.session.add(profile) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc + return _profile_payload(profile) + + +def _source_payload(source: ShippingInventorySource) -> dict[str, Any]: + """序列化库存站点及其是否满足正式启用前置条件。""" + return { + 'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name, + 'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id, + 'parsing_profile_id': source.parsing_profile_id, + 'excel_template_id': source.excel_template_id, + 'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id, + 'report_path_json': source.report_path_json or {}, 'query_parameters_json': source.query_parameters_json or [], + 'match_aliases_json': source.match_aliases_json or [], + 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled), + 'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at), + 'activation': get_source_activation_status(source), + } + + +def list_sources() -> list[dict[str, Any]]: + """列出库存源及其稳定业务配置。""" + return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()] + + +def delete_source(source_id: int) -> None: + """删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。""" + source = db.session.get(ShippingInventorySource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + source_code = str(source.source_code or '').strip().upper() + has_mapping = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id).count() > 0 + has_snapshot = ShippingInventoryFile.query.filter_by(source_code=source_code).count() > 0 + has_rule = any( + source_code in {str(code).strip().upper() for code in candidates} + for rule in ShippingInventoryRoutingRule.query.all() + for candidates in [(rule.action_payload_json or {}).get('source_codes', [])] + if isinstance(candidates, list) + ) + has_task = ShippingTask.query.filter_by(inventory_source_code=source_code).count() > 0 + has_export_run = any( + source_code in {str(code).strip().upper() for code in source_codes} + for run in ScheduleRun.query.all() + for source_codes in [(run.api_request_json or {}).get('source_codes', [])] + if isinstance(source_codes, list) + ) + if has_mapping or has_snapshot or has_rule or has_task or has_export_run: + raise ConflictError('Inventory Source has operational references', code='SHIPPING.INVENTORY_SOURCE_DELETE_BLOCKED') + db.session.delete(source) + db.session.commit() + + +def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]: + """投影库存快照的管理端只读行,不暴露存储路径或库存明细。""" + return { + 'id': snapshot.id, 'inventory_file_no': snapshot.inventory_file_no, + 'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id, + 'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status, + 'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode, + 'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at), + 'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id, + 'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at), + 'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')), + 'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None, + } + + +def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]: + """列出最新库存快照,供管理员确认当前可用的库存文件。""" + rows = ShippingInventoryFile.query.order_by( + ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(), + ).limit(max(1, min(limit, 200))).all() + return [_snapshot_payload(row) for row in rows] + + +def get_snapshot_download(snapshot_id: int) -> tuple[str, str]: + """返回管理员可下载的库存快照路径及安全文件名。 + + Args: + snapshot_id: 库存快照主键。 + + Returns: + 本地托管文件绝对路径和面向下载的文件名。 + + Raises: + NotFoundError: 快照不存在或托管文件已不存在。 + """ + from pathlib import Path + + snapshot = db.session.get(ShippingInventoryFile, snapshot_id) + if snapshot is None: + raise NotFoundError('Inventory snapshot not found', code='SHIPPING.INVENTORY_SNAPSHOT_NOT_FOUND') + path = Path(str(snapshot.storage_path or '')).resolve() + if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file(): + raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.INVENTORY_SNAPSHOT_FILE_NOT_FOUND') + filename = str(snapshot.source_file_name or f'{snapshot.inventory_file_no}{path.suffix or ".xlsx"}') + return str(path), filename + + +def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]: + """列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。""" + file_rows = ShippingInventoryFile.query.filter( + ShippingInventoryFile.rpa_run_no.is_not(None), + ).order_by( + ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(), + ).limit(max(1, min(limit, 200))).all() + records = [_snapshot_payload(row) for row in file_rows] + known_identities = { + (str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or '')) + for item in records + } + + # 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。 + schedule_runs = ScheduleRun.query.join(ScheduleTask).filter( + ScheduleTask.platform_api_path == 'shipping-inventory-rpa', + ).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all() + for run in schedule_runs: + response = run.api_response_json if isinstance(run.api_response_json, dict) else {} + request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {} + run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip() + items: list[tuple[str, dict[str, Any]]] = [] + for status, key in (('skipped', 'skipped'), ('failed', 'failed')): + for item in response.get(key) if isinstance(response.get(key), list) else []: + if isinstance(item, dict): + items.append((status, item)) + if not items and run.status in {'queued', 'running'}: + pending = (run.response_summary_json or {}).get('pending_details', []) + for item in pending if isinstance(pending, list) else []: + if isinstance(item, dict): + items.append(('awaiting_rpa', item)) + if not items and run.status in {'failed', 'partial_failed'}: + for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []: + items.append(('failed', {'source_code': source_code, 'error_message': run.error_message})) + for status, item in items: + source_code = str(item.get('source_code') or '').strip() + warehouse_id = str(item.get('warehouse_id') or '').strip() + identity = (run_no, source_code, warehouse_id) + if identity in known_identities: + continue + known_identities.add(identity) + records.append({ + 'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}', + 'inventory_file_no': None, + 'source_code': source_code or None, + 'warehouse_id': warehouse_id or None, + 'snapshot_status': status, + 'export_status': status, + 'identity_status': None, + 'line_count': 0, + 'share_mode': None, + 'exported_at': _iso(run.finished_at or run.created_at), + 'expires_at': None, + 'rpa_run_no': run_no or None, + 'schedule_run_id': run.id, + 'source_file_name': None, + 'created_at': _iso(run.created_at), + 'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None, + }) + records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True) + return records[:max(1, min(limit, 200))] + + +def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_id: str | None) -> bool: + """判断已确认的货代仓库是否已有精确映射或库存源默认映射。""" + query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True) + warehouse = str(warehouse_id or '').strip().upper() + if warehouse and query.filter_by(freight_warehouse_id=warehouse).first() is not None: + return True + return query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() is not None + + +def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]: + """复核当前测试文件与已绑定方案,返回解析和仓库映射的启用前置条件。""" + missing: list[str] = [] + details: dict[str, Any] = {'sample_warehouses': []} + confirmed_test = ShippingInventoryConfigurationTestRun.query.filter_by( + inventory_source_id=source.id, + status='completed', + source_config_version=source.config_version, + ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {} + if not confirmed_test or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0): + return ['configuration_test'], details + analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id) + profile = source.parsing_profile + if analysis is None or profile is None: + return ['configuration_test'], details + structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} + candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else [] + definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + selected = next((item for item in candidates if isinstance(item, dict) + and item.get('sheet_name') == definition.get('sheet_name') + and item.get('header_row_index') == definition.get('header_row_index')), None) + headers = [str(item).strip() for item in (selected or {}).get('headers', []) if str(item).strip()] + duplicate_headers = { + str(item.get('header') or '').strip() + for item in (selected or {}).get('columns', []) + if isinstance(item, dict) and item.get('duplicate') + } + mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {} + from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids + + runtime_mapping, catalog = runtime_field_mapping(mapping) + usages = usage_field_ids() + mapped_ids = set(runtime_mapping) + match_fields = mapped_ids & usages.get('match_identity', set()) + quantity_fields = mapped_ids & usages.get('inventory_quantity', set()) + required_fields = match_fields | quantity_fields + if ( + not selected + or not match_fields + or len(quantity_fields) != 1 + or not required_fields <= set(runtime_mapping) + or any(str(runtime_mapping.get(field) or '').strip() not in headers for field in required_fields) + or any(str(value or '').strip() in duplicate_headers for value in mapping.values()) + or not int((selected or {}).get('sample_row_count') or 0) + ): + missing.append('parsing_validation') + return missing, details + column_by_header = { + str(item.get('header') or '').strip(): item + for item in (selected or {}).get('columns', []) if isinstance(item, dict) + } + quantity_codes = quantity_fields + quantity_column = next(( + column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {}) + for field in quantity_codes + ), {}) + identifier_columns = [ + column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {}) + for field in match_fields + ] + if ( + quantity_column.get('inferred_type') != 'number' + or any(not item.get('sample_values') for item in identifier_columns) + ): + missing.append('parsing_validation') + return missing, details + if source.warehouse_resolution_mode == 'fixed': + if not _enabled_external_mapping_exists(source, source.fixed_warehouse_id): + missing.append('warehouse_mapping') + return missing, details + warehouse_codes = mapped_ids & usages.get('warehouse_identity', set()) + if len(warehouse_codes) != 1: + missing.append('warehouse_identification') + return missing, details + warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '') + if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers: + missing.append('warehouse_identification') + return missing, details + column = next((item for item in (selected or {}).get('columns', []) + if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {}) + sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()}) + details['sample_warehouses'] = sample_warehouses + if not sample_warehouses or any(not _enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses): + missing.append('warehouse_mapping') + return missing, details + + +def _template_validation_missing(source: ShippingInventorySource) -> list[str]: + """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" + template = source.excel_template + profile = source.parsing_profile + if template is None or profile is None: + return [] + definition = template.definition_json if isinstance(template.definition_json, dict) else {} + mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] + profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()} + invalid = any( + isinstance(item, dict) + and item.get('source_kind') == 'inventory_field' + and str(item.get('source_key') or '') not in inventory_fields + for item in mappings + ) + return ['template_validation'] if not mappings or invalid else [] + + +def _activation_missing_requirements(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]: + """计算库存站点进入正式运行前尚未完成的业务步骤和测试验证详情。""" + missing: list[str] = [] + if source.rpa_profile is None or not source.rpa_profile.enabled: + missing.append('rpa_profile') + if source.parsing_profile is None or source.parsing_profile.status != 'published': + missing.append('parsing_profile') + if source.excel_template is None or source.excel_template.status != 'published': + missing.append('excel_template') + else: + missing.extend(_template_validation_missing(source)) + validation_missing, validation_details = _test_analysis_validation(source) + missing.extend(validation_missing) + return missing, validation_details + + +def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]: + """返回库存站点启用检查结果,供管理端展示下一步操作。""" + missing, validation = _activation_missing_requirements(source) + return { + 'ready': not missing, + 'missing_requirements': missing, + 'validation': validation, + } + + +def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """启用完成验证的库存站点;未通过任一前置条件时保持停用。""" + source = db.session.get(ShippingInventorySource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + status = get_source_activation_status(source) + if not status['ready']: + raise ConflictError( + 'Inventory Source is not ready for activation', + code='SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED', + details=status, + ) + source.enabled = True + source.updated_by = actor_id + source.config_version += 1 + db.session.commit() + return _source_payload(source) + + +def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """停用库存站点,保留其解析方案和历史运行审计以便后续重新测试。""" + source = db.session.get(ShippingInventorySource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + source.enabled = False + source.updated_by = actor_id + source.config_version += 1 + db.session.commit() + return _source_payload(source) + + +def save_source( + data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None, + allow_enable_transition: bool = True, +) -> dict[str, Any]: + """保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。""" + source = db.session.get(ShippingInventorySource, source_id) if source_id else None + if source_id and source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + try: + profile_id = int(data.get('rpa_profile_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('rpa_profile_id is required') from exc + profile = db.session.get(ShippingRpaProfile, profile_id) + if profile is None: + raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False) + if not allow_enable_transition: + # 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。 + enabled = bool(source.enabled) if source is not None else False + else: + enabled = requested_enabled + if enabled and not profile.enabled: + raise ValidationError( + 'Enabled Inventory Source requires an enabled RPA Profile', + code='SHIPPING.RPA_PROFILE_DISABLED', + ) + parsing_profile_id = data.get('parsing_profile_id') + parsing_profile = db.session.get(ShippingInventoryParsingProfile, int(parsing_profile_id)) if str(parsing_profile_id or '').isdigit() else None + if parsing_profile_id not in (None, '', 0, '0') and (parsing_profile is None or parsing_profile.status != 'published'): + raise ValidationError('parsing_profile_id must reference a published profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + if enabled and parsing_profile is None: + raise ValidationError('published parsing_profile_id is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + excel_template_id = data.get('excel_template_id') + excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None + if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'): + raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') + if enabled and excel_template is None: + raise ValidationError('published excel_template_id is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') + is_new = source is None + source = source or ShippingInventorySource( + source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed', + ) + source.source_code = str(_text(data, 'source_code', required=True)).upper() + source.display_name = str(_text(data, 'display_name', required=True)) + source.connector_type = str(_text(data, 'connector_type', required=True)).lower() + source.rpa_profile = profile + source.parsing_profile = parsing_profile + source.excel_template = excel_template + source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower() + source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id') + source.report_path_json = _validate_report_path(source.connector_type, _json_object(data, 'report_path_json')) + source.query_parameters_json = _validate_query_parameters(data) + source.match_aliases_json = _json_string_list(data, 'match_aliases_json') + source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400) + source.enabled = enabled + source.updated_by = actor_id + if source_id: + source.config_version += 1 + if is_new: + source.created_by = actor_id + db.session.add(source) + validate_source_profile(source, profile) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.INVENTORY_SOURCE_INVALID') from exc + return _source_payload(source) + + +def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]: + return { + 'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope, + 'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status, + 'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version, + 'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id, + 'system_fact_key': c.system_fact_key, 'operator': c.operator, 'expected_value_json': c.expected_value_json, + 'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions], + } + + +def _validate_rule_condition_expected(operator: str, value: Any) -> Any: + """按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。""" + if operator in {'is_empty', 'is_not_empty'}: + return None + if operator in {'in', 'not_in'}: + if not isinstance(value, list): + raise ValidationError('List operator requires a string list', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + normalized = [str(item).strip() for item in value if str(item).strip()] + if not normalized: + raise ValidationError('List operator requires at least one value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + return normalized + if operator in {'numeric_length', 'string_length'}: + try: + length = int(value) + except (TypeError, ValueError) as exc: + raise ValidationError('Length operator requires an integer', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') from exc + if length < 0: + raise ValidationError('Length must not be negative', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + return length + if not isinstance(value, str) or not value.strip(): + raise ValidationError('Routing condition requires an expected value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + return value.strip() + + +def list_rules() -> list[dict[str, Any]]: + """列出规则及条件,用于草稿编辑和已发布规则查看。""" + return [_rule_payload(item) for item in ShippingInventoryRoutingRule.query.order_by(ShippingInventoryRoutingRule.priority.desc()).all()] + + +def delete_draft_rule(rule_id: int) -> None: + """删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。""" + rule = db.session.get(ShippingInventoryRoutingRule, rule_id) + if rule is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + if rule.status != 'draft': + raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.INVENTORY_RULE_DELETE_BLOCKED') + db.session.delete(rule) + db.session.commit() + + +def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: + """归档已发布规则,使其不再参与新路由,同时保留已发布版本。""" + rule = db.session.get(ShippingInventoryRoutingRule, rule_id) + if rule is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + if rule.status != 'published': + raise ConflictError('Only published routing rules can be retired', code='SHIPPING.INVENTORY_RULE_RETIRE_INVALID') + rule.status = 'retired' + rule.updated_by = actor_id + db.session.commit() + return _rule_payload(rule) + + +def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]: + """保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。""" + if rule_id: + current = db.session.get(ShippingInventoryRoutingRule, rule_id) + if current is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + if current.status != 'draft': + raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.INVENTORY_RULE_IMMUTABLE') + rule = current if rule_id else ShippingInventoryRoutingRule( + rule_code='', rule_name='', scope='', action_type='', action_payload_json={} + ) + rule.rule_code = str(_text(data, 'rule_code', required=True)).upper() + rule.rule_name = str(_text(data, 'rule_name', required=True)) + rule.scope = str(_text(data, 'scope', required=True)).lower() + rule.priority = int(data.get('priority') or 0) + rule.match_mode = str(data.get('match_mode') or 'all').lower() + rule.status = 'draft' + rule.action_type = str(_text(data, 'action_type', required=True)).lower() + rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {} + rule.version = int(data.get('version') or 1) + if not rule_id: + rule.created_by = actor_id + rule.updated_by = actor_id + if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}: + raise ValidationError('Invalid routing rule metadata', code='SHIPPING.INVENTORY_RULE_INVALID') + conditions = data.get('conditions') + if not isinstance(conditions, list) or not conditions: + raise ValidationError('Routing rule requires conditions', code='SHIPPING.INVENTORY_RULE_CONDITIONS_REQUIRED') + # 草稿更新在同一版本内替换条件;发布后不可原地修改。 + if rule_id: + db.session.query(ShippingInventoryRoutingRuleCondition).filter_by(rule_id=rule.id).delete( + synchronize_session=False + ) + db.session.flush() + db.session.expire(rule, ['conditions']) + for index, item in enumerate(conditions, start=1): + if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS: + raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + source_kind = str(item.get('source_kind') or 'order_field') + order_field_id = str(item.get('order_field_id') or '') or None + system_fact_key = str(item.get('system_fact_key') or '') or None + field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None + if source_kind == 'order_field': + if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'): + raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + system_fact_key = None + elif source_kind == 'system_fact': + if system_fact_key not in ALLOWED_SYSTEM_FACT_KEYS: + raise ValidationError('Routing system fact is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + order_field_id = None + else: + raise ValidationError('Routing condition source is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + operator = str(item['operator']) + rule.conditions.append(ShippingInventoryRoutingRuleCondition( + condition_group=int(item.get('condition_group') or 1), source_kind=source_kind, + order_field_id=order_field_id, system_fact_key=system_fact_key, + operator=operator, expected_value_json=_validate_rule_condition_expected( + operator, item.get('expected_value_json'), + ), sequence=index, + )) + if not rule_id: + db.session.add(rule) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('Routing rule code and version already exist', code='SHIPPING.INVENTORY_RULE_CONFLICT') from exc + return _rule_payload(rule) + + +def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: + """发布草稿并写入不可变规则定义快照。""" + rule = db.session.get(ShippingInventoryRoutingRule, rule_id) + if rule is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + if rule.status != 'draft': + raise ConflictError('Only draft routing rules can be published', code='SHIPPING.INVENTORY_RULE_PUBLISH_INVALID') + if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}: + payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {} + source_codes = { + str(code or '').strip().upper() + for code in payload.get('source_codes', []) + if str(code or '').strip() + } + enabled_codes = { + str(code).strip().upper() + for (code,) in db.session.query(ShippingInventorySource.source_code).filter_by(enabled=True).all() + } + missing_codes = sorted(source_codes - enabled_codes) + if missing_codes: + raise ValidationError( + 'Routing rule references unavailable inventory sources', + code='SHIPPING.INVENTORY_RULE_SOURCE_INVALID', + details={'source_codes': missing_codes}, + ) + rule.status = 'published' + rule.updated_by = actor_id + db.session.add(ShippingInventoryRoutingRuleVersion( + rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id, + )) + db.session.commit() + return _rule_payload(rule) + + +def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, Any]: + return { + 'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id, + 'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code, + 'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code, + 'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name, + 'enabled': bool(mapping.enabled), 'version': mapping.version, + } + + +def list_external_mappings() -> list[dict[str, Any]]: + """列出库存源到外部系统仓库的映射,不执行调拨判断。""" + return [_external_payload(item) for item in ShippingInventoryExternalMapping.query.order_by(ShippingInventoryExternalMapping.id).all()] + + +def delete_external_mapping(mapping_id: int) -> None: + """删除错误的外部仓库映射;历史文件和任务不回写此实时配置。""" + record = db.session.get(ShippingInventoryExternalMapping, mapping_id) + if record is None: + raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND') + db.session.delete(record) + db.session.commit() + + +def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]: + """创建或更新精确/默认外部系统映射。""" + record = db.session.get(ShippingInventoryExternalMapping, mapping_id) if mapping_id else None + if mapping_id and record is None: + raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND') + try: + source_id = int(data.get('inventory_source_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('inventory_source_id is required') from exc + if db.session.get(ShippingInventorySource, source_id) is None: + raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='') + record.inventory_source_id = source_id + # Freight warehouse is a business identity token; normalize it to match runtime inventory rows. + record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None + record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper() + record.external_organization_code = _text(data, 'external_organization_code') + record.external_site_code = _text(data, 'external_site_code') + record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper() + record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True)) + record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True) + record.updated_by = actor_id + if not mapping_id: + record.created_by = actor_id + db.session.add(record) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_CONFLICT') from exc + return _external_payload(record) diff --git a/backend/app/services/agent_runtime_context/parser.py b/backend/app/services/agent_runtime_context/parser.py index f00d6529..2f7c9c61 100644 --- a/backend/app/services/agent_runtime_context/parser.py +++ b/backend/app/services/agent_runtime_context/parser.py @@ -34,6 +34,8 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset( "refs.capability", "refs.intake_nos", "refs.file_name", + "refs.temporary_inventory_asset_no", + "refs.temporary_inventory_session_no", "refs.schedule_task_id", "refs.hxops_turn_id", "domain.type", diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 7bb6abd5..dcb8cc38 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -2,7 +2,7 @@ backend/app/services/schedule/job_options.py 用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。 -依赖:models.Agent、shipping_notice.inventory_sources。 +依赖:models.Agent、shipping_notice.inventory_source_repository。 逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用; 前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。 """ @@ -32,8 +32,8 @@ def _agent_apps_options() -> list[dict[str, Any]]: def _shipping_inventory_sources_options() -> list[dict[str, Any]]: - """启用中的货代库存源(value=source_code,来自 backend/config/shipping_inventory_sources.yaml)。""" - from app.services.shipping_notice.inventory_sources import list_inventory_sources + """启用中的货代库存源(value=source_code,来自数据库主数据)。""" + from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources return [ { @@ -41,11 +41,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]: "value": source.get("source_code"), "description": ( f"{source.get('connector_type')} · " - f"{source.get('site_id') or '-'} · " - f"{source.get('warehouse_id')}" + f"{source.get('warehouse_resolution_mode')} · " + f"{source.get('fixed_warehouse_id') or '-'}" ), } - for source in list_inventory_sources() + for source in list_database_inventory_sources() ] diff --git a/backend/app/services/schedule/shipping_inventory_rpa_archive.py b/backend/app/services/schedule/shipping_inventory_rpa_archive.py index 7d2a3b72..17f56eb1 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_archive.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_archive.py @@ -36,14 +36,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { def get_inventory_archive_dir() -> str: """返回库存 RPA 原始 ZIP 归档根目录(自动创建)。""" archive_dir = Path( - current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR") + current_app.config.get("SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR") if current_app else "" ) if not str(archive_dir): from app.core.config.settings import Config - archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR) + archive_dir = Path(Config.SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR) archive_dir.mkdir(parents=True, exist_ok=True) return str(archive_dir) @@ -195,7 +195,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool: """ 校验归档 ZIP 路径是否安全可下载。 - 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。 + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。 """ resolved = zip_path.resolve() if resolved.suffix.lower() != ".zip": @@ -216,7 +216,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: 解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。 核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、 - 且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。 + 且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。 Returns: tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 diff --git a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py index 11975d55..899a6768 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py @@ -28,7 +28,6 @@ FinalizeScheduleRunResult = dict[str, Any] _INVENTORY_RPA_HEADER_ORDER = [ "source_code", - "site_id", "warehouse_id", "display_name", "inventory_file_no", @@ -38,7 +37,6 @@ _INVENTORY_RPA_HEADER_ORDER = [ ] _INVENTORY_RPA_HEADER_LABELS = { "source_code": "库存源", - "site_id": "站点", "warehouse_id": "仓库", "display_name": "名称", "inventory_file_no": "库存快照号", @@ -145,7 +143,6 @@ def _build_finalize_details( base = pending_by_key.get(key, {}) details.append({ "source_code": code or item.get("source_code"), - "site_id": item.get("site_id") or base.get("site_id"), "warehouse_id": wh or base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": item.get("inventory_file_no"), @@ -163,7 +160,6 @@ def _build_finalize_details( base = pending_by_key.get(key, {}) details.append({ "source_code": code or item.get("source_code"), - "site_id": item.get("site_id") or base.get("site_id"), "warehouse_id": wh or base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": "", @@ -181,7 +177,6 @@ def _build_finalize_details( base = pending_by_key.get(key, {}) details.append({ "source_code": code or item.get("source_code"), - "site_id": item.get("site_id") or base.get("site_id"), "warehouse_id": wh or base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": "", @@ -194,7 +189,6 @@ def _build_finalize_details( continue details.append({ "source_code": base.get("source_code"), - "site_id": base.get("site_id"), "warehouse_id": base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": "", diff --git a/backend/app/services/schedule/shipping_inventory_rpa_job.py b/backend/app/services/schedule/shipping_inventory_rpa_job.py index 162dc34f..a7d729fa 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_job.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_job.py @@ -1,8 +1,8 @@ """ backend/app/services/schedule/shipping_inventory_rpa_job.py -用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。 -依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。 +用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。 +依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。 逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用; 写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。 """ @@ -17,7 +17,7 @@ from app import db from app.core.errors import ServiceUnavailableError from app.models import ScheduleRun, ScheduleTask from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS -from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source, list_inventory_sources +from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE @@ -53,34 +53,15 @@ def _normalize_filter_tokens(raw: Any) -> set[str]: return {str(item).strip().upper() for item in values if str(item).strip()} -def _source_identity_tokens(source: dict[str, Any]) -> set[str]: - """收集库存源可用于匹配的标识集合(source_code / site_id / warehouse_id / match_aliases)。""" - tokens: set[str] = set() - for key in ("source_code", "site_id", "warehouse_id"): - value = str(source.get(key) or "").strip().upper() - if value: - tokens.add(value) - for alias in source.get("match_aliases") or []: - value = str(alias or "").strip().upper() - if value: - tokens.add(value) - return tokens - - def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]: """ 从 api_body_template 提取筛选 token。 - 推荐键:source_codes;兼容:source_code / site_ids / site_id / warehouse_ids / warehouse_id / match_aliases。 + 仅支持 source_codes/source_code,排程目标必须是 Inventory Source。 """ wanted: set[str] = set() for key in ( "source_codes", "source_code", - "site_ids", - "site_id", - "warehouse_ids", - "warehouse_id", - "match_aliases", ): if key in body_template: wanted |= _normalize_filter_tokens(body_template.get(key)) @@ -107,18 +88,18 @@ def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None: def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]: """ 读取 enabled 库存源;job_params / api_body_template 可限定子集。 - 核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / site_id / warehouse_id / match_aliases 命中。 + 核心逻辑:无筛选则导出全部启用 Source;有筛选时严格按 source_code 命中。 """ - enabled = list_inventory_sources() + enabled = list_database_inventory_sources() body_template = _resolve_filter_payload(task) if body_template: wanted = _extract_wanted_tokens(body_template) if wanted: enabled = [ item for item in enabled - if _source_identity_tokens(item) & wanted + if str(item.get('source_code') or '').strip().upper() in wanted ] - return [source for source in enabled if build_rpa_inventory_source(source.get("source_code"))] + return enabled def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: @@ -183,8 +164,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> details = [ { "source_code": item.get("source_code"), - "site_id": item.get("site_id"), - "warehouse_id": item.get("warehouse_id"), + "warehouse_id": item.get("fixed_warehouse_id"), "display_name": item.get("display_name"), } for item in sources diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py index 2a914372..aa55fd72 100644 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -675,7 +675,8 @@ def create_shipping_batch_from_candidates( target = ( db.session.query(ShippingTask) .filter_by(task_no=target_no, user_id=int(user_id)) - .with_for_update() + # Lock only ShippingTask. Its eager nullable ShippingCase join cannot be locked by PostgreSQL. + .with_for_update(of=ShippingTask) .first() ) if target is None: diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index fb24404f..ac80ae31 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -157,7 +157,24 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: if ( process_status == "waiting_inventory" and not getattr(task, "inventory_lines_json", None) - and pending_reason in {"", PH_RPA_PENDING} + and pending_reason == PH_RPA_PENDING + ): + # A pending task already has an explicit RPA attempt. Poll its timeout + # state through the RPA workflow; normal auto-progress must not start RPA. + from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + + result = ensure_inventory_via_rpa(task, mode="auto") + if current_app: + current_app.logger.info( + "[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s", + task.task_no, + result.get("status"), + str(result.get("message") or "")[:300], + ) + elif ( + process_status == "waiting_inventory" + and not getattr(task, "inventory_lines_json", None) + and pending_reason == "" ): payload["mode"] = "auto" result = auto_progress(payload) @@ -370,7 +387,10 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]: process_status = str(getattr(task, "process_status", "") or "").strip().lower() pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING: - result = auto_progress({"task_id": task.task_no, "mode": "auto"}) + # This is a poll of an existing request, never an implicit new RPA run. + from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + + result = ensure_inventory_via_rpa(task, mode="auto") status = str(result.get("status") or "").strip().lower() if status in {"ok", "running", "needs_human"}: started += 1 diff --git a/backend/app/services/shipping_notice/business_case_service.py b/backend/app/services/shipping_notice/business_case_service.py index 3e4e38d8..184e5cdc 100644 --- a/backend/app/services/shipping_notice/business_case_service.py +++ b/backend/app/services/shipping_notice/business_case_service.py @@ -3,7 +3,7 @@ services/shipping_notice/business_case_service.py 用途:为新建货代任务创建或继承业务单聚合。 依赖:db、ShippingCase、ShippingTask、uuid/datetime。 -逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单,必要时为历史父任务补建。 +逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。 """ from __future__ import annotations @@ -50,8 +50,8 @@ def resolve_shipping_case_for_new_task( """ 为即将创建的任务解析业务单归属。 - 核心逻辑:revision 继承父任务业务单;历史父任务未关联时在同一事务补建; - normal/force_create 均创建独立业务单,保证强制新建重新占用未来流水。 + 核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单, + 保证强制新建重新占用未来流水。 Args: supersedes_task_id: 修订目标任务主键,仅 revision 使用。 @@ -78,11 +78,11 @@ def resolve_shipping_case_for_new_task( 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 + if parent.shipping_case is None: + raise ConflictError( + '修订目标任务缺少业务单关联', + code='SHIPPING_NOTICE.REVISION_CASE_MISSING', + details={'supersedes_task_id': supersedes_task_id}, + ) + return parent.shipping_case diff --git a/backend/app/services/shipping_notice/chat_action_extended_handlers.py b/backend/app/services/shipping_notice/chat_action_extended_handlers.py index b75035ec..191f0ba1 100644 --- a/backend/app/services/shipping_notice/chat_action_extended_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_extended_handlers.py @@ -1,27 +1,24 @@ """ backend/app/services/shipping_notice/chat_action_extended_handlers.py -用途:货代 Chat Turn 扩展 Action Handler(上传/映射/切票/缺口查询)。 +用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。 依赖:shipping_tools、task_workflow、tool_common、shipping_turn_helpers、action_registry。 逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大。 """ from __future__ import annotations -import io from typing import Any, Iterator -from werkzeug.datastructures import FileStorage - from app import db from app.core.errors import NotFoundError, ValidationError from app.services.chat.action_registry import register_action_handler from app.services.chat.action_schema import TurnEvent from app.services.chat.turn_context import TurnContext from app.services.shipping_notice import tools as shipping_tools -from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK, MAP_JSON from app.services.shipping_notice.query_service import ( get_batch_for_user, + get_task_by_ref, get_task_for_user, serialize_task_detail, ) @@ -61,16 +58,11 @@ def _require_task(ctx: TurnContext): return task -def _filestorage_from_staged(staged: dict[str, Any]) -> FileStorage: - data = staged.get("data") - if not isinstance(data, (bytes, bytearray)): - raise ValidationError("upload file data is missing") - filename = str(staged.get("filename") or "upload").strip() or "upload" - content_type = str(staged.get("content_type") or "").strip() or None - return FileStorage(stream=io.BytesIO(bytes(data)), filename=filename, content_type=content_type) +def _first_staged_upload(ctx: TurnContext): + """将当前 Chat Turn 暂存附件转换为通知替换流程可读取的文件对象。""" + from io import BytesIO + from werkzeug.datastructures import FileStorage - -def _first_staged_upload(ctx: TurnContext) -> FileStorage: payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} staged_files = payload.get("_staged_files") if not isinstance(staged_files, list) or not staged_files: @@ -78,18 +70,14 @@ def _first_staged_upload(ctx: TurnContext) -> FileStorage: first = staged_files[0] if not isinstance(first, dict): raise ValidationError("invalid staged upload") - return _filestorage_from_staged(first) - - -def _format_inventory_upload_message(result: dict[str, Any], task_no: str) -> str: - base = tool_result_message(result) or "库存文件已上传。" - lines = [base, f"任务编号:{task_no}"] - checkpoint = str(result.get("checkpoint") or "").strip() - if checkpoint == "map_infer": - lines.append("下一步:请确认或调整列映射。") - elif checkpoint == "align_review": - lines.append("下一步:请核对字段对齐结果。") - return "\n".join(lines) + data = first.get("data") + if not isinstance(data, (bytes, bytearray)): + raise ValidationError("upload file data is missing") + return FileStorage( + stream=BytesIO(bytes(data)), + filename=str(first.get("filename") or "upload").strip() or "upload", + content_type=str(first.get("content_type") or "").strip() or None, + ) def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str: @@ -105,45 +93,6 @@ def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str: return "\n".join(line for line in lines if line) -def _format_mapping_applied_message(result: dict[str, Any], task_no: str, mapping: dict[str, str]) -> str: - mapping_text = ",".join(f"{key}={value}" for key, value in mapping.items()) - hint = tool_result_message(result) - lines = [ - f"映射已应用:{mapping_text}" if mapping_text else "映射已应用并解析库存。", - f"任务编号:{task_no}", - hint, - ] - return "\n".join(line for line in lines if line) - - -class ShippingUploadInventoryAction: - action_type = "shipping.upload_inventory" - - def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - task = _require_task(ctx) - upload = _first_staged_upload(ctx) - yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."}) - result = shipping_tools.upload_inventory_file(task.task_no, upload) - if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed": - raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "upload_inventory failed") - from app.services.shipping_notice.query_service import get_task_by_ref - - refreshed = get_task_by_ref(task.task_no) or task - yield shipping_task_ui_state_event(refreshed) - data = result.get("data") if isinstance(result.get("data"), dict) else {} - message_payload: dict[str, Any] = { - "task_no": task.task_no, - "tool_result": result, - "checkpoint": result.get("checkpoint"), - } - preview = data.get("schema_preview") - if isinstance(preview, dict): - message_payload["schema_preview"] = preview - content = _format_inventory_upload_message(result, task.task_no) - yield from stream_text_events(content, message_type="text", payload=message_payload) - yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"}) - - class ShippingReplaceNoticeAction: action_type = "shipping.replace_notice" @@ -190,34 +139,37 @@ class ShippingReplaceNoticeAction: yield TurnEvent(event="step.completed", data={"step_id": "replace_notice"}) -class ShippingApplyInventoryMappingAction: - action_type = "shipping.apply_inventory_mapping" +class ShippingUploadInventoryAction: + """为已有发货任务上传正式库存文件,并使用库存站点发布方案解析。""" + + action_type = "shipping.upload_inventory" def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]: - task = _require_task(ctx) - payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {} - mapping_raw = payload.get(MAP_JSON) or payload.get("map_json") or payload.get("mapping") - if not isinstance(mapping_raw, dict) or not mapping_raw: - raise ValidationError(f"{MAP_JSON} is required") - mapping = {str(k): str(v) for k, v in mapping_raw.items() if str(v or "").strip()} - if not mapping.get("part_number") or not mapping.get("available_qty"): - raise ValidationError("part_number and available_qty mapping are required") - yield TurnEvent(event="step.started", data={"step_id": "apply_inventory_mapping", "label": "应用列映射..."}) - result = shipping_tools.apply_inventory_mapping({ - "task_id": task.task_no, - MAP_JSON: mapping, - AUTO_CHAIN_FALLBACK: True, - "event_source": "chat_turn", - }) - if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed": - raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "apply_inventory_mapping failed") - from app.services.shipping_notice.query_service import get_task_by_ref + """ + 保存当前 Turn 的库存附件并返回确定性解析结果。 + 核心逻辑:先按当前用户反查任务,再将 multipart 暂存附件交给既有库存工作流; + 本 Handler 不调用 Dify、不创建临时库存会话,也不允许任务级猜列或字段映射确认。 + """ + task = _require_task(ctx) + upload = _first_staged_upload(ctx) + yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."}) + result = shipping_tools.upload_inventory_file(task.task_no, upload) + if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed": + raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "upload_inventory failed") refreshed = get_task_by_ref(task.task_no) or task yield shipping_task_ui_state_event(refreshed) - content = _format_mapping_applied_message(result, task.task_no, mapping) - yield from stream_text_events(content, payload={"task_no": task.task_no, "mapping": mapping, "tool_result": result}) - yield TurnEvent(event="step.completed", data={"step_id": "apply_inventory_mapping"}) + data = result.get("data") if isinstance(result.get("data"), dict) else {} + content = "\n".join(filter(None, [tool_result_message(result), f"任务编号:{task.task_no}"])) + yield from stream_text_events( + content, + payload={ + "task_no": task.task_no, + "inventory_file_no": data.get("inventory_file_no"), + "tool_result": result, + }, + ) + yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"}) class ShippingSwitchBatchFocusAction: @@ -274,9 +226,8 @@ class ShippingQueryShortageDetailsAction: _HANDLERS = ( - ShippingUploadInventoryAction(), ShippingReplaceNoticeAction(), - ShippingApplyInventoryMappingAction(), + ShippingUploadInventoryAction(), ShippingSwitchBatchFocusAction(), ShippingQueryShortageDetailsAction(), ) diff --git a/backend/app/services/shipping_notice/chat_action_handlers.py b/backend/app/services/shipping_notice/chat_action_handlers.py index b50612d2..50f8fdca 100644 --- a/backend/app/services/shipping_notice/chat_action_handlers.py +++ b/backend/app/services/shipping_notice/chat_action_handlers.py @@ -51,35 +51,8 @@ def _require_task(ctx: TurnContext): def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str: """对齐前端 shippingDecisionFormat.ts 的助手摘要格式。""" lines = [_tool_result_message(result) or "操作已完成。"] - data = result.get("data") if isinstance(result.get("data"), dict) else {} - if decision == "correct_inventory_mapping": - preview = data.get("schema_preview") if isinstance(data.get("schema_preview"), dict) else {} - headers = [str(item) for item in (preview.get("headers") or []) if item] - suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {} - header_row_index = preview.get("header_row_index") - if header_row_index: - lines.extend(["", f"表头在第 {header_row_index} 行:{' | '.join(headers)}"]) - elif headers: - lines.extend(["", f"当前表头:{' | '.join(headers)}"]) - mapping_lines = [ - f"- part_number → {suggested['part_number']}" if suggested.get("part_number") else None, - f"- aws_part_number → {suggested['aws_part_number']}" if suggested.get("aws_part_number") else None, - f"- reservation_id → {suggested['reservation_id']}" if suggested.get("reservation_id") else None, - f"- available_qty → {suggested['available_qty']}" if suggested.get("available_qty") else None, - ] - mapping_lines = [line for line in mapping_lines if line] - if mapping_lines: - lines.extend(["", "建议列映射:", *mapping_lines]) - lines.extend([ - "", - "如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。", - "也可点击「选择库存文件」重新上传。", - ]) - elif decision == "confirm_inventory_mapping": - if str(result.get("checkpoint") or "").strip() == "map_ok": - lines.extend(["", "下一步:匹配库存与发货需求。"]) - elif decision == "reparse_inventory": - lines.extend(["", "请重新上传或粘贴库存 Excel。"]) + if decision == "reparse_inventory": + lines.extend(["", "请点击「选择库存文件」重新上传。"]) lines.extend(["", f"任务编号:{task_no}"]) return "\n".join(lines) diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index bfe90155..9d8c45a5 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -8,23 +8,11 @@ services/shipping_notice/constants.py from __future__ import annotations -from typing import Any - -# HTTP JSON request/response fields -MAP_JSON = "map_json" -SUGGEST_OK = "suggest_ok" -AUTO_MAP = "auto_map" # Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑 AUTO_CHAIN_FALLBACK = "auto_chain_fallback" -# Legacy request field names (read-only compat) -MAP_JSON_LEGACY = "column_mapping_json" - # Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py) -CP_ALIGN_REVIEW = "align_review" -CP_MAP_INFER = "map_infer" 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" @@ -45,7 +33,6 @@ CP_UPLOADED = "uploaded" CP_COMPLETED = "completed" # review_status -RS_ALIGN_REVIEW = "align_review" RS_PARSE_REVIEW = "parse_review" RS_SHORTAGE_REVIEW = "shortage_review" RS_RSV_REQ = "rsv_req" @@ -53,8 +40,6 @@ RS_REJECTED = "rejected" RS_CONFIRMED = "confirmed" # pending_human_reason (internal; shortened) -PH_ALIGN_REVIEW = CP_ALIGN_REVIEW -PH_MAP_INFER = CP_MAP_INFER PH_LOW_CONF = "low_confidence" PH_RSV_REQ = CP_RSV_REQ PH_SHORTAGE = "shortage" @@ -65,13 +50,3 @@ PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved" PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" - - -def payload_map_json(payload: dict[str, Any]) -> Any: - """从请求体读取列映射 JSON,兼容 map_json 与 legacy column_mapping_json 字段名。""" - raw = payload.get(MAP_JSON) - if raw is None: - raw = payload.get(MAP_JSON_LEGACY) - if raw is None: - raw = payload.get("field_mapping") - return raw diff --git a/backend/app/services/shipping_notice/context_adapter.py b/backend/app/services/shipping_notice/context_adapter.py index f9cf0527..fe440674 100644 --- a/backend/app/services/shipping_notice/context_adapter.py +++ b/backend/app/services/shipping_notice/context_adapter.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/context_adapter.py 用途:发货通知 Agent 的 Context Adapter,构建 agent_runtime_context Dify inputs。 依赖:shipping_notice.dify_inputs.build_dify_chat_inputs、agent_runtime_context.registry。 -逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传 task/batch。 +逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传任务锚点或临时库存资产锚点。 """ from __future__ import annotations @@ -28,7 +28,7 @@ def build_shipping_notice_context_adapter( """ 构建发货通知 Dify Start inputs。 - 核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch 或待抽取 Intake 集合,委托 dify_inputs 组装 runtime_context。 + 核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch、待抽取 Intake 集合或临时库存资产,委托 dify_inputs 组装 runtime_context。 Args: agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。 @@ -52,4 +52,6 @@ def build_shipping_notice_context_adapter( locale=locale, intake_nos=shipping_hints.get('intake_nos'), capability=shipping_hints.get('capability'), + temporary_inventory_asset_no=shipping_hints.get('temporary_inventory_asset_no'), + temporary_inventory_session_no=shipping_hints.get('temporary_inventory_session_no'), ) diff --git a/backend/app/services/shipping_notice/credential_crypto.py b/backend/app/services/shipping_notice/credential_crypto.py new file mode 100644 index 00000000..59f5a577 --- /dev/null +++ b/backend/app/services/shipping_notice/credential_crypto.py @@ -0,0 +1,82 @@ +""" +services/shipping_notice/credential_crypto.py + +用途:加密和解密库存 RPA Profile 的登录凭据。 +依赖:Flask current_app、cryptography.fernet;调用方仅保存密文,不将凭据写入日志或 API 响应。 +逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用 decrypt_credential。 +""" + +from __future__ import annotations + +from cryptography.fernet import Fernet, InvalidToken +from flask import current_app + +from app.core.errors import ServiceUnavailableError, ValidationError + + +def _fernet() -> Fernet: + """ + 构造当前环境的凭据加密器。 + + 核心逻辑:主密钥只从运行环境读取,缺失或格式无效时拒绝继续,避免写入无法恢复的密文。 + + Returns: + Fernet: 可执行对称加密的实例。 + + Raises: + ServiceUnavailableError: 未配置或配置了无效的主密钥。 + """ + key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip() + if not key: + raise ServiceUnavailableError( + 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured', + code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING', + ) + try: + return Fernet(key.encode('ascii')) + except (ValueError, UnicodeEncodeError) as exc: + raise ServiceUnavailableError( + 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid', + code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID', + ) from exc + + +def encrypt_credential(value: str) -> str: + """ + 加密单个 RPA 凭据字段以便持久化。 + + Args: + value: 非空明文凭据;调用方不得记录此值。 + + Returns: + str: 可安全保存到数据库的 Fernet 密文。 + + Raises: + ValidationError: 传入空凭据。 + """ + plaintext = str(value or '') + if not plaintext: + raise ValidationError('RPA credential must not be empty', code='SHIPPING.RPA_CREDENTIAL_EMPTY') + return _fernet().encrypt(plaintext.encode('utf-8')).decode('ascii') + + +def decrypt_credential(ciphertext: str) -> str: + """ + 在受控运行时解密 RPA 凭据。 + + Args: + ciphertext: 数据库中保存的 Fernet 密文。 + + Returns: + str: 仅供 RPA 执行内存使用的明文。 + + Raises: + ValidationError: 密文为空、已损坏或使用了错误主密钥。 + """ + value = str(ciphertext or '').strip() + if not value: + raise ValidationError('RPA credential ciphertext is missing', code='SHIPPING.RPA_CREDENTIAL_MISSING') + try: + return _fernet().decrypt(value.encode('ascii')).decode('utf-8') + except (InvalidToken, UnicodeDecodeError) as exc: + raise ValidationError('RPA credential ciphertext is invalid', code='SHIPPING.RPA_CREDENTIAL_INVALID') from exc diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py index 7783b019..01192f60 100644 --- a/backend/app/services/shipping_notice/customer_auto_resolution.py +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -25,7 +25,7 @@ from app.models import ( ) 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.tool_common import cfg_bool, cfg_float, cfg_int from app.services.shipping_notice.business_case_service import generate_shipping_case_no from app.services.shipping_notice.business_numbering_service import assign_business_number @@ -35,7 +35,6 @@ CUSTOMER_AUDIT_EVENT_TYPES = ( "customer_auto_resolution_evaluated", "customer_auto_confirmed", "customer_correction_applied", - "customer_historical_backfilled", ) @@ -44,6 +43,48 @@ def auto_customer_resolution_enabled() -> bool: return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False) +def _auto_confirmation_quality_gate() -> dict[str, Any]: + """ + 评估自动确认质量门禁,只以当前强规则会唯一命中的已人工标注样本为分母。 + + 人工标签覆盖的是解析不稳定的真实来件;未达到样本量或准确率时,宁可保留人工复核, + 不允许生成不可逆的客户绑定和业务编号。 + """ + min_samples = cfg_int('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES', 20, min_value=0) + min_accuracy = cfg_float('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY', 0.98, min_value=0.0, max_value=1.0) + labeled = ( + db.session.query(ShippingCustomerShadowResolution) + .filter(ShippingCustomerShadowResolution.manual_customer_id.isnot(None)) + .all() + ) + eligible_samples = 0 + correct_samples = 0 + for shadow in labeled: + decision = _resolve_auto_customer_from_evidence(shadow.evidence_json or []) + if decision['status'] != 'unique_strong_match': + continue + eligible_samples += 1 + if int(decision['customer_id']) == int(shadow.manual_customer_id): + correct_samples += 1 + accuracy = (correct_samples / eligible_samples) if eligible_samples else None + if eligible_samples < min_samples: + status = 'insufficient_labeled_samples' + # min_samples=0 是显式受控放行配置;无样本时不存在可计算的准确率,不应误判为失败。 + elif min_samples > 0 and (accuracy is None or accuracy < min_accuracy): + status = 'insufficient_accuracy' + else: + status = 'eligible' + return { + 'status': status, + 'is_eligible': status == 'eligible', + 'labeled_sample_count': eligible_samples, + 'correct_sample_count': correct_samples, + 'accuracy': accuracy, + 'min_labeled_samples': min_samples, + 'min_accuracy': min_accuracy, + } + + def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool: """判断识别证据是否达到自动确认门槛。""" if identifier.status != "approved" or not identifier.auto_match_allowed: @@ -55,33 +96,10 @@ def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool: 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": []} - +def _resolve_auto_customer_from_evidence(evidence_rows: list[object]) -> dict[str, Any]: + """以候选的规范化证据求唯一强规则客户,不读取总开关或质量门禁。""" matched: dict[int, list[dict[str, Any]]] = {} - for evidence in shadow.evidence_json or []: + for evidence in evidence_rows: if not isinstance(evidence, dict): continue kind = str(evidence.get("type") or "").strip() @@ -120,6 +138,43 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]: } +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": []} + quality_gate = _auto_confirmation_quality_gate() + if not quality_gate['is_eligible']: + return { + 'status': quality_gate['status'], + 'rule_version': AUTO_RESOLUTION_VERSION, + 'customer_id': None, + 'evidence': [], + 'quality_gate': quality_gate, + } + 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": []} + + return {**_resolve_auto_customer_from_evidence(shadow.evidence_json or []), 'quality_gate': quality_gate} + + def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]: """ 尝试自动确认并生成业务编号;未达门槛时保持 customer_review。 @@ -157,52 +212,6 @@ def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]: 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, *, @@ -264,6 +273,8 @@ def correct_numbered_task_customer( 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 == "merged": + raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED") if customer.status != "active": raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE") if original_case.customer_id == customer.id: @@ -339,7 +350,6 @@ def correct_numbered_task_customer( # 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。 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 @@ -383,7 +393,7 @@ def correct_numbered_task_customer( 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() @@ -393,9 +403,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]: 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) @@ -407,10 +414,10 @@ def get_auto_resolution_metrics() -> dict[str, Any]: return { "enabled": auto_customer_resolution_enabled(), "rule_version": AUTO_RESOLUTION_VERSION, + 'quality_gate': _auto_confirmation_quality_gate(), "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": [ { diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py index 72318e5f..77b3cfb1 100644 --- a/backend/app/services/shipping_notice/customer_identity_gate.py +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -24,9 +24,9 @@ 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 + return False case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id)) if case is None or case.customer_id is None: return False @@ -36,10 +36,10 @@ def customer_identity_is_confirmed(task: ShippingTask) -> bool: def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None: """ - 标准客户硬门禁;新业务单未确认时阻断库存、RPA、匹配、Excel 与上传。 + 标准客户硬门禁;业务单缺失或客户未确认时阻断库存、RPA、匹配、Excel 与上传。 Args: - task: 当前发货任务;历史无业务单任务兼容放行。 + task: 当前发货任务。 operation: 触发门禁的操作名,写入错误详情。 Raises: AppError: 客户尚未确认、客户已停用或业务单关联无效。 @@ -101,8 +101,8 @@ def confirm_task_customer( """ 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', + 'Shipping task is missing its required shipping case', + code='SHIPPING.CUSTOMER_CASE_REQUIRED', ) case = ( db.session.query(ShippingCase) @@ -115,6 +115,8 @@ def confirm_task_customer( 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 == 'merged': + raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED') if customer.status != 'active': raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') if case.business_no and case.customer_id not in {None, customer.id}: diff --git a/backend/app/services/shipping_notice/customer_shadow_resolution.py b/backend/app/services/shipping_notice/customer_shadow_resolution.py index a4a76b8c..4355467c 100644 --- a/backend/app/services/shipping_notice/customer_shadow_resolution.py +++ b/backend/app/services/shipping_notice/customer_shadow_resolution.py @@ -17,10 +17,11 @@ from typing import Any from sqlalchemy import func from app import db -from app.core.errors import NotFoundError, ValidationError +from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingCustomer, ShippingCustomerIdentifier, + ShippingCustomerShadowMatch, ShippingCustomerShadowResolution, ShippingNoticeCandidate, ShippingNoticeIntake, @@ -135,6 +136,24 @@ def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> S 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 + # 规范化候选关联用于客户生命周期约束;JSON 继续保留完整证据供展示与审计。 + # 先落库删除旧快照,避免 SQLite/PostgreSQL 在同次 flush 中先插入后删除而触发唯一约束。 + db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete( + synchronize_session=False, + ) + db.session.flush() + db.session.expire(row, ['matches']) + row.matches = [ + ShippingCustomerShadowMatch( + customer_id=int(item['customer_id']), + match_rank=index, + score=float(item['score']), + standard_name_snapshot=str(item['standard_name']), + short_code_snapshot=str(item['short_code']), + reasons_json=list(item.get('reasons') or []), + ) + for index, item in enumerate(matches, start=1) + ] row.updated_at = datetime.utcnow() db.session.flush() return row @@ -168,6 +187,9 @@ def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidat row.candidate_matches_json = [] row.top_customer_id = None row.top_score = None + db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete( + synchronize_session=False, + ) row.updated_at = datetime.utcnow() db.session.flush() except Exception: @@ -186,6 +208,8 @@ def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: i 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') + if customer.status == 'merged': + raise ConflictError('Merged customer cannot be used as a new label', code='SHIPPING.CUSTOMER_MERGED_LOCKED') row.manual_customer_id = customer.id row.labeled_by_id = actor_id row.labeled_at = datetime.utcnow() diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index a40da0b7..1321da83 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -1,8 +1,8 @@ """ services/shipping_notice/decision_workflow.py -用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。 -依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow、task_line_store。 +用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。 +依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、task_line_store。 逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。 """ @@ -11,9 +11,9 @@ from __future__ import annotations from typing import Any from app import db +from app.models import ShippingTaskInventoryLink from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, - CP_MAP_INFER, CP_PARSE_OK, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, @@ -23,32 +23,12 @@ from app.services.shipping_notice.constants import ( RS_SHORTAGE_REVIEW, ) from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory -from app.services.shipping_notice.inventory_mapping import mapping_is_complete from app.services.shipping_notice.task_line_store import clear_task_order_lines -from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping -from app.services.shipping_notice.inventory_mapping_workflow import ( - awaiting_inventory_mapping_confirm, - inventory_mapping_checkpoint_response, - latest_inventory_column_meta, -) -from app.services.shipping_notice.inventory_file_store import ( - active_inventory_file_for_task, - linked_task_nos_for_inventory_file, - start_inventory_file_linked_tasks, -) -from app.services.shipping_notice.inventory_upload import ( - has_uploaded_task_inventory, - read_task_inventory_schema_preview, - resolve_task_inventory_upload_path, - task_inventory_upload_path, -) from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.inventory_source_gate import ( is_inventory_source_stable, adjudicate_and_apply_inventory_source, ensure_inventory_source_review_state, - task_needs_parse_review, - transition_task_to_inventory_source_review, ) from app.services.shipping_notice.i18n import resolve_lang, t from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool @@ -91,12 +71,26 @@ def _reset_inventory_state_for_forced_rpa(task) -> None: task.error_message = None +def _prepare_task_for_inventory_reupload(task) -> None: + """ + 解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。 + + 【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。 + 历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。 + """ + if task.id is not None: + for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all(): + link.is_active = False + _reset_inventory_state_for_forced_rpa(task) + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + + def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: """ 提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。 - 【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“更正映射”“关闭任务”等决策类指令时调用。 + 【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。 - 核心逻辑:先解析 decision,再按状态机规则分发到解析确认、映射确认、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。 + 核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。 Args: payload: 必须包含任务定位信息与 decision,可选 comment、lang 等上下文。 @@ -115,6 +109,37 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: lang = resolve_lang(payload) event_source = str(payload.get("event_source") or "").strip() or "decision_workflow" + # Published parsing profiles are the only production mapping contract. + # Reject legacy task-level mapping decisions instead of reopening a manual + # mapping path that could override the source's configured profile. + if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}: + return tool_response( + status="failed", + task_id=task.task_no, + message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。", + data=serialize_task_for_tool(task), + ) + + if decision == "reparse_inventory": + _prepare_task_for_inventory_reupload(task) + log_task_action_event( + task, + "inventory_reupload_requested", + action="reparse_inventory", + source=event_source, + comment=comment, + ) + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。", + data=serialize_task_for_tool(task), + checkpoint="upload_req", + human_options=["upload_inventory_file", "retry_rpa"], + stop_agent_turn=True, + ) + # [STEP 1] 先处理终止型决策。 # reject / close 会直接结束当前任务,不再继续进入库存或出货链路。 if decision == "reject": @@ -240,7 +265,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: human_options=resolve_task_ui_state(task).human_options, stop_agent_turn=True, ) - if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)): + if not task.inventory_lines_json: orchestrator_started = start_task_orchestrator(task.task_no) return tool_response( status="running" if orchestrator_started else "ok", @@ -289,10 +314,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: data=serialize_task_for_tool(task), ) - if awaiting_inventory_mapping_confirm(task): - lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() - return inventory_mapping_checkpoint_response(task, lang=lang or None) - if task.inventory_lines_json or task.process_status == "inventory_ready": orchestrator_started = start_task_orchestrator(task.task_no) return tool_response( @@ -310,7 +331,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 3] 处理重算型决策。 - # retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory + # retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路, # 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。 if decision == "retry_rpa": _reset_inventory_state_for_forced_rpa(task) @@ -350,186 +371,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: ) return match_result - if decision == "confirm_inventory_mapping": - if not awaiting_inventory_mapping_confirm(task): - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.mapping_not_needed", lang=lang), - data=serialize_task_for_tool(task), - ) - meta = latest_inventory_column_meta(task) or {} - inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {} - res_source = None - if isinstance(inv_mapping.get("reservation_id"), dict): - res_source = inv_mapping["reservation_id"].get("source_column") - if not str(res_source or "").strip(): - apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD) - db.session.commit() - lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() - warning = t("workflow.decision.mapping_missing_reservation_warning", lang=lang) - ui = resolve_task_ui_state(task) - return tool_response( - status="needs_human", - task=task, - message=warning, - data=serialize_task_for_tool(task), - checkpoint=ui.checkpoint, - human_options=ui.human_options, - next_required_action=t("workflow.decision.mapping_correction_next", lang=lang), - forbidden_next_tools=["match_inventory"], - stop_agent_turn=True, - ) - headers = meta.get("headers") if isinstance(meta.get("headers"), list) else [] - field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None - if headers and field_mapping and mapping_is_complete(field_mapping): - upsert_inventory_mapping( - task.customer_code, - preview={ - "headers": headers, - "header_row_index": meta.get("header_row_index") or 1, - }, - field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()}, - ) - apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED) - inv_file = active_inventory_file_for_task(task) - linked_task_nos = [task.task_no] - if inv_file: - inv_file.mapping_confirmed = True - log_task_event( - task, - "inventory_mapping_confirmed", - { - **{ - "comment": comment, - "confirmed_by_task_no": task.task_no, - "inventory_file_no": inv_file.inventory_file_no, - }, - **{ - "action": "confirm_inventory_mapping", - "source": event_source, - "target_type": "task", - "target_id": task.task_no, - "batch_no": task.batch.batch_no if task.batch else "", - "conversation_id": task.conversation_id or "", - }, - }, - ) - for link in inv_file.links or []: - linked_task = link.task - if not link.is_active or not linked_task: - continue - linked_task_nos.append(linked_task.task_no) - if awaiting_inventory_mapping_confirm(linked_task): - apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED) - log_task_event( - linked_task, - "inventory_mapping_confirmed", - { - **{ - "comment": comment, - "confirmed_by_task_no": task.task_no, - "inventory_file_no": inv_file.inventory_file_no, - }, - **{ - "action": "confirm_inventory_mapping", - "source": event_source, - "target_type": "task", - "target_id": linked_task.task_no, - "batch_no": linked_task.batch.batch_no if linked_task.batch else "", - "conversation_id": linked_task.conversation_id or "", - }, - }, - ) - else: - log_task_action_event( - task, - "inventory_mapping_confirmed", - action="confirm_inventory_mapping", - source=event_source, - comment=comment, - ) - db.session.commit() - orchestrator_started = ( - start_inventory_file_linked_tasks(inv_file) - if inv_file - else start_task_orchestrator(task.task_no) - ) - if inv_file: - linked_task_nos = linked_task_nos_for_inventory_file(inv_file) - return tool_response( - status="running" if orchestrator_started else "ok", - task=task, - message=t("workflow.decision.mapping_confirmed_running", lang=lang), - data={**serialize_task_for_tool(task), "linked_task_nos": linked_task_nos}, - ) - - if decision == "correct_inventory_mapping": - if not awaiting_inventory_mapping_confirm(task): - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.mapping_correction_invalid_state", lang=lang), - data=serialize_task_for_tool(task), - ) - task.inventory_lines_json = None - apply_task_transition(task, TaskTransition.CORRECT_MAPPING) - log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment}) - db.session.commit() - upload_path = resolve_task_inventory_upload_path(task.task_no) - if upload_path is not None: - try: - preview = read_task_inventory_schema_preview(task.task_no) - except OSError as exc: - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.decision.read_inventory_preview_failed", lang=lang).format(error=exc), - data=serialize_task_for_tool(task), - ) - else: - meta = latest_inventory_column_meta(task) or {} - preview = { - "headers": meta.get("headers") or [], - "sample_rows": [], - "suggested_mapping": meta.get("field_mapping") or {}, - "note": t("workflow.decision.mapping_preview_note", lang=lang), - } - return tool_response( - status="needs_human", - task=task, - message=t("workflow.decision.mapping_correction_needed", lang=lang), - data={**serialize_task_for_tool(task), "schema_preview": preview}, - checkpoint=CP_MAP_INFER, - next_required_action=t("workflow.decision.mapping_correction_next", lang=lang), - forbidden_next_tools=["match_inventory"], - stop_agent_turn=True, - ) - - if decision == "reparse_inventory": - task.inventory_lines_json = None - if task.process_status == "inventory_ready": - apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE) - else: - apply_task_transition(task, TaskTransition.REPARSE_INVENTORY) - for suffix in (".xlsx", ".csv"): - upload_path = task_inventory_upload_path(task.task_no, suffix=suffix) - if upload_path.is_file(): - try: - upload_path.unlink() - except OSError: - pass - log_task_event(task, "inventory_reparse_requested", {"comment": comment}) - db.session.commit() - return tool_response( - status="ok", - task_id=task.task_no, - message=t("workflow.decision.inventory_cleared", lang=lang), - data=serialize_task_for_tool(task), - next_required_action=t("workflow.decision.mapping_correction_next", lang=lang), - forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], - ) - # [STEP 4] 最后处理整单重新解析。 # 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。 if decision == "reparse": diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 4b4a221d..992fe770 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -10,9 +10,10 @@ services/shipping_notice/dify_inputs.py from __future__ import annotations +from datetime import datetime from typing import Any -from app.models import ShippingBatch, ShippingTask +from app.models import ShippingBatch, ShippingTask, ShippingTemporaryInventorySession from app.services.agent_runtime_context.builder import serialize_for_dify from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT from app.services.shipping_notice.runtime_context import build_shipping_runtime_context @@ -38,6 +39,35 @@ def _task_by_task_no(task_id: str) -> ShippingTask | None: return ShippingTask.query.filter_by(task_no=normalized).first() +def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None: + """ + 恢复当前聊天中仍待用户处理的临时库存会话锚点。 + + Args: + conversation_id: HXOPS 本地聊天会话 ID。 + + Returns: + 最新未过期待处理会话号;没有符合条件的会话时返回 None。 + """ + normalized = str(conversation_id or '').strip() + if not normalized: + return None + item = ShippingTemporaryInventorySession.query.filter( + ShippingTemporaryInventorySession.conversation_id == normalized, + ShippingTemporaryInventorySession.status.in_([ + 'created', + 'awaiting_profile_confirmation', + 'awaiting_mapping_suggestion', + 'awaiting_mapping_confirmation', + ]), + ShippingTemporaryInventorySession.expires_at > datetime.utcnow(), + ).order_by( + ShippingTemporaryInventorySession.updated_at.desc(), + ShippingTemporaryInventorySession.id.desc(), + ).first() + return str(item.session_no or '').strip().upper() or None if item else None + + def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None: """ 解析当前显式焦点任务行。 @@ -70,6 +100,8 @@ def build_dify_chat_inputs( locale: str | None = None, intake_nos: list[str] | None = None, capability: str | None = None, + temporary_inventory_asset_no: str | None = None, + temporary_inventory_session_no: str | None = None, ) -> dict[str, Any]: """ 构建发货通知 Dify Chatflow inputs。 @@ -83,6 +115,15 @@ def build_dify_chat_inputs( explicit_task = str(task_id or "").strip().upper() explicit_batch = str(batch_no or "").strip().upper() + explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper() + resolved_temporary_session = ( + explicit_temporary_session + or ( + _latest_pending_temporary_inventory_session(conv_id) + if trigger_source != 'backend_orchestrator' + else None + ) + ) batch = _latest_batch_for_conversation(conv_id) explicit_task_row = _task_by_task_no(explicit_task) @@ -113,10 +154,12 @@ def build_dify_chat_inputs( run_purpose=( "parse_notice" if trigger_source == "backend_orchestrator" - else ("order_extraction" if intake_nos else "chat_turn") + else ("temporary_inventory" if temporary_inventory_asset_no else ("order_extraction" if intake_nos else "chat_turn")) ), intake_nos=intake_nos, - capability=capability, + capability=capability or ("temporary_inventory" if temporary_inventory_asset_no else None), + temporary_inventory_asset_no=temporary_inventory_asset_no, + temporary_inventory_session_no=resolved_temporary_session, ) if not runtime_context: return {} diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index 4ec55aa9..3c56fd27 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -320,6 +320,11 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]: summary = cand.structured_result_json.get('business_summary') structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {} extraction = structured.get('extraction') if isinstance(structured.get('extraction'), dict) else {} + customer_matches = ( + extraction.get('customer_matches') + if isinstance(extraction.get('customer_matches'), list) + else [] + ) adjudication = ( extraction.get('field_adjudication') if isinstance(extraction.get('field_adjudication'), dict) @@ -354,6 +359,7 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]: 'observation_history': list(adjudication.get('observation_history') or []), 'conflicts': list(adjudication.get('conflicts') or []), } if adjudication else None, + 'customer_matches': list(customer_matches), 'duplicate': { 'status': status, 'blocking': blocking, diff --git a/backend/app/services/shipping_notice/excel_template.py b/backend/app/services/shipping_notice/excel_template.py new file mode 100644 index 00000000..3af76a20 --- /dev/null +++ b/backend/app/services/shipping_notice/excel_template.py @@ -0,0 +1,358 @@ +""" +services/shipping_notice/excel_template.py + +用途:管理发货 Excel 模板草稿、映射定义、发布版本与受管模板文件。 +依赖:openpyxl、ShippingExcelTemplate、订单字段目录、Flask 配置与统一业务异常。 +逻辑:上传 xlsx 创建草稿;草稿可改定义;发布时验证工作表、字段引用和映射目标并计算不可变校验和。 +""" + +from __future__ import annotations + +import hashlib +import json +import re +import uuid +from datetime import datetime +from io import BytesIO +from typing import Any + +from flask import current_app +from openpyxl import load_workbook +from openpyxl.utils import get_column_letter +from werkzeug.datastructures import FileStorage + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingExcelTemplate, + ShippingExportArtifact, + ShippingInventoryField, + ShippingInventorySource, + ShippingOrderField, +) +from app.services.file_assets.storage import file_asset_storage + +ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'constant'} +ALLOWED_ROW_MODES = {'header', 'line'} +ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'} +ALLOWED_SYSTEM_FACTS = {'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date'} + + +def _storage_key(template_code: str, version: int) -> str: + """构造长期私有模板对象键,与临时上传资产生命周期隔离。""" + return f'shipping-excel-templates/{template_code}/v{version}/{uuid.uuid4().hex}.xlsx' + + +def _checksum_json(value: Any) -> str: + payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(payload.encode('utf-8')).hexdigest() + + +def _payload(item: ShippingExcelTemplate) -> dict[str, Any]: + """序列化模板元数据,绝不向管理端暴露服务器存储路径。""" + return { + 'id': item.id, 'template_code': item.template_code, 'display_name': item.display_name, + 'version': item.version, 'status': item.status, 'original_filename': item.original_filename, + 'file_checksum': item.file_checksum, 'definition': item.definition_json or {}, + 'definition_checksum': item.definition_checksum, + 'created_at': item.created_at.isoformat() if item.created_at else None, + 'published_at': item.published_at.isoformat() if item.published_at else None, + } + + +def list_templates() -> list[dict[str, Any]]: + """按编码和版本列出模板,供库存源绑定及草稿编辑。""" + rows = ShippingExcelTemplate.query.order_by( + ShippingExcelTemplate.template_code, ShippingExcelTemplate.version.desc(), + ).all() + return [_payload(item) for item in rows] + + +def _next_version(template_code: str) -> int: + latest = ShippingExcelTemplate.query.filter_by(template_code=template_code).order_by( + ShippingExcelTemplate.version.desc(), + ).first() + return int(latest.version) + 1 if latest else 1 + + +def create_draft(upload: FileStorage | None, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 上传模板文件并创建新草稿版本。 + + Args: + upload: 必须为非空 xlsx 文件;宏工作簿和 CSV 不接受。 + data: template_code、display_name 与 JSON definition。 + actor_id: 当前管理员 ID。 + """ + code = str(data.get('template_code') or '').strip().upper() + name = str(data.get('display_name') or '').strip() + filename = str(getattr(upload, 'filename', '') or '').strip() + if not code or not name or upload is None or not filename.lower().endswith('.xlsx'): + raise ValidationError('template_code, display_name and xlsx file are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID') + if not re.fullmatch(r'[A-Z0-9_-]{2,64}', code): + raise ValidationError('template_code format is invalid', code='SHIPPING.EXCEL_TEMPLATE_INVALID') + if ShippingExcelTemplate.query.filter_by(template_code=code, status='draft').count(): + raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS') + raw = upload.read() + if not raw: + raise ValidationError('Template file is empty', code='SHIPPING.EXCEL_TEMPLATE_INVALID') + max_mb = max(int(current_app.config.get('SHIPPING_EXCEL_TEMPLATE_MAX_SIZE_MB') or 20), 1) + if len(raw) > max_mb * 1024 * 1024: + raise ValidationError('Template file exceeds size limit', code='SHIPPING.EXCEL_TEMPLATE_INVALID') + try: + workbook = load_workbook(BytesIO(raw), read_only=True) + workbook.close() + except Exception as exc: + raise ValidationError('Template file is not a valid xlsx workbook', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc + definition = data.get('definition') if isinstance(data.get('definition'), dict) else {} + version = _next_version(code) + storage_key = _storage_key(code, version) + file_asset_storage.upload_bytes( + storage_key=storage_key, data=raw, + content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + item = ShippingExcelTemplate( + template_code=code, display_name=name, version=version, status='draft', + storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, + original_filename=filename[:255], + file_checksum=hashlib.sha256(raw).hexdigest(), definition_json=definition, + created_by=actor_id, + ) + try: + db.session.add(item) + db.session.commit() + except Exception: + db.session.rollback() + try: + file_asset_storage.delete_object(storage_key) + except Exception: + pass + raise + return _payload(item) + + +def update_draft(template_id: int, data: dict[str, Any]) -> dict[str, Any]: + """更新草稿显示名称和映射定义;发布版本禁止原地修改。""" + item = db.session.get(ShippingExcelTemplate, template_id) + if item is None: + raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') + if item.status != 'draft': + raise ConflictError('Published template is immutable', code='SHIPPING.EXCEL_TEMPLATE_IMMUTABLE') + name = str(data.get('display_name') or '').strip() + definition = data.get('definition') + if not name or not isinstance(definition, dict): + raise ValidationError('display_name and definition are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID') + item.display_name = name + item.definition_json = definition + db.session.commit() + return _payload(item) + + +def _workbook_layout(raw: bytes, definition: dict[str, Any]) -> dict[str, list[dict[str, Any]]]: + """读取受管模板的工作表和首行栏位,供编辑器重新加载已保存文件的结构。""" + workbook = load_workbook(BytesIO(raw), read_only=True, data_only=False) + try: + header_rows: dict[str, int] = {} + for mapping in definition.get('mappings', []): + if not isinstance(mapping, dict): + continue + sheet_name = str(mapping.get('sheet') or '') + start_row = int(mapping.get('start_row') or 1) + candidate_row = max(start_row - 1, 1) + header_rows[sheet_name] = min(header_rows.get(sheet_name, candidate_row), candidate_row) + layout: dict[str, list[dict[str, Any]]] = {} + for sheet_name in workbook.sheetnames: + sheet = workbook[sheet_name] + if sheet.max_column is None: + sheet.calculate_dimension(force=True) + header_row = header_rows.get(sheet_name, 1) + max_column = int(sheet.max_column or 0) + columns: list[dict[str, Any]] = [] + for column_index in range(1, max_column + 1): + value = sheet.cell(header_row, column_index).value + column = get_column_letter(column_index) + columns.append({'index': column_index, 'label': f'{column} - {value}' if value else column}) + layout[sheet_name] = columns + return layout + finally: + workbook.close() + + +def get_layout(template_id: int) -> dict[str, Any]: + """返回已保存模板的工作表和目标列信息,不要求用户重新上传文件。""" + item = db.session.get(ShippingExcelTemplate, template_id) + if item is None: + raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') + raw = file_asset_storage.get_bytes(item.storage_key) + if hashlib.sha256(raw).hexdigest() != item.file_checksum: + raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') + return {'template_id': item.id, 'sheets': _workbook_layout(raw, item.definition_json or {})} + + +def create_draft_from_existing(template_id: int, *, actor_id: int | None) -> dict[str, Any]: + """复制已保存模板文件和映射定义,创建可编辑的新草稿版本。""" + source = db.session.get(ShippingExcelTemplate, template_id) + if source is None: + raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') + if source.status not in {'draft', 'published', 'retired'}: + raise ConflictError('Template status cannot create a new version', code='SHIPPING.EXCEL_TEMPLATE_VERSION_INVALID') + if ShippingExcelTemplate.query.filter_by(template_code=source.template_code, status='draft').count(): + raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS') + raw = file_asset_storage.get_bytes(source.storage_key) + if hashlib.sha256(raw).hexdigest() != source.file_checksum: + raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') + version = _next_version(source.template_code) + storage_key = _storage_key(source.template_code, version) + file_asset_storage.upload_bytes( + storage_key=storage_key, data=raw, + content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + item = ShippingExcelTemplate( + template_code=source.template_code, display_name=source.display_name, version=version, status='draft', + storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, + original_filename=source.original_filename, file_checksum=hashlib.sha256(raw).hexdigest(), + definition_json=json.loads(json.dumps(source.definition_json or {}, ensure_ascii=False)), created_by=actor_id, + ) + try: + db.session.add(item) + db.session.commit() + except Exception: + db.session.rollback() + try: + file_asset_storage.delete_object(storage_key) + except Exception: + pass + raise + return _payload(item) + + +def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]: + """验证模板定义、实际工作表和稳定字段引用,返回规范化定义。""" + definition = item.definition_json if isinstance(item.definition_json, dict) else {} + mappings = definition.get('mappings') + filename_pattern = str(definition.get('filename_pattern') or '').strip() + if not isinstance(mappings, list) or not mappings or not filename_pattern: + raise ValidationError('Template mappings and filename_pattern are required', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') + try: + rendered_name = filename_pattern.format( + task_no='TASK', business_no='BUSINESS', source_code='SOURCE', ts='20260101000000', date='20260101', + customer_short_code='CUSTOMER', business_date='260602', sequence='01', + ) + except (KeyError, ValueError) as exc: + raise ValidationError('Template filename_pattern is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc + if not rendered_name.strip(): + raise ValidationError('Template filename_pattern is empty', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') + raw = file_asset_storage.get_bytes(item.storage_key) + if hashlib.sha256(raw).hexdigest() != item.file_checksum: + raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID') + wb = load_workbook(BytesIO(raw), read_only=True) + sheet_names = set(wb.sheetnames) + wb.close() + published_field_ids: set[str] = set() + if any(isinstance(mapping, dict) and mapping.get('source_kind') == 'order_field' for mapping in mappings): + from app.services.shipping_notice.order_schema import service as order_schema_service + + published_field_ids = { + str(field.get('field_id') or '') + for field in order_schema_service.get_published_contract().get('fields', []) + } + normalized: list[dict[str, Any]] = [] + seen_targets: set[tuple[str, str, int]] = set() + for index, raw in enumerate(mappings): + if not isinstance(raw, dict): + raise ValidationError('Template mapping must be an object', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') + sheet = str(raw.get('sheet') or '').strip() + row_mode = str(raw.get('row_mode') or '').strip().lower() + source_kind = str(raw.get('source_kind') or '').strip().lower() + source_key = str(raw.get('source_key') or '').strip() + formatter = str(raw.get('formatter') or 'text').strip().lower() + try: + start_row = int(raw.get('start_row')) + target_column = int(raw.get('target_column')) + except (TypeError, ValueError) as exc: + raise ValidationError('Template target row and column must be integers', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc + if sheet not in sheet_names or row_mode not in ALLOWED_ROW_MODES or source_kind not in ALLOWED_SOURCE_KINDS: + raise ValidationError('Template mapping metadata is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID', details={'index': index}) + if start_row < 1 or target_column < 1 or formatter not in ALLOWED_FORMATTERS: + raise ValidationError('Template mapping target or formatter is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') + if source_kind == 'order_field': + field = db.session.get(ShippingOrderField, source_key) + allowed_scopes = {'header'} if row_mode == 'header' else {'header', 'line'} + if field is None or field.status != 'active' or field.scope not in allowed_scopes or field.id not in published_field_ids: + raise ValidationError('Order field is invalid for mapping scope', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') + elif source_kind == 'inventory_field': + try: + inventory_field_id = int(source_key) + except (TypeError, ValueError) as exc: + raise ValidationError('Inventory field is invalid', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') from exc + inventory_field = db.session.get(ShippingInventoryField, inventory_field_id) + if inventory_field is None or inventory_field.status != 'active': + raise ValidationError('Inventory field is unavailable', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') + source_key = str(inventory_field.id) + elif source_kind == 'system_fact' and source_key not in ALLOWED_SYSTEM_FACTS: + raise ValidationError('System fact is not allowed', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') + elif source_kind != 'constant' and not source_key: + raise ValidationError('source_key is required', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') + target = (sheet, row_mode, target_column) + if target in seen_targets: + raise ValidationError('Duplicate template target column', code='SHIPPING.EXCEL_TEMPLATE_TARGET_DUPLICATE') + seen_targets.add(target) + normalized.append({ + 'sheet': sheet, 'row_mode': row_mode, 'start_row': start_row, + 'target_column': target_column, 'source_kind': source_kind, + 'source_key': source_key, 'formatter': formatter, + }) + return {'filename_pattern': filename_pattern, 'mappings': normalized} + + +def publish(template_id: int, *, actor_id: int | None) -> dict[str, Any]: + """验证并发布模板版本;发布后文件和定义均不可变。""" + item = db.session.get(ShippingExcelTemplate, template_id) + if item is None: + raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') + if item.status != 'draft': + raise ConflictError('Only draft template can be published', code='SHIPPING.EXCEL_TEMPLATE_PUBLISH_INVALID') + definition = _validate_definition(item) + item.definition_json = definition + item.definition_checksum = _checksum_json(definition) + item.status = 'published' + item.published_by = actor_id + item.published_at = datetime.utcnow() + db.session.commit() + return _payload(item) + + +def retire(template_id: int) -> dict[str, Any]: + """退役不再供新库存源绑定的模板;现有产物引用保持不变。""" + item = db.session.get(ShippingExcelTemplate, template_id) + if item is None: + raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') + if item.status != 'published': + raise ConflictError('Only published template can be retired', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_INVALID') + if ShippingInventorySource.query.filter_by(excel_template_id=item.id).count(): + raise ConflictError('Rebind inventory sources first', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED') + item.status = 'retired' + db.session.commit() + return _payload(item) + + +def delete_draft(template_id: int) -> None: + """删除未发布草稿及其受管文件;已有 Artifact 的模板永远不可删除。""" + item = db.session.get(ShippingExcelTemplate, template_id) + if item is None: + raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') + if item.status != 'draft' or ShippingExportArtifact.query.filter_by(template_id=item.id).count(): + raise ConflictError('Only unused draft can be deleted', code='SHIPPING.EXCEL_TEMPLATE_DELETE_BLOCKED') + storage_key = item.storage_key + raw = file_asset_storage.get_bytes(storage_key) + file_asset_storage.delete_object(storage_key) + try: + db.session.delete(item) + db.session.commit() + except Exception: + db.session.rollback() + file_asset_storage.upload_bytes( + storage_key=storage_key, data=raw, + content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + raise diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 3b656732..8bf141dd 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -1,311 +1,383 @@ """ services/shipping_notice/export.py -用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。 -依赖:openpyxl、app.models.ShippingTask、path_utils、task_line_store、Flask current_app 配置。 -逻辑:由 fulfillment_workflow.generate_excel 调用本文件;订单行经 read_task_order_lines 读取。 +用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。 +依赖:ShippingExcelTemplate/ShippingExportArtifact、动态订单 FieldValue、库存快照与 openpyxl。 +逻辑:锁定 Source、模板、订单 Schema/Extraction、库存解析 Profile 和库存快照,按白名单映射写入模板。 """ from __future__ import annotations -from datetime import datetime +import hashlib +import json +import uuid +from datetime import date, datetime +from decimal import Decimal from pathlib import Path -from shutil import copy2 from typing import Any +from zoneinfo import ZoneInfo from flask import current_app -from openpyxl import Workbook, load_workbook +from openpyxl import load_workbook +from sqlalchemy import update -from app.models import ShippingTask -from app.path_utils import backend_dir, resolve_backend_relative_path -from app.services.shipping_notice.task_line_store import read_task_order_lines - -DEFAULT_HEADERS = [ - "客户名称", - "客户代码", - "收货地址", - "要求交期", - "料号", - "发货数量", - "单位", - "备注", -] - -HEADER_SHEET = "PVMI Pull Request Header" -DETAIL_SHEET = "PVMI Pull Request Detail" -DATA_START_ROW = 4 +from app import db +from app.models import ( + ShippingExcelTemplate, + ShippingExportArtifact, + ShippingInventoryField, + ShippingInventorySource, + ShippingOrderExtraction, + ShippingOrderFieldValue, + ShippingTask, +) +from app.path_utils import resolve_backend_relative_path +from app.services.file_assets.storage import file_asset_storage def _storage_root() -> Path: - """发货通知文件存储根目录(exports/notice_uploads/inventory_uploads 的父路径)。""" - root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip() - if root: - return Path(resolve_backend_relative_path(root)) - return Path(current_app.instance_path) / "shipping_notice" - - -def _default_template_path() -> Path | None: - configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip() + """返回发货通知文件根目录。""" + configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip() if configured: - path = Path(resolve_backend_relative_path(configured)) - if path.is_file(): - return path - bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx" - return bundled if bundled.is_file() else None + return Path(resolve_backend_relative_path(configured)) + return Path(current_app.instance_path) / 'shipping_notice' -def _is_pvmi_workbook(wb) -> bool: - return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames - - -def _format_delivery_date(value: Any) -> str: - text = str(value or "").strip() - if not text: - return "" - for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"): - try: - parsed = datetime.strptime(text[:10], fmt) - return parsed.strftime("%m/%d/%Y") - except ValueError: - continue - if len(text) >= 10 and text[4] == "-" and text[7] == "-": - try: - parsed = datetime.strptime(text[:10], "%Y-%m-%d") - return parsed.strftime("%m/%d/%Y") - except ValueError: - pass - return text - - -def _delivery_date_for_task(task: ShippingTask) -> str: - if task.required_date: - formatted = _format_delivery_date(task.required_date) - if formatted: - return formatted - for line in read_task_order_lines(task): - formatted = _format_delivery_date(line.get("required_date")) - if formatted: - return formatted - return "" - - -def _resolve_odm_id(task: ShippingTask) -> str: - """ - 按订单内部料号与 Reservation 定位当前库存投影中的 ODM ID。 - - 核心逻辑:订单与库存统一按 part_number + reservation_id 配对。 - Args: - task: 已关联库存快照的发货任务。 - Returns: - 首个匹配库存行的 ODM ID;未命中时回退库存中的首个非空值。 - """ - notice_lines = read_task_order_lines(task) - inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)] - if not inventory_lines: - return "" - - inv_by_key: dict[tuple[str, str], dict[str, Any]] = {} - for row in inventory_lines: - key = ( - str(row.get("part_number") or "").strip(), - str(row.get("reservation_id") or "").strip(), - ) - inv_by_key[key] = row - - for line in notice_lines: - key = ( - str(line.get("part_number") or "").strip(), - str(line.get("reservation_id") or "").strip(), - ) - matched = inv_by_key.get(key) - if matched: - odm_id = str(matched.get("odm_id") or "").strip() - if odm_id: - return odm_id - - for row in inventory_lines: - odm_id = str(row.get("odm_id") or "").strip() - if odm_id: - return odm_id - return "" - - -def _shipment_warehouse_id(task: ShippingTask) -> str: - """ - 解析发货 Excel Header 的 Warehouse ID。 - 核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。 - """ - try: - from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link - - snapshot = serialize_inventory_snapshot_link(task) - except Exception: - snapshot = None - if isinstance(snapshot, dict): - value = str(snapshot.get("warehouse_id") or "").strip() - if value: +def _typed_value(item: ShippingOrderFieldValue) -> Any: + """从类型化投影读取唯一业务值,禁止回退旧任务固定列。""" + for value in ( + item.value_text, item.value_decimal, item.value_integer, + item.value_date, item.value_boolean, item.value_json, + ): + if value is not None: return value - return "AWSDU" + return None -def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str: - for value in (line.get("po_number"), task.po_number): - text = str(value or "").strip() - if text: - return text - return "" +def _order_values(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """将稳定 field_id 投影为 Header 字典及按订单行 position 排序的字典列表。""" + header: dict[str, Any] = {} + line_positions = {line.id: line.position for line in extraction.lines} + lines: dict[int, dict[str, Any]] = {position: {} for position in line_positions.values()} + for item in extraction.values: + value = _typed_value(item) + if item.line_id is None: + header[item.field_id] = value + elif item.line_id in line_positions: + lines[line_positions[item.line_id]][item.field_id] = value + return header, [lines[position] for position in sorted(lines)] -def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str: - for value in (line.get("currency"), getattr(task, "currency", None)): - text = str(value or "").strip().upper() - if text: - return text - return "" +def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """读取任务当前已接受订单解析,并按稳定字段 ID 返回 Header 与明细值。""" + extraction = ( + db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + if task.current_order_extraction_id is not None else None + ) + if extraction is None or extraction.status != 'accepted': + raise ValueError('任务没有可用于库存匹配的订单解析版本') + return _order_values(extraction) -def _line_part_number(line: dict[str, Any]) -> str: - """返回货代明细使用的内部料号。""" - return str(line.get("part_number") or "").strip() +def _system_fact(task: ShippingTask, key: str) -> Any: + """读取受控任务事实,模板不能通过任意属性路径访问 ORM。""" + values = { + 'task_no': task.task_no, + 'business_no': task.shipping_case.business_no if task.shipping_case else None, + 'warehouse_id': task.inventory_warehouse_id, + 'inventory_source_code': task.inventory_source_code, + 'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(), + } + return values.get(key) -def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None: - if ws.max_row < from_row: - return - for row_idx in range(from_row, ws.max_row + 1): - for col_idx in range(1, ws.max_column + 1): - ws.cell(row_idx, col_idx).value = None +def _format_value(value: Any, formatter: str) -> Any: + """应用发布契约允许的确定性格式化器。""" + if value is None: + return '' + if formatter == 'upper': + return str(value).upper() + if formatter == 'lower': + return str(value).lower() + if formatter == 'date_mmddyyyy': + if isinstance(value, (date, datetime)): + return value.strftime('%m/%d/%Y') + text = str(value).strip() + for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d', '%m/%d/%Y'): + try: + return datetime.strptime(text[:10], pattern).strftime('%m/%d/%Y') + except ValueError: + continue + return text + if formatter == 'integer': + return int(Decimal(str(value))) + if formatter == 'decimal': + return float(Decimal(str(value))) + return str(value) if isinstance(value, (Decimal, date, datetime)) else value -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] - - _clear_sheet_data_rows(detail_ws) - _clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW) - - header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task) - if header_ws.cell(DATA_START_ROW, 2).value in (None, ""): - header_ws.cell(DATA_START_ROW, 2).value = "n" - if header_ws.cell(DATA_START_ROW, 3).value in (None, ""): - header_ws.cell(DATA_START_ROW, 3).value = "WEL" - if header_ws.cell(DATA_START_ROW, 4).value in (None, ""): - header_ws.cell(DATA_START_ROW, 4).value = "normal" - - 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) - 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 = read_task_order_lines(task) - if not notice_lines: - notice_lines = [{}] - - for index, line in enumerate(notice_lines, start=1): - row_idx = DATA_START_ROW + index - 1 - line_no = str(line.get("line_no") or index).strip() - qty = line.get("qty") - amount = line.get("amount") - - 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_part_number(line) - detail_ws.cell(row_idx, 5).value = qty if qty is not None else "" - detail_ws.cell(row_idx, 7).value = _line_po_number(task, line) - detail_ws.cell(row_idx, 10).value = amount if amount is not None else "" - detail_ws.cell(row_idx, 11).value = _line_currency(task, line) - - wb.save(path) +def _mapping_value( + mapping: dict[str, Any], *, task: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any], + header_values: dict[str, Any] | None = None, +) -> Any: + """按映射来源类型读取值;未知来源已在模板发布时被拒绝。""" + kind = mapping['source_kind'] + key = mapping['source_key'] + if kind == 'order_field': + value = order_values.get(key) + if value is None and mapping.get('row_mode') == 'line' and header_values is not None: + value = header_values.get(key) + elif kind == 'inventory_field': + value = inventory_values.get(str(key)) + elif kind == 'system_fact': + value = _system_fact(task, key) + else: + value = key + return _format_value(value, mapping['formatter']) -def _row_values(task: ShippingTask, line: dict | None) -> list: - line = line or {} - return [ - task.customer_name or "", - task.customer_code or "", - task.ship_to or "", - task.required_date or "", - line.get("part_number") or "", - line.get("qty") or "", - line.get("uom") or "EA", - line.get("remark") or "", - ] +def _match_text(value: Any) -> str: + """规范化订单与库存匹配键;仅做确定性文本比较,不进行模糊推断。""" + if value is None: + return '' + if isinstance(value, Decimal): + return format(value.normalize(), 'f') + return str(value).strip().casefold() -def _fill_legacy_template(task: ShippingTask, path: Path) -> None: - """填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。""" - wb = load_workbook(filename=str(path)) - ws = wb.active - lines = read_task_order_lines(task) or [None] - if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)): - ws.append(DEFAULT_HEADERS) - for line in lines: - ws.append(_row_values(task, line)) - wb.save(path) +def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]: + """返回模板直接引用的库存字段 ID,用于多命中一致性验证。""" + raw_ids = { + str(item['source_key']) for item in mappings + if item.get('row_mode') == row_mode and item.get('source_kind') == 'inventory_field' + } + ids = {int(item) for item in raw_ids if item.isdigit()} + if len(ids) != len(raw_ids): + raise ValueError('发货模板引用的库存字段无效') + rows = ShippingInventoryField.query.filter( + ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active', + ).all() if ids else [] + if len(rows) != len(ids): + raise ValueError('发货模板引用的库存字段已不存在') + return {str(item.id) for item in rows} -def _fill_blank_workbook(task: ShippingTask, path: Path) -> None: - """生成无模板工作簿;技术任务号继续保留在导出文件名与系统记录中。""" - wb = Workbook() - ws = wb.active - ws.title = "Shipment" - ws.append(DEFAULT_HEADERS) - lines = read_task_order_lines(task) or [None] - for line in lines: - ws.append(_row_values(task, line)) - wb.save(path) +def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]: + """多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。""" + if not rows: + return {} + resolved = dict(rows[0]) + for field in required_fields: + values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))} + if len(values) > 1: + raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致') + if values: + resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field))) + return resolved -def _sanitize_filename(name: str) -> str: - cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."}) - return cleaned or "shipment.xlsx" +def _match_inventory_lines( + order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], + match_keys: list[dict[str, str]], required_fields: set[str], +) -> list[dict[str, Any]]: + """按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。""" + if not order_lines: + return [] + if not match_keys: + raise ValueError('库存解析模板缺少订单与库存匹配键') + from app.models import ShippingInventoryField + + ids = { + int(item.get('inventory_field_id')) + for item in match_keys + if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit() + } + catalog = { + str(item.id): str(item.id) + for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all() + } + normalized_keys: list[dict[str, str]] = [] + for item in match_keys: + if not isinstance(item, dict): + raise ValueError('库存解析模板匹配键无效') + field_id = str(item.get('inventory_field_id') or '').strip() + inventory_field = catalog.get(field_id) + if not inventory_field: + raise ValueError('库存解析模板引用的库存字段已不可用') + normalized_keys.append({ + 'order_field_id': str(item.get('order_field_id') or ''), + 'inventory_field': inventory_field, + }) + result: list[dict[str, Any]] = [] + for position, order_line in enumerate(order_lines, start=1): + expected = [ + (_match_text(order_line.get(item['order_field_id'])), item['inventory_field']) + for item in normalized_keys + ] + if any(not value for value, _field in expected): + raise ValueError(f'第 {position} 条订单行缺少库存匹配键值') + matched = [ + row for row in inventory_lines + if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected) + ] + if not matched: + raise ValueError(f'第 {position} 条订单行没有匹配的库存记录') + result.append(_collapse_inventory_matches(matched, required_fields)) + return result -def _export_filename(task: ShippingTask, ts: str) -> str: - pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip() - if not pattern: - pattern = "shipment_{task_no}_{ts}.xlsx" +def _header_inventory_values( + matched_lines: list[dict[str, Any]], required_fields: set[str], +) -> dict[str, Any]: + """Header 库存字段必须在所有订单行匹配结果中一致,否则不能生成单一 Header。""" + return _collapse_inventory_matches(matched_lines, required_fields) + + +def _safe_filename(name: str) -> str: + """清理配置化文件名,防止路径穿越并强制 xlsx 扩展名。""" + cleaned = ''.join(ch for ch in name if ch.isalnum() or ch in {'-', '_', '.'}).strip('.') + cleaned = cleaned or 'shipment.xlsx' + return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx' + + +def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str: + """按发布规则生成下载名,业务单变量始终取已锁定的客户与编号快照。""" + pattern = str((template.definition_json or {}).get('filename_pattern') or '') + now = datetime.utcnow().strftime('%Y%m%d%H%M%S') + shipping_case = task.shipping_case + values = { + 'task_no': task.task_no, + 'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no, + 'source_code': task.inventory_source_code or '', + 'ts': now, + 'date': now[:8], + 'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '', + 'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '', + 'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '', + } try: - name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8]) - except Exception: - name = f"shipment_{task.task_no}_{ts}.xlsx" - if not str(name).lower().endswith(".xlsx"): - name = f"{name}.xlsx" - return _sanitize_filename(str(name)) + return _safe_filename(pattern.format(**values)) + except (KeyError, ValueError) as exc: + raise ValueError('发货 Excel 文件名规则无效') from exc -def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]: +def _input_checksum( + task: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate, + extraction: ShippingOrderExtraction, header: dict[str, Any], lines: list[dict[str, Any]], +) -> str: + """计算完整生成输入指纹,供审计和重复生成差异判断。""" + payload = { + 'task_id': task.id, 'source_id': source.id, 'template_id': template.id, + 'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum, + 'schema_version_id': extraction.schema_version_id, 'extraction_id': extraction.id, + 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id, + 'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [], + } + raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(raw.encode('utf-8')).hexdigest() + + +def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExportArtifact]: """ - 基于任务数据生成货代发货 Excel 并写入 exports 目录。 - 【AI 触发时机】:由 generate_excel Tool 调用;Agent 禁止直接操作文件系统。 - - 核心逻辑:复制 PVMI/legacy 模板 → 填充 Header/Detail 或 legacy 行 → 返回 (绝对路径, 文件名)。 + 按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。 + 【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。 Returns: - tuple[str, str]: (export_file_path, export_file_name)。 + (绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。 + + Raises: + ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。 """ - root = _storage_root() / "exports" - root.mkdir(parents=True, exist_ok=True) + source_code = str(task.inventory_source_code or '').strip().upper() + source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + if source is None: + raise ValueError('库存源不存在或已停用,不能生成发货 Excel') + # Fixed Sources receive this value from configuration; dynamic Sources receive it + # only after Reservation ID + Part Number resolves a unique inventory Warehouse. + if not str(task.inventory_warehouse_id or '').strip(): + raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel') + template = source.excel_template + if template is None or template.status != 'published': + raise ValueError('库存源未绑定已发布的发货 Excel 模板') + if source.parsing_profile is None or source.parsing_profile.status != 'published': + raise ValueError('库存源未绑定已发布的库存解析模板') + extraction = ( + db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + if task.current_order_extraction_id is not None else None + ) + if extraction is None or extraction.status != 'accepted': + raise ValueError('任务没有可用于导出的订单解析版本') + header_values, line_values = _order_values(extraction) + inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)] + definition = template.definition_json or {} + mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] + if not mappings: + raise ValueError('发货 Excel 模板没有已发布的字段映射') + profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {} + match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else [] + line_inventory_fields = _inventory_fields_by_mode(mappings, 'line') + header_inventory_fields = _inventory_fields_by_mode(mappings, 'header') + matched_inventory_lines = _match_inventory_lines( + line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields, + ) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values] + header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields) - ts = datetime.utcnow().strftime("%Y%m%d%H%M%S") - filename = _export_filename(task, ts) - path = root / filename - - template = _default_template_path() - if template: - copy2(template, path) - wb = load_workbook(filename=str(path), read_only=True) + filename = _filename(task, template) + artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}' + directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no + directory.mkdir(parents=True, exist_ok=True) + path = directory / f'{artifact_no}_{filename}' + template_bytes = file_asset_storage.get_bytes(template.storage_key) + if hashlib.sha256(template_bytes).hexdigest() != template.file_checksum: + raise ValueError('发货 Excel 模板文件缺失或校验失败') + try: + path.write_bytes(template_bytes) + wb = load_workbook(path) try: - is_pvmi = _is_pvmi_workbook(wb) + for mapping in mappings: + ws = wb[mapping['sheet']] + start_row = int(mapping['start_row']) + column = int(mapping['target_column']) + if mapping['row_mode'] == 'header': + ws.cell(start_row, column).value = _mapping_value( + mapping, task=task, order_values=header_values, inventory_values=header_inventory, + ) + continue + row_count = max(len(line_values), 1) + for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1): + ws.cell(row_index, column).value = None + for index in range(row_count): + order_line = line_values[index] if index < len(line_values) else {} + inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {} + ws.cell(start_row + index, column).value = _mapping_value( + mapping, task=task, order_values=order_line, inventory_values=inventory_line, + header_values=header_values, + ) + wb.save(path) finally: wb.close() - if is_pvmi: - _fill_pvmi_template(task, path) - else: - _fill_legacy_template(task, path) - else: - _fill_blank_workbook(task, path) - return str(path), filename + content = path.read_bytes() + db.session.execute( + update(ShippingExportArtifact) + .where( + ShippingExportArtifact.task_id == task.id, + ShippingExportArtifact.status == 'ready', + ) + .values(status='superseded') + ) + artifact = ShippingExportArtifact( + artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_id, template_id=template.id, + order_schema_version_id=extraction.schema_version_id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id, + input_checksum=_input_checksum(task, source, template, extraction, header_values, line_values), + file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(), + file_size=len(content), status='ready', + ) + db.session.add(artifact) + db.session.flush() + return str(path), filename, artifact + except Exception: + if path.is_file(): + path.unlink() + raise diff --git a/backend/app/services/shipping_notice/export_archive.py b/backend/app/services/shipping_notice/export_archive.py new file mode 100644 index 00000000..8338e7a7 --- /dev/null +++ b/backend/app/services/shipping_notice/export_archive.py @@ -0,0 +1,129 @@ +""" +services/shipping_notice/export_archive.py + +用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。 +依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。 +逻辑:只选每票最新 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime +from pathlib import Path +from tempfile import SpooledTemporaryFile +from typing import BinaryIO +from zipfile import ZIP_DEFLATED, ZipFile + +from app.core.errors import NotFoundError, ValidationError +from app.models import ShippingExportArtifact, ShippingTask +from app.services.shipping_notice.query_service import get_batch_for_user, get_task_for_user, list_sorted_batch_tasks + +MAX_ARCHIVE_TASKS = 100 + + +def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingTask], str]: + """按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。""" + normalized_batch = str(batch_no or '').strip() + normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip())) + if bool(normalized_batch) == bool(normalized_tasks): + raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID') + if normalized_batch: + batch = get_batch_for_user(normalized_batch, user_id) + if batch is None: + raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') + tasks = list_sorted_batch_tasks(batch) + archive_key = normalized_batch + else: + tasks = [] + for task_no in normalized_tasks: + task = get_task_for_user(task_no, user_id) + if task is None: + raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND') + tasks.append(task) + archive_key = 'selected' + if not tasks: + raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY') + if len(tasks) > MAX_ARCHIVE_TASKS: + raise ValidationError( + f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once', + code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS}, + ) + return tasks, archive_key + + +def _latest_ready_artifacts(tasks: list[ShippingTask]) -> dict[int, ShippingExportArtifact]: + """批量查询每票最新 ready Artifact,避免 N+1。""" + task_ids = [int(task.id) for task in tasks if task.id is not None] + rows = ShippingExportArtifact.query.join(ShippingTask, ShippingTask.id == ShippingExportArtifact.task_id).filter( + ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready', + ShippingTask.export_file_path == ShippingExportArtifact.file_path, + ).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).all() + result: dict[int, ShippingExportArtifact] = {} + for item in rows: + result.setdefault(int(item.task_id), item) + return result + + +def _archive_name(filename: str, task_no: str, used: set[str]) -> str: + """保留原下载名;冲突时追加 task_no,仍冲突再追加序号。""" + safe = Path(filename or f'{task_no}.xlsx').name + candidate = safe + if candidate.lower() in used: + stem = Path(safe).stem + suffix = Path(safe).suffix or '.xlsx' + candidate = f'{stem}_{task_no}{suffix}' + sequence = 2 + base = candidate + while candidate.lower() in used: + candidate = f'{Path(base).stem}_{sequence}{Path(base).suffix}' + sequence += 1 + used.add(candidate.lower()) + return candidate + + +def build_export_archive( + *, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None, +) -> tuple[BinaryIO, str, dict]: + """ + 生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。 + + Returns: + (定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。 + """ + tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos) + artifacts = _latest_ready_artifacts(tasks) + # 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。 + stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b') + used_names: set[str] = {'manifest.json'} + entries: list[dict] = [] + included = 0 + with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive: + for task in tasks: + artifact = artifacts.get(int(task.id)) if task.id is not None else None + entry = {'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None} + if artifact is not None: + entry['artifact_no'] = artifact.artifact_no + path = Path(artifact.file_path) + if not path.is_file(): + entry['status'] = 'missing_file' + else: + content = path.read_bytes() + if hashlib.sha256(content).hexdigest() != artifact.file_checksum: + entry['status'] = 'checksum_mismatch' + else: + name = _archive_name(artifact.file_name, task.task_no, used_names) + archive.writestr(name, content) + entry.update({'status': 'included', 'file_name': name, 'file_checksum': artifact.file_checksum}) + included += 1 + entries.append(entry) + manifest = { + 'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []}, + 'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks), + 'included_count': included, 'excluded_count': len(tasks) - included, 'entries': entries, + } + archive.writestr('manifest.json', json.dumps(manifest, ensure_ascii=False, indent=2).encode('utf-8')) + stream.seek(0) + filename = f'shipping_exports_{archive_key}_{datetime.utcnow():%Y%m%d%H%M%S}.zip' + return stream, filename, manifest diff --git a/backend/app/services/shipping_notice/field_alignment_summary.py b/backend/app/services/shipping_notice/field_alignment_summary.py index c63efb84..53fba6ce 100644 --- a/backend/app/services/shipping_notice/field_alignment_summary.py +++ b/backend/app/services/shipping_notice/field_alignment_summary.py @@ -105,9 +105,7 @@ def format_field_alignment_summary( payload: dict[str, Any] | None = None, ) -> str: """ - 生成字段对齐确认的固定 Markdown 摘要(apply_inventory_mapping / align_review 用)。 - - Agent 须原文展示 message 给用户后再等待 confirm_inventory_mapping。 + 生成库存与订单字段对照的固定 Markdown 摘要,仅用于解析审计和结果展示。 """ resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None) inv_count = inventory_row_count diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 83890ea7..e24596f1 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -9,6 +9,8 @@ services/shipping_notice/fulfillment_workflow.py from __future__ import annotations +from pathlib import Path + from datetime import datetime from typing import Any @@ -17,11 +19,7 @@ from flask import current_app from app import db from app.models import ShippingTask, ShippingTaskEvent from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING -from app.services.shipping_notice.export import generate_shipment_excel -from app.services.shipping_notice.inventory_mapping_workflow import ( - awaiting_inventory_mapping_confirm, - inventory_mapping_checkpoint_response, -) +from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task from app.services.shipping_notice.inventory_workflow import ( ensure_inventory, @@ -34,7 +32,6 @@ from app.services.shipping_notice.query_service import ( task_export_error_message, ) from app.services.shipping_notice.i18n import resolve_lang, t -from app.services.shipping_notice.reservation_id import is_valid_reservation_id from app.services.shipping_notice.reservation_gate import reservation_gate_issues from app.services.shipping_notice.task_field_gate import field_conflict_gate_response from app.services.shipping_notice.task_line_store import read_task_order_lines @@ -232,6 +229,27 @@ def try_auto_chain_after_match( return result +def _order_extraction_gate_response( + task: ShippingTask, + *, + forbidden_next_tools: list[str], +) -> dict[str, Any] | None: + """要求任务绑定已接受的动态订单解析版本,禁止旧固定字段任务进入履约副作用。""" + try: + order_field_id_values(task) + except ValueError as exc: + return tool_response( + status="failed", + task=task, + message=str(exc), + data=serialize_task_for_tool(task), + forbidden_next_tools=forbidden_next_tools, + next_required_action="请重新提交订单解析并确认动态订单字段后继续。", + stop_agent_turn=True, + ) + return None + + def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: """ 将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。 @@ -272,12 +290,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: if reservation_gate is not None: return reservation_gate - # [STEP 1] 先确认字段对齐与库存快照是否已经就绪。 - # 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。 - if awaiting_inventory_mapping_confirm(task): - lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() - return inventory_mapping_checkpoint_response(task, lang=lang or None) + extraction_gate = _order_extraction_gate_response( + task, + forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], + ) + if extraction_gate is not None: + return extraction_gate + # [STEP 1] 正式库存已在载入阶段按 published Profile 校验;这里只确认库存快照是否就绪。 inventory_lines = parse_inventory_lines(payload) if inventory_lines: task.inventory_lines_json = inventory_lines @@ -290,6 +310,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: inv_payload["lang"] = lang return ensure_inventory(inv_payload) notice_lines = read_task_order_lines(task) + _order_header_values, order_field_lines = order_field_id_values(task) + for index, order_line in enumerate(order_field_lines): + legacy_line = notice_lines[index] if index < len(notice_lines) else {} + order_line['__required_qty'] = legacy_line.get('qty') + order_line['__display_part_number'] = legacy_line.get('part_number') + order_line['__display_reservation_id'] = legacy_line.get('reservation_id') total_notice_lines = len(notice_lines) set_task_step_progress( task, @@ -304,13 +330,6 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) db.session.flush() - # [STEP 2] 订单侧 Reservation 已在任何库存副作用前校验;此处只统计库存侧缺失。 - inv_missing_count = sum( - 1 - for row in (inventory_lines or []) - if not is_valid_reservation_id((row or {}).get("reservation_id")) - ) - if not is_inventory_source_stable(task): return tool_response( status="needs_human", @@ -339,13 +358,29 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: if processed == total or processed % 50 == 0: db.session.flush() + from app.models import ShippingInventoryField, ShippingInventorySource + + source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first() + definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} + match_keys = definition.get('match_keys') if isinstance(definition, dict) else [] + mapped_field_ids = [ + int(field_id) for field_id in (definition.get('field_mapping') or {}) + if str(field_id).isdigit() + ] if isinstance(definition, dict) else [] + quantity_fields = ShippingInventoryField.query.filter( + ShippingInventoryField.id.in_(mapped_field_ids), + ShippingInventoryField.status == 'active', + ShippingInventoryField.usage_type == 'inventory_quantity', + ).all() if mapped_field_ids else [] + if len(quantity_fields) != 1: + raise ValueError('库存解析方案必须且只能配置一个库存数量字段') match_status, line_results, shortage = match_notice_lines( - notice_lines, + order_field_lines, inventory_lines or [], + match_keys=match_keys, + quantity_field_id=str(quantity_fields[0].id), progress_callback=_on_match_progress, ) - if inv_missing_count and isinstance(shortage, dict): - shortage.pop("warnings", None) task.match_status = match_status task.line_results_json = line_results task.shortage_json = shortage @@ -396,6 +431,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) +def _commit_generated_export(path: str) -> None: + """提交任务与 Artifact;提交失败时回滚并删除本次生成文件。""" + try: + db.session.commit() + except Exception: + db.session.rollback() + generated_path = Path(path) + if generated_path.is_file(): + generated_path.unlink() + raise + + def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: """ 基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。 @@ -430,6 +477,13 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: if reservation_gate is not None: return reservation_gate + extraction_gate = _order_extraction_gate_response( + task, + forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], + ) + if extraction_gate is not None: + return extraction_gate + if not is_inventory_source_stable(task): return tool_response( status="failed", @@ -475,7 +529,16 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 3] 生成文件并把任务推进到等待上传阶段。 # 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。 - path, filename = generate_shipment_excel(task) + try: + path, filename, artifact = generate_shipment_excel(task) + except ValueError as exc: + return tool_response( + status="failed", + task=task, + message=str(exc), + data=serialize_task_for_tool(task), + forbidden_next_tools=["upload_to_freight"], + ) task.export_file_path = path task.export_file_name = filename apply_task_transition(task, TaskTransition.WAITING_UPLOAD) @@ -488,8 +551,8 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: progress_percent=100, detail=filename, ) - log_task_event(task, "export_generated", {"file_name": filename}) - db.session.commit() + log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no}) + _commit_generated_export(path) return tool_response( status="ok", task_id=task.task_no, @@ -823,4 +886,3 @@ def run_auto_progress_fulfillment_steps( return up return None - diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index e78c5aa7..a62cd016 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -84,14 +84,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态", "workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory", "workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。", - "workflow.decision.confirm_invalid_state": "当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。", - "workflow.decision.mapping_not_needed": "当前无需确认库存字段对齐。", - "workflow.decision.mapping_missing_reservation_warning": "库存表必须包含 Reservation ID 列标题(该列允许为空值)。请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。", - "workflow.decision.mapping_correction_invalid_state": "当前不在库存字段对齐确认步骤,无法更正映射。", - "workflow.decision.read_inventory_preview_failed": "读取库存表头失败: {error}", - "workflow.decision.mapping_preview_note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。", - "workflow.decision.mapping_correction_needed": "已回到列映射步骤。请根据 schema_preview 提供新的 map_json,再调用 apply_inventory_mapping。", - "workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)", + "workflow.decision.confirm_invalid_state": "当前状态无法使用确认。请先完成库存匹配,或选择重新解析订单。", "workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。", "workflow.decision.unknown": "未知 decision: {decision}", "workflow.inventory.task_not_found": "未找到任务编号", @@ -99,23 +92,15 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.inventory.text_too_large": "库存文本过大({chars} 字符,上限 {max_chars})。请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 POST /tools/upload_inventory_file 上传,再 parse_inventory(use_uploaded_file=true)。", "workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)", "workflow.inventory.parse_failed": "未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。", - "workflow.inventory.preview_read_failed": "读取库存表头失败: {error}", - "workflow.inventory.preview_ready": "已读取库存表头与样例行。请根据 schema_preview 推断列映射,调用 apply_inventory_mapping(map_json=...)。", - "workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"part_number\":\"\",\"aws_part_number\":\"\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping", "workflow.inventory.uploaded_file_missing_short": "未找到已上传的库存文件。请先 upload_inventory_file。", - "workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"part_number\":\"Supplier Sku列\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"};aws_part_number 可选。", - "workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。", "workflow.inventory.parse_failed_detail": "解析库存失败: {error}", "workflow.inventory.file_missing": "未收到 file 字段", - "workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .csv 库存文件", + "workflow.inventory.file_type_unsupported": "仅支持 .xls / .xlsx / .csv 库存文件", "workflow.inventory.uploading": "正在上传并解析库存文件", "workflow.inventory.uploading_detail": "正在处理库存文件 {filename}", "workflow.inventory.save_failed": "保存库存文件失败: {error}", "workflow.inventory.completed_task_locked": "该任务已完成,不能再重新上传库存。请切换到仍待处理的任务后再上传库存文件。", "workflow.inventory.uploaded": "库存文件已上传。", - "workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。", - "workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。", - "workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)", "workflow.inventory.ready_for_match": "已有库存快照且字段对齐已确认,可调用 match_inventory。", "workflow.inventory.unavailable": "暂无可用库存数据。请重新获取库存,或手动上传货代库存 Excel。", "workflow.fulfillment.task_not_found": "未找到任务编号", @@ -222,14 +207,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.", "workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory", "workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.", - "workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Please complete inventory matching first, or use confirm_inventory_mapping / reparse.", - "workflow.decision.mapping_not_needed": "Inventory field alignment confirmation is not needed right now.", - "workflow.decision.mapping_missing_reservation_warning": "The inventory sheet must contain a Reservation ID column header (the values in that column may be empty). Please use Fix Mapping to choose the Reservation ID column again, or re-upload an inventory Excel that contains that column.", - "workflow.decision.mapping_correction_invalid_state": "The task is not currently in the inventory field alignment confirmation step, so the mapping cannot be corrected.", - "workflow.decision.read_inventory_preview_failed": "Failed to read inventory headers: {error}", - "workflow.decision.mapping_preview_note": "No uploaded Excel was found. Please paste a small inventory table or re-upload, then call apply_inventory_mapping / parse_inventory.", - "workflow.decision.mapping_correction_needed": "The task has returned to the mapping step. Please provide a new map_json based on schema_preview, then call apply_inventory_mapping.", - "workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)", + "workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Complete inventory matching first, or reparse the order.", "workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.", "workflow.decision.unknown": "Unknown decision: {decision}", "workflow.inventory.task_not_found": "Task ID not found.", @@ -237,23 +215,15 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.inventory.text_too_large": "The inventory text is too large ({chars} characters, limit {max_chars}). Do not send the full Excel content to the LLM. Please call POST /tools/upload_inventory_file first, then parse_inventory(use_uploaded_file=true).", "workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)", "workflow.inventory.parse_failed": "Inventory lines could not be parsed. For large Excel files, use upload_inventory_file; for small tables, paste the content; if inventory is unavailable, use RPA.", - "workflow.inventory.preview_read_failed": "Failed to read inventory headers: {error}", - "workflow.inventory.preview_ready": "Inventory headers and sample rows have been loaded. Please infer the column mapping from schema_preview and call apply_inventory_mapping(map_json=...).", - "workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"part_number\":\"\",\"aws_part_number\":\"\",\"reservation_id\":\"\",\"available_qty\":\"\"}, then call apply_inventory_mapping", "workflow.inventory.uploaded_file_missing_short": "No uploaded inventory file was found. Please call upload_inventory_file first.", - "workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. Provide part_number (Supplier Sku), reservation_id, and available_qty mappings; aws_part_number is optional.", - "workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.", "workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}", "workflow.inventory.file_missing": "The file field was not received.", - "workflow.inventory.file_type_unsupported": "Only .xlsx / .csv inventory files are supported.", + "workflow.inventory.file_type_unsupported": "Only .xls / .xlsx / .csv inventory files are supported.", "workflow.inventory.uploading": "Uploading and parsing the inventory file.", "workflow.inventory.uploading_detail": "Processing inventory file {filename}", "workflow.inventory.save_failed": "Failed to save inventory file: {error}", "workflow.inventory.completed_task_locked": "This task is already completed, so inventory cannot be uploaded again. Please switch to a task that still needs processing.", "workflow.inventory.uploaded": "The inventory file has been uploaded.", - "workflow.inventory.uploaded_suggested_complete": " suggested_mapping is complete, so the canvas can call apply_inventory_mapping directly without using the LLM.", - "workflow.inventory.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.", - "workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)", "workflow.inventory.ready_for_match": "An inventory snapshot already exists and the field alignment has been confirmed. You may call match_inventory.", "workflow.inventory.unavailable": "No usable inventory data is available yet. Please retry the RPA export or upload the freight inventory Excel manually.", "workflow.fulfillment.task_not_found": "Task ID not found.", @@ -360,14 +330,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง", "workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory", "workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้", - "workflow.decision.confirm_invalid_state": "ไม่สามารถใช้ confirm ในสถานะปัจจุบันได้ โปรดทำ inventory matching ให้เสร็จก่อน หรือใช้ confirm_inventory_mapping / reparse", - "workflow.decision.mapping_not_needed": "ขณะนี้ยังไม่ต้องยืนยันการจับคู่คอลัมน์สต็อก", - "workflow.decision.mapping_missing_reservation_warning": "ไฟล์สต็อกต้องมีหัวคอลัมน์ Reservation ID (ค่าภายในคอลัมน์นี้สามารถเว้นว่างได้) โปรดใช้ Fix Mapping เพื่อเลือกคอลัมน์ Reservation ID ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกที่มีคอลัมน์นี้อีกครั้ง", - "workflow.decision.mapping_correction_invalid_state": "ขณะนี้งานไม่ได้อยู่ในขั้นตอนยืนยันการจับคู่คอลัมน์สต็อก จึงไม่สามารถแก้ไข mapping ได้", - "workflow.decision.read_inventory_preview_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}", - "workflow.decision.mapping_preview_note": "ไม่พบไฟล์ Excel ที่อัปโหลดไว้ โปรดวางตารางสต็อกขนาดเล็กหรืออัปโหลดใหม่ แล้วจึงเรียก apply_inventory_mapping / parse_inventory", - "workflow.decision.mapping_correction_needed": "งานได้ย้อนกลับมาที่ขั้นตอนจับคู่คอลัมน์แล้ว โปรดส่ง map_json ใหม่ตาม schema_preview แล้วเรียก apply_inventory_mapping", - "workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)", + "workflow.decision.confirm_invalid_state": "ไม่สามารถยืนยันในสถานะปัจจุบันได้ โปรดจับคู่สต็อกให้เสร็จก่อน หรือแยกวิเคราะห์คำสั่งซื้อใหม่", "workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน", "workflow.decision.unknown": "ไม่รู้จัก decision: {decision}", "workflow.inventory.task_not_found": "ไม่พบรหัสงาน", @@ -375,23 +338,15 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.inventory.text_too_large": "ข้อความสต็อกมีขนาดใหญ่เกินไป ({chars} ตัวอักษร, จำกัด {max_chars}) โปรดอย่าส่งเนื้อหา Excel ทั้งหมดเข้า LLM ให้เรียก POST /tools/upload_inventory_file ก่อน แล้วจึงใช้ parse_inventory(use_uploaded_file=true)", "workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)", "workflow.inventory.parse_failed": "ไม่สามารถแยกรายการสต็อกได้ สำหรับไฟล์ Excel ขนาดใหญ่ให้ใช้ upload_inventory_file; สำหรับตารางเล็กสามารถวางข้อความได้; หากไม่มีสต็อกให้ใช้ RPA", - "workflow.inventory.preview_read_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}", - "workflow.inventory.preview_ready": "อ่านหัวตารางและแถวตัวอย่างของสต็อกแล้ว โปรดอนุมานการจับคู่คอลัมน์จาก schema_preview แล้วเรียก apply_inventory_mapping(map_json=...)", - "workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows โดยใช้ part_number จาก Supplier Sku, aws_part_number จาก AWS Sku (ไม่บังคับ), reservation_id และ available_qty แล้วเรียก apply_inventory_mapping", "workflow.inventory.uploaded_file_missing_short": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดเรียก upload_inventory_file ก่อน", - "workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ part_number (Supplier Sku), reservation_id และ available_qty; aws_part_number เป็นตัวเลือก", - "workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers", "workflow.inventory.parse_failed_detail": "解析库存失败: {error}", "workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file", - "workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .csv", + "workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xls / .xlsx / .csv", "workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก", "workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}", "workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}", "workflow.inventory.completed_task_locked": "งานนี้เสร็จสิ้นแล้ว จึงไม่สามารถอัปโหลดสต็อกซ้ำได้ โปรดสลับไปยังงานที่ยังต้องดำเนินการ", "workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว", - "workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM", - "workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping", - "workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)", "workflow.inventory.ready_for_match": "มี inventory snapshot อยู่แล้วและยืนยันการจับคู่คอลัมน์แล้ว สามารถเรียก match_inventory ได้", "workflow.inventory.unavailable": "ยังไม่มีข้อมูลสต็อกที่ใช้งานได้ โปรดลองส่งออกผ่าน RPA ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกของผู้ให้บริการขนส่งด้วยตนเอง", "workflow.fulfillment.task_not_found": "ไม่พบรหัสงาน", diff --git a/backend/app/services/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/inventory_configuration_test.py new file mode 100644 index 00000000..7c039549 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_configuration_test.py @@ -0,0 +1,167 @@ +""" +services/shipping_notice/inventory_configuration_test.py + +用途:编排库存站点测试导出、RPA 回调文件分析和管理员确认解析方案。 +依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。 +逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。 +""" + +from __future__ import annotations + +import shutil +from datetime import datetime +from pathlib import Path +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + ShippingInventoryConfigurationTestRun, + ShippingInventoryParsingProfile, + ShippingInventorySource, +) + + +def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]: + """投影测试运行状态,避免暴露 RPA 文件的服务器路径。""" + return { + 'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id, + 'source_config_version': run.source_config_version, 'status': run.status, 'stage': run.stage, + 'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message, + 'created_at': run.created_at.isoformat() if run.created_at else None, + 'completed_at': run.completed_at.isoformat() if run.completed_at else None, + } + + +def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """为停用库存站点写入专用测试 trigger;重复点击复用等待中的运行。""" + source = db.session.get(ShippingInventorySource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + if source.enabled: + raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID') + if source.rpa_profile is None or not source.rpa_profile.enabled: + raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED') + active = ShippingInventoryConfigurationTestRun.query.filter( + ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, + ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + if active: + return _payload(active) + from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + + run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}' + run = ShippingInventoryConfigurationTestRun( + run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version, + status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id, + ) + db.session.add(run) + db.session.flush() + source_payload = get_database_inventory_source(source.source_code, enabled_only=False) + if source_payload is None: + raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + try: + trigger = write_inventory_export_batch_trigger(run_no, [source_payload], payload={ + 'trigger_type': 'configuration_test', 'configuration_test_run_id': run.id, + }) + except Exception: + db.session.rollback() + raise + if not trigger: + db.session.rollback() + raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE') + run.result_json = {'trigger_written': True} + db.session.commit() + return _payload(run) + + +def get_test_run(source_id: int, run_no: str) -> dict[str, Any]: + """读取指定库存站点的测试运行,防止跨站点查看结果。""" + run = ShippingInventoryConfigurationTestRun.query.filter_by( + inventory_source_id=source_id, run_no=str(run_no or '').strip(), + ).first() + if run is None: + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') + return _payload(run) + + +def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: + """处理 Worker 测试回调:分析文件并生成推荐,绝不创建生产库存快照。""" + run_no = str(payload.get('run_no') or '').strip() + run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first() + if run is None: + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') + if run.status == 'completed': + return _payload(run) + source = db.session.get(ShippingInventorySource, run.inventory_source_id) + if source is None or source.config_version != run.source_config_version: + run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow() + db.session.commit() + return _payload(run) + status = str(payload.get('status') or 'success').lower() + if status != 'success': + run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow() + db.session.commit() + return _payload(run) + path = Path(str(payload.get('file_path') or '')) + if not path.is_file(): + run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow() + db.session.commit() + return _payload(run) + from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, _analysis_root, serialize_analysis + from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix + from app.models import ShippingInventoryStructureAnalysis + import hashlib + import uuid + from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition + from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + + run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush() + suffix = resolve_inventory_upload_suffix(path.name) + raw = path.read_bytes() + target_dir = _analysis_root() / uuid.uuid4().hex + target_dir.mkdir(parents=True, exist_ok=False) + target = target_dir / f'test{suffix}' + try: + shutil.copy2(path, target) + structure, suggested, summary, warnings = _analyse_path(target, suffix) + definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', [])) + analysis = ShippingInventoryStructureAnalysis( + source_kind='configuration_test', source_file_name=path.name, storage_path=str(target), file_checksum=hashlib.sha256(raw).hexdigest(), + file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, + validation_summary_json=summary, warning_json=warnings, created_by=run.created_by, + exact_structure_fingerprint=exact_fingerprint(definition), compatibility_fingerprint=compatibility_fingerprint(definition=definition, field_mapping=suggested, match_keys=[]), + ) + db.session.add(analysis); db.session.flush() + analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint}) + run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow() + db.session.commit() + except Exception: + shutil.rmtree(target_dir, ignore_errors=True) + db.session.rollback() + raise + return _payload(run) + + +def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]: + """管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。""" + run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first() + if run is None or run.status != 'completed' or run.analysis_id is None: + raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_READY') + source = db.session.get(ShippingInventorySource, source_id) + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + if source is None or profile is None or profile.status != 'published': + raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + if source.enabled or source.config_version != run.source_config_version: + raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE') + from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile + + adopt_published_profile(run.analysis_id, profile_id) + source.parsing_profile_id = profile.id + source.updated_by = actor_id + source.config_version += 1 + run.source_config_version = source.config_version + run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum} + db.session.commit() + return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id} diff --git a/backend/app/services/shipping_notice/inventory_external_mapping.py b/backend/app/services/shipping_notice/inventory_external_mapping.py new file mode 100644 index 00000000..9e0ef723 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_external_mapping.py @@ -0,0 +1,38 @@ +""" +services/shipping_notice/inventory_external_mapping.py + +用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。 +依赖:ShippingInventoryExternalMapping、ShippingInventorySource。 +逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ShippingInventoryExternalMapping, ShippingInventorySource + + +def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None: + """按精确 Warehouse 映射优先、Source 默认映射兜底的顺序解析外部系统仓库。""" + code = str(source_code or '').strip().upper() + warehouse = str(freight_warehouse_id or '').strip().upper() + if not code: + return None + source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first() + if source is None: + return None + query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True) + mapping = query.filter_by(freight_warehouse_id=warehouse).first() if warehouse else None + mapping = mapping or query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() + if mapping is None: + return None + return { + 'external_system_code': mapping.external_system_code, + 'external_organization_code': mapping.external_organization_code, + 'external_site_code': mapping.external_site_code, + 'external_warehouse_code': mapping.external_warehouse_code, + 'external_warehouse_name': mapping.external_warehouse_name, + 'freight_warehouse_id': warehouse or None, + 'mapping_id': mapping.id, + } diff --git a/backend/app/services/shipping_notice/inventory_field_catalog.py b/backend/app/services/shipping_notice/inventory_field_catalog.py new file mode 100644 index 00000000..08312c6a --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_field_catalog.py @@ -0,0 +1,190 @@ +""" +services/shipping_notice/inventory_field_catalog.py + +用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。 +依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。 +逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。 +""" + +from __future__ import annotations + +import re +from hashlib import sha1 +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile + + +ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'} +ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'} + + +def _payload(item: ShippingInventoryField) -> dict[str, Any]: + """输出业务字段目录记录,不向管理端暴露内部字段编码。""" + return { + 'id': item.id, + 'display_name': item.display_name, + 'description': item.description or '', + 'value_type': item.value_type, + 'usage_type': item.usage_type, + 'status': item.status, + 'sort_order': item.sort_order, + 'created_at': item.created_at.isoformat() if item.created_at else None, + 'updated_at': item.updated_at.isoformat() if item.updated_at else None, + } + + +def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]: + """按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。""" + query = ShippingInventoryField.query + if not include_retired: + query = query.filter_by(status='active') + return [_payload(item) for item in query.order_by( + ShippingInventoryField.sort_order, ShippingInventoryField.id, + ).all()] + + +def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]: + """校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。""" + display_name = str(data.get('display_name') or '').strip() + description = str(data.get('description') or '').strip() or None + value_type = str(data.get('value_type') or 'text').strip().lower() + usage_type = str(data.get('usage_type') or 'general').strip().lower() + try: + sort_order = int(data.get('sort_order') if data.get('sort_order') is not None else 100) + except (TypeError, ValueError) as exc: + raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') from exc + if not display_name or len(display_name) > 128 or value_type not in ALLOWED_VALUE_TYPES or usage_type not in ALLOWED_USAGE_TYPES: + raise ValidationError('Inventory field data is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') + if sort_order < 0 or sort_order > 9999: + raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') + return { + 'display_name': display_name, + 'description': description, + 'value_type': value_type, + 'usage_type': usage_type, + 'sort_order': sort_order, + } + + +def _field_code(display_name: str) -> str: + """为扩展字段生成稳定内部编码;重复时追加序号,管理员无需维护该技术值。""" + stem = re.sub(r'[^a-z0-9]+', '_', display_name.lower()).strip('_') + if not stem: + # Chinese business names have no ASCII transliteration requirement; derive a stable opaque code instead. + stem = f'custom_{sha1(display_name.encode("utf-8")).hexdigest()[:12]}' + stem = stem[:52] + code = stem + sequence = 2 + while ShippingInventoryField.query.filter_by(field_code=code).first() is not None: + suffix = f'_{sequence}' + code = f'{stem[:64 - len(suffix)]}{suffix}' + sequence += 1 + return code + + +def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """创建用户定义的库存字段;内部编码仅供审计,不参与运行判断。""" + values = _normalized_payload(data) + if ShippingInventoryField.query.filter_by(display_name=values['display_name']).first() is not None: + raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT') + item = ShippingInventoryField( + field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id, + **values, + ) + db.session.add(item) + db.session.commit() + return _payload(item) + + +def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。""" + item = db.session.get(ShippingInventoryField, field_id) + if item is None: + raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + if item.status != 'active': + raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE') + values = _normalized_payload(data, existing=item) + references = _runtime_references(item.id) + if references and (values['value_type'] != item.value_type or values['usage_type'] != item.usage_type): + raise ConflictError( + 'Referenced inventory field type or usage cannot be changed', + code='SHIPPING.INVENTORY_FIELD_IMMUTABLE', details={'references': references}, + ) + duplicate = ShippingInventoryField.query.filter( + ShippingInventoryField.display_name == values['display_name'], + ShippingInventoryField.id != item.id, + ).first() + if duplicate is not None: + raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT') + for key, value in values.items(): + setattr(item, key, value) + item.updated_by = actor_id + db.session.commit() + return _payload(item) + + +def delete_field(field_id: int) -> dict[str, Any]: + """物理删除从未被配置引用的用户字段。""" + item = db.session.get(ShippingInventoryField, field_id) + if item is None: + raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + references = _runtime_references(item.id) + if references: + raise ConflictError( + 'Inventory field is referenced by runtime configuration', + code='SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED', details={'references': references}, + ) + db.session.delete(item) + db.session.commit() + return {'action': 'deleted'} + + +def retire_field(field_id: int) -> dict[str, Any]: + """退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。""" + item = db.session.get(ShippingInventoryField, field_id) + if item is None: + raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + references = _runtime_references(item.id) + if references: + raise ConflictError( + 'Inventory field is referenced by runtime configuration', + code='SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED', details={'references': references}, + ) + item.status = 'retired' + db.session.commit() + return _payload(item) + + +def _runtime_references(field_id: int) -> list[str]: + """列出字段目录的运行配置引用;阶段三会在此处补充发货模板引用。""" + reference = str(field_id) + parsing_profiles = [ + f'parsing_profile:{item.profile_code}:v{item.version}' + for item in ShippingInventoryParsingProfile.query.filter( + ShippingInventoryParsingProfile.status.in_(['draft', 'published']), + ).all() + if reference in { + str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys() + } + or any( + str(key.get('inventory_field_id') or '') == reference + for key in ((item.definition_json or {}).get('match_keys') or []) + if isinstance(key, dict) + ) + ] + templates = [ + f'excel_template:{item.template_code}:v{item.version}' + for item in ShippingExcelTemplate.query.filter( + ShippingExcelTemplate.status.in_(['draft', 'published']), + ).all() + if any( + isinstance(mapping, dict) + and mapping.get('source_kind') == 'inventory_field' + and str(mapping.get('source_key') or '') == reference + for mapping in ((item.definition_json or {}).get('mappings') or []) + ) + ] + return parsing_profiles + templates diff --git a/backend/app/services/shipping_notice/inventory_file_identity.py b/backend/app/services/shipping_notice/inventory_file_identity.py index a5b568d3..95317804 100644 --- a/backend/app/services/shipping_notice/inventory_file_identity.py +++ b/backend/app/services/shipping_notice/inventory_file_identity.py @@ -2,7 +2,7 @@ services/shipping_notice/inventory_file_identity.py 用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。 -依赖:openpyxl、csv、app.core.errors.AppError。 +依赖:openpyxl、xlrd、csv、app.core.errors.AppError。 逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。 """ @@ -107,6 +107,54 @@ def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int wb.close() +def _load_xls_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]: + """仅读取旧 xls 前若干行供 Warehouse 表头定位。""" + import xlrd + + try: + book = xlrd.open_workbook(filename=str(path), on_demand=True) + except Exception: + return [] + try: + sheet = book.sheet_by_index(0) + return [ + tuple(_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols)) + for row_index in range(min(max_rows, sheet.nrows)) + ] + finally: + book.release_resources() + + +def _iter_xls_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]: + """流式遍历旧 xls Warehouse 列非空值。""" + import xlrd + + book = xlrd.open_workbook(filename=str(path), on_demand=True) + try: + sheet = book.sheet_by_index(0) + for row_index in range(header_row_idx + 1, sheet.nrows): + if col_idx >= sheet.ncols: + continue + value = str(_xls_cell_value(book, sheet.cell(row_index, col_idx)) or '').strip().upper() + if value: + yield value + finally: + book.release_resources() + + +def _xls_cell_value(book: Any, cell: Any) -> Any: + """将 xlrd 旧 Excel 单元格转换为与 xlsx 读取一致的值。""" + import xlrd + + if cell.ctype == xlrd.XL_CELL_EMPTY: + return None + if cell.ctype == xlrd.XL_CELL_DATE: + return xlrd.xldate_as_datetime(cell.value, book.datemode) + if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer(): + return int(cell.value) + return cell.value + + def _detect_csv_dialect(sample: str) -> csv.Dialect: """探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。""" try: @@ -219,7 +267,13 @@ def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]: _iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx) ) if suffix == ".xls": - return set() + header_rows = _load_xls_header_rows(path) + header_row_idx, col_idx = _find_warehouse_column(header_rows) + if header_row_idx is None or col_idx is None: + return set() + return _collect_unique_warehouse_values( + _iter_xls_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx) + ) return set() @@ -254,10 +308,10 @@ def assert_inventory_excel_warehouse_identity( ) suffix = path.suffix.lower() - if suffix not in {".xlsx", ".csv"}: + if suffix not in {".xls", ".xlsx", ".csv"}: raise AppError( code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", - message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传", + message="库存源身份校验仅支持 .xls / .xlsx / .csv", http_status=409, details={"operation": operation, "file_suffix": suffix}, ) diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index 87cdd8e9..240a6939 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -28,7 +28,7 @@ from app.services.shipping_notice.inventory_source_gate import ( is_inventory_source_stable, task_inventory_identity, ) -from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version +from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version from app.services.shipping_notice.query_service import list_sorted_batch_tasks _TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"}) @@ -50,16 +50,17 @@ def generate_inventory_file_no() -> str: return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" -_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"}) +_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xls", ".xlsx", ".csv"}) def resolve_inventory_upload_suffix(filename: str) -> str: """ 解析人工上传库存文件的合法落盘后缀。 - 核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。 + 核心逻辑:允许 .xls / .xlsx / .csv;旧 Excel 由库存解析器使用 xlrd 读取, + 不将 .xls 伪装为 .xlsx 处理。 Raises: - AppError: 后缀缺失、不支持或为 .xls。 + AppError: 后缀缺失或不支持。 """ name = str(filename or "").strip().lower() if not name or "." not in name: @@ -73,14 +74,10 @@ def resolve_inventory_upload_suffix(filename: str) -> str: if name.endswith(".csv"): return ".csv" if name.endswith(".xls"): - raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", - message="库存上传不支持 .xls,请转换为 .xlsx 或 .csv 后重新上传", - http_status=409, - ) + return ".xls" raise AppError( code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", - message="库存上传仅支持 .xlsx / .csv", + message="库存上传仅支持 .xls / .xlsx / .csv", http_status=409, ) @@ -161,7 +158,6 @@ def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> boo right = task_inventory_identity(rhs) return ( left["inventory_source_code"] == right["inventory_source_code"] - and left["inventory_site_id"] == right["inventory_site_id"] and left["inventory_warehouse_id"] == right["inventory_warehouse_id"] ) @@ -171,7 +167,8 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship 保存库存 Excel 并创建批次级库存快照。 【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。 - 核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。 + 核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析; + 快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。 """ if not is_inventory_source_stable(task): raise AppError( @@ -182,7 +179,6 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship identity = task_inventory_identity(task) source_code = identity["inventory_source_code"] or "" - site_id = identity["inventory_site_id"] warehouse_id = identity["inventory_warehouse_id"] from datetime import datetime @@ -192,17 +188,44 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship path.parent.mkdir(parents=True, exist_ok=True) try: upload.save(str(path)) + from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + + structure_check = validate_production_inventory_structure(source_code=source_code, path=path) + inventory_lines, column_meta = parse_inventory_excel_with_meta( + path, + field_mapping=structure_check['field_mapping'], + mapping_source='parsing_profile', + header_row_index=structure_check['header_row_index'], + sheet_name=structure_check['sheet_name'], + ) + column_meta.update({ + 'sheet_name': structure_check['sheet_name'], + 'header_row_index': structure_check['header_row_index'], + 'structure_validation': { + 'level': structure_check['level'], + 'difference': structure_check['difference'], + 'warnings': structure_check['warnings'], + }, + }) + if not inventory_lines: + raise AppError( + code='SHIPPING.INVENTORY_FILE_EMPTY', + message='库存文件没有可用于匹配的有效库存数据', + http_status=409, + ) from app.services.shipping_notice.inventory_file_identity import ( assert_inventory_excel_warehouse_identity, ) - assert_inventory_excel_warehouse_identity( - path, - expected_warehouse_id=str(warehouse_id or ""), - operation="manual_upload", - ) + if str(warehouse_id or '').strip(): + assert_inventory_excel_warehouse_identity( + path, + expected_warehouse_id=str(warehouse_id or ""), + operation="manual_upload", + ) preview = read_inventory_schema_preview(path) preview["upload_filename"] = str(upload.filename or path.name) + preview['structure_validation'] = column_meta['structure_validation'] except AppError: if path.is_file(): try: @@ -230,12 +253,15 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship storage_path=str(path), schema_preview_json=preview, share_mode="task_only", - line_count=0, + line_count=len(inventory_lines), + inventory_lines_json=inventory_lines, + field_mapping_json=dict(structure_check['field_mapping']), + mapping_source='parsing_profile', + mapping_confirmed=True, source_code=source_code, 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(), + source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(), identity_status="pending", snapshot_status="ready", exported_at=datetime.utcnow(), @@ -387,31 +413,35 @@ def read_linked_inventory_schema_preview(task: ShippingTask) -> dict[str, Any]: return preview -def parse_linked_inventory_file( - task: ShippingTask, - *, - field_mapping: dict[str, str] | None = None, - mapping_source: str = "rules", - header_row_index: int | None = None, - llm_match_rule: str | None = None, - llm_match_key: list[str] | None = None, -) -> tuple[list[dict[str, Any]], dict[str, Any], Path, ShippingInventoryFile]: - """解析任务 active 库存快照 Excel,并返回解析行、列元数据、文件路径和快照对象。""" - inv_file = active_inventory_file_for_task(task) - if not inv_file: - raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照") +def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。 + + 仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败, + 促使管理员修复库存站点配置而不是让运行期静默采用旧规则或 LLM 映射。 + """ path = Path(inv_file.storage_path) if not path.is_file(): raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}") - lines, column_meta = parse_inventory_excel_with_meta( + from app.models import ShippingInventorySource + from app.services.shipping_notice.inventory_parsing_profile import require_source_profile + from app.core.errors import ValidationError + + source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first() + profile = require_source_profile(source) + actual_format = path.suffix.lower().lstrip('.') + if actual_format != profile.file_format: + raise ValidationError( + f'Inventory file format {actual_format} does not match parsing profile {profile.file_format}', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + definition = dict(profile.definition_json or {}) + return parse_inventory_excel_with_meta( path, - field_mapping=field_mapping, - mapping_source=mapping_source, - header_row_index=header_row_index, - llm_match_rule=llm_match_rule, - llm_match_key=llm_match_key, + field_mapping=dict(definition.get('field_mapping') or {}), + mapping_source=f"parsing_profile:{profile.profile_code}:v{profile.version}", + header_row_index=definition.get('header_row_index'), + sheet_name=str(definition.get('sheet_name') or '').strip() or None, ) - return lines, column_meta, path, inv_file def apply_inventory_parse_result_to_linked_tasks( diff --git a/backend/app/services/shipping_notice/inventory_mapping.py b/backend/app/services/shipping_notice/inventory_mapping.py index 6bc9f274..693d5dbe 100644 --- a/backend/app/services/shipping_notice/inventory_mapping.py +++ b/backend/app/services/shipping_notice/inventory_mapping.py @@ -1,23 +1,71 @@ """ services/shipping_notice/inventory_mapping.py -用途:标准化库存字段映射,补充匹配规则说明,并校验映射是否完整。 -依赖:match_rule_desc、标准 `json`/`typing` 能力。 -逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件解析 map_json,再进入库存解析和匹配链路。 +用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。 +依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。 +逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。 """ from __future__ import annotations from typing import Any +from app.models import ShippingInventoryField + from app.services.shipping_notice.match_rule_desc import resolve_match_rule -SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty") -REQUIRED_SYSTEM_FIELDS = ("part_number", "reservation_id", "available_qty") +LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty", "warehouse_id") +LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty") + + +def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]: + """读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。""" + try: + ids = {int(key) for key in field_mapping} + except (TypeError, ValueError): + return {} + if not ids or any(item <= 0 for item in ids): + return {} + rows = ShippingInventoryField.query.filter( + ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active', + ).all() + return {str(row.id): row for row in rows} + + +def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool: + """判断映射键是否为字段目录 ID;纯数字键绝不能回退成旧运行字段。""" + if not field_mapping: + return False + try: + return all(int(key) > 0 for key in field_mapping) + except (TypeError, ValueError): + return False + + +def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]: + """验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。""" + catalog = _catalog_by_id(field_mapping) + if _uses_catalog_ids(field_mapping): + if len(catalog) != len(field_mapping): + return {}, {} + return ({str(item.id): str(field_mapping[str(item.id)]).strip() for item in catalog.values()}, catalog) + # 临时会话上传尚未绑定库存站点时沿用受控旧格式;正式解析方案不会走该分支。 + return ({str(key): str(value).strip() for key, value in field_mapping.items()}, {}) + + +def usage_field_ids() -> dict[str, set[str]]: + """按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。""" + rows = ShippingInventoryField.query.filter( + ShippingInventoryField.status == 'active', + ).all() + result: dict[str, set[str]] = {} + for row in rows: + result.setdefault(row.usage_type, set()).add(str(row.id)) + return result def normalize_field_mapping(raw: Any) -> dict[str, str] | None: - """将 map_json 规范为库存 v2 字段映射;缺内部料号、Reservation 或可用量时返回 None。""" + """规范库存字段目录 ID 到来源栏位的映射;缺必要用途字段时返回 None。""" data: dict[str, Any] | None = None if isinstance(raw, dict): data = raw @@ -38,17 +86,17 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None: return None result: dict[str, str] = {} - for key in SYSTEM_FIELDS: + for key in LEGACY_SYSTEM_FIELDS: value = inner.get(key) if value is None: continue text = str(value).strip() if text: result[key] = text - return result if all(field in result for field in REQUIRED_SYSTEM_FIELDS) else None + return result if all(field in result for field in LEGACY_REQUIRED_FIELDS) else None -def suggest_field_mapping(headers: list[str]) -> dict[str, str]: +def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]: """基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。""" from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header @@ -105,12 +153,41 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]: if qty: mapping["available_qty"] = qty + warehouse = pick("warehouse_id", "Warehouse ID", "Warehouse", "Warehouse Code", "WH ID") + if warehouse: + mapping["warehouse_id"] = warehouse + return mapping +def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> dict[str, str]: + """按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。""" + if not as_catalog: + return _suggest_runtime_field_mapping(headers) + from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header + + rows = ShippingInventoryField.query.filter_by(status='active').all() + header_by_name: dict[str, list[str]] = {} + for header in headers: + normalized = normalise_header(header) + if normalized: + header_by_name.setdefault(normalized, []).append(str(header).strip()) + result: dict[str, str] = {} + for row in rows: + candidates = header_by_name.get(normalise_header(row.display_name), []) + if len(candidates) == 1: + result[str(row.id)] = candidates[0] + return result + + def mapping_is_complete(field_mapping: dict[str, str]) -> bool: - """映射是否同时包含内部料号、Reservation ID 与可用数量。""" - return all(bool(field_mapping.get(field)) for field in REQUIRED_SYSTEM_FIELDS) + """映射是否至少提供一个匹配字段和且仅一个库存数量字段。""" + runtime_mapping, catalog = runtime_field_mapping(field_mapping) + if catalog: + mapped = set(runtime_mapping) + usages = usage_field_ids() + return bool(mapped & usages.get('match_identity', set())) and len(mapped & usages.get('inventory_quantity', set())) == 1 + return all(bool(runtime_mapping.get(field)) for field in LEGACY_REQUIRED_FIELDS) def validate_field_mapping_against_headers( @@ -121,16 +198,17 @@ def validate_field_mapping_against_headers( norm_headers = [str(h or "").strip() for h in headers] lower_set = {h.lower() for h in norm_headers if h} errors: list[str] = [] - labels = { - "part_number": "part_number", - "aws_part_number": "aws_part_number", - "reservation_id": "reservation_id", - "available_qty": "available_qty", - } - for key, label in labels.items(): - name = str(field_mapping.get(key) or "").strip() + runtime_mapping, catalog = runtime_field_mapping(field_mapping) + if not runtime_mapping: + return ['库存字段目录中存在已停用或不存在的字段'] + required_codes = set(LEGACY_REQUIRED_FIELDS) + if catalog: + usages = usage_field_ids() + required_codes = (set(runtime_mapping) & usages.get('match_identity', set())) | (set(runtime_mapping) & usages.get('inventory_quantity', set())) + for key, name in runtime_mapping.items(): + label = catalog.get(key).display_name if key in catalog else key if not name: - if key in REQUIRED_SYSTEM_FIELDS: + if key in required_codes: errors.append(f"缺少 {label} 列映射") continue if name not in norm_headers and name.lower() not in lower_set: @@ -145,9 +223,7 @@ def resolve_columns_from_field_mapping( headers: list[str], field_mapping: dict[str, str], ) -> dict[str, int | None]: - """将显式 field_mapping 转为系统字段 → 列索引映射(保留自动检测的可选列)。""" - from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns - + """将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。""" norm_headers = [str(h or "").strip() for h in headers] lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h} @@ -161,19 +237,10 @@ def resolve_columns_from_field_mapping( return norm_headers.index(name) return lower_to_idx.get(name.lower()) - # Keep auto-detected optional columns (e.g. odm_id / qty) even when the - # required mapping is provided explicitly by LLM or user. - columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP) - columns.update({ - "part_number": idx_for(field_mapping.get("part_number")), - "aws_part_number": idx_for(field_mapping.get("aws_part_number")), - "reservation_id": idx_for(field_mapping.get("reservation_id")), - "available_qty": None, - }) - avail_header = field_mapping.get("available_qty") - if avail_header: - columns["available_qty"] = idx_for(avail_header) - return columns + runtime_mapping, _catalog = runtime_field_mapping(field_mapping) + if not runtime_mapping: + return {} + return {field_code: idx_for(header_name) for field_code, header_name in runtime_mapping.items()} def build_column_meta_from_mapping( @@ -181,10 +248,9 @@ def build_column_meta_from_mapping( field_mapping: dict[str, str], *, mapping_source: str = "rules", - llm_match_rule: str | None = None, - llm_match_key: list[str] | None = None, ) -> dict[str, Any]: - """由用户/LLM 确认的 field_mapping 构建 column_meta(含 match_rule 与 source_column)。""" + """由规则建议或已发布方案构建 column_meta(含匹配说明与来源栏位)。""" + runtime_mapping, catalog = runtime_field_mapping(field_mapping) columns = resolve_columns_from_field_mapping(headers, field_mapping) def source_column(index: int | None) -> str | None: @@ -193,38 +259,19 @@ def build_column_meta_from_mapping( text = str(headers[index] or "").strip() return text or None - qty_header = field_mapping.get("available_qty") - match_rule, match_key, match_rule_source = resolve_match_rule( - field_mapping, - llm_match_rule=llm_match_rule, - llm_match_key=llm_match_key, - ) + labels = {str(item.id): item.display_name for item in catalog.values()} + match_rule, match_key, match_rule_source = resolve_match_rule(runtime_mapping) return { "headers": [str(h or "").strip() for h in headers], "mapping_source": mapping_source, "field_mapping": dict(field_mapping), "mapping": { - "part_number": { - "system_field": "part_number", - "label": "Supplier Sku / 内部料号", - "source_column": source_column(columns.get("part_number")), - }, - "aws_part_number": { - "system_field": "aws_part_number", - "label": "AWS Sku / AWS 料号", - "source_column": source_column(columns.get("aws_part_number")), - }, - "reservation_id": { - "system_field": "reservation_id", - "label": "Reservation ID", - "source_column": source_column(columns.get("reservation_id")), - }, - "available_qty": { - "system_field": "available_qty", - "label": "可用数量", - "source_column": qty_header or source_column(columns.get("available_qty")), - "qty_preference": "available_qty", - }, + field_id: { + "inventory_field_id": int(field_id) if field_id.isdigit() else None, + "label": labels.get(field_id, field_id), + "source_column": source_column(index), + } + for field_id, index in columns.items() }, "match_key": match_key, "match_rule": match_rule, diff --git a/backend/app/services/shipping_notice/inventory_mapping_store.py b/backend/app/services/shipping_notice/inventory_mapping_store.py deleted file mode 100644 index 9b1bf2f3..00000000 --- a/backend/app/services/shipping_notice/inventory_mapping_store.py +++ /dev/null @@ -1,91 +0,0 @@ -""" -services/shipping_notice/inventory_mapping_store.py - -用途:持久化库存字段映射模板,并按客户与表头哈希做查询复用。 -依赖:db、ShippingInventoryMapping 模型、hashlib/json。 -逻辑:由 inventory_mapping_workflow 或库存上传链路调用本文件,把用户确认过的映射保存下来供后续同模板复用。 -""" - -from __future__ import annotations - -import json -from datetime import datetime -from hashlib import sha256 -from typing import Any - -from app import db -from app.models import ShippingInventoryMapping - - -_GLOBAL_CUSTOMER_CODE = "GLOBAL" - - -def _customer_key(customer_code: str | None) -> str: - key = str(customer_code or "").strip() - return key or _GLOBAL_CUSTOMER_CODE - - -def compute_inventory_header_hash(headers: list[str], header_row_index: int | None = None) -> str: - """对表头行与 header_row_index 计算 SHA256,用作映射模板去重键。""" - norm_headers = [str(h or "").strip() for h in headers] - payload = { - "header_row_index": int(header_row_index or 1), - "headers": norm_headers, - } - raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8") - return sha256(raw).hexdigest() - - -def find_inventory_mapping(customer_code: str | None, header_hash: str) -> ShippingInventoryMapping | None: - """按 customer_code + header_hash 查找已保存的列映射模板。""" - customer = _customer_key(customer_code) - if not header_hash: - return None - return ShippingInventoryMapping.query.filter_by(customer_code=customer, header_hash=header_hash).first() - - -def resolve_inventory_mapping( - customer_code: str | None, - *, - preview: dict[str, Any], -) -> dict[str, str] | None: - """从 schema preview 匹配历史映射模板;命中时更新 last_used_at。""" - customer = _customer_key(customer_code) - headers = preview.get("headers") if isinstance(preview.get("headers"), list) else [] - header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index")) - record = find_inventory_mapping(customer, header_hash) - if not record: - return None - record.last_used_at = datetime.utcnow() - if isinstance(record.field_mapping_json, dict) and record.field_mapping_json: - return {str(k): str(v) for k, v in record.field_mapping_json.items() if v} - return None - - -def upsert_inventory_mapping( - customer_code: str | None, - *, - preview: dict[str, Any], - field_mapping: dict[str, str], -) -> ShippingInventoryMapping | None: - """保存或更新客户+表头哈希对应的列映射模板。""" - customer = _customer_key(customer_code) - headers = preview.get("headers") if isinstance(preview.get("headers"), list) else [] - header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index")) - record = find_inventory_mapping(customer, header_hash) - now = datetime.utcnow() - if record: - record.field_mapping_json = dict(field_mapping) - record.headers_json = [str(h or "").strip() for h in headers] - record.updated_at = now - record.last_used_at = now - return record - record = ShippingInventoryMapping( - customer_code=customer, - header_hash=header_hash, - headers_json=[str(h or "").strip() for h in headers], - field_mapping_json=dict(field_mapping), - last_used_at=now, - ) - db.session.add(record) - return record diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py index 9d218159..eabc4cbf 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py @@ -1,275 +1,28 @@ """ services/shipping_notice/inventory_mapping_workflow.py -用途:库存字段对齐确认、自动映射推进与库存载入后的 auto-chain 编排。 -依赖:inventory_snapshot、inventory_mapping_store、query_service、task_line_store、tool_common、state_machine。 -逻辑:inventory_workflow / inventory_rpa_workflow 在解析/上传后委托本模块; - task_workflow / fulfillment_workflow 在决策与 auto_progress 中调用映射门禁; - 订单行对齐预览经 read_task_order_lines 读取。 +用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。 +依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。 +逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。 """ from __future__ import annotations from typing import Any -from flask import current_app - from app import db -from app.models import ShippingTask, ShippingTaskEvent -from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary +from app.models import ShippingTask from app.services.shipping_notice.inventory_file_store import ( active_inventory_file_for_task, apply_inventory_parse_result_to_linked_tasks, start_inventory_file_linked_tasks, ) -from app.services.shipping_notice.inventory_mapping import mapping_is_complete -from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview from app.services.shipping_notice.query_service import serialize_task_for_tool from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.task_line_store import read_task_order_lines -from app.services.shipping_notice.tool_common import ( - auto_mapping_allow_llm, - auto_match_enabled, - auto_progress_enabled, - log_task_event, - payload_wants_auto_chain_fallback, - set_task_step_progress, -) +from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress from app.services.shipping_notice.tool_response import tool_response -from app.services.shipping_notice.constants import RS_ALIGN_REVIEW - - -def mapping_review_enabled() -> bool: - """是否启用库存字段对齐人审(SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW,默认 true)。""" - val = current_app.config.get("SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW") - if val is None: - return True - return str(val).lower() not in {"0", "false", "no", "off"} - - -def awaiting_inventory_mapping_confirm(task: ShippingTask) -> bool: - """任务是否停在 align_review 等待用户确认库存列映射。""" - return task.review_status == RS_ALIGN_REVIEW - - -def latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None: - """从最近 30 条任务事件中回溯最新的 column_meta。""" - if task.id is None: - return None - events = ( - ShippingTaskEvent.query.filter_by(task_id=task.id) - .order_by(ShippingTaskEvent.id.desc()) - .limit(30) - .all() - ) - for event in events: - detail = event.detail_json or {} - meta = detail.get("column_meta") - if isinstance(meta, dict) and meta: - return meta - return None - - -def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | None = None) -> dict[str, Any]: - """为当前任务生成 field_alignment 预览(订单行 vs 库存行 + warnings)。""" - meta = column_meta or latest_inventory_column_meta(task) - return build_field_alignment_preview( - task.inventory_lines_json or [], - read_task_order_lines(task), - column_meta=meta, - ) - - -def mapping_confirm_blockers(task: ShippingTask) -> list[str]: - """列映射尚不能自动/人工确认的原因列表(中文)。""" - blockers: list[str] = [] - meta = latest_inventory_column_meta(task) or {} - inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {} - res_source = None - if isinstance(inv_mapping.get("reservation_id"), dict): - res_source = inv_mapping["reservation_id"].get("source_column") - if not str(res_source or "").strip(): - blockers.append("缺少 Reservation ID 列映射") - field_alignment = field_alignment_for_task(task) - warnings = field_alignment.get("warnings") if isinstance(field_alignment.get("warnings"), list) else [] - blockers.extend(str(w) for w in warnings if w) - return blockers - - -def can_auto_advance_mapping(task: ShippingTask) -> bool: - """映射完整且无 blocker 时,auto_progress 可跳过 align_review 人审门禁。""" - if not auto_progress_enabled() or not auto_match_enabled(): - return False - if not mapping_review_enabled(): - return False - if not awaiting_inventory_mapping_confirm(task): - return False - if mapping_confirm_blockers(task): - return False - meta = latest_inventory_column_meta(task) or {} - mapping_source = str(meta.get("mapping_source") or "rules").strip().lower() - if mapping_source == "llm" and not auto_mapping_allow_llm(): - return False - return True - - -def should_auto_chain_after_mapping( - task: ShippingTask, - payload: dict[str, Any] | None, -) -> bool: - """库存映射完成后是否应自动串联 match_inventory(fallback 或 auto_advance)。""" - if payload_wants_auto_chain_fallback(payload): - return True - return can_auto_advance_mapping(task) - - -def inventory_mapping_checkpoint_response( - task: ShippingTask, - *, - column_meta: dict[str, Any] | None = None, - extra_data: dict[str, Any] | None = None, - lang: str | None = None, -) -> dict[str, Any]: - """ - 返回 align_review 检查点响应,强制 Agent 停等用户确认字段对齐。 - 【AI 触发时机】:match_inventory 发现仍待映射确认时由内部调用;Agent 禁止主动调用。 - """ - # [STEP 1] 先根据任务和列信息构建字段对齐视图。 - # 这里要把库存列、订单字段和额外 warning 汇总成用户能直接确认的 message/data。 - field_alignment = field_alignment_for_task(task, column_meta) - extra = extra_data or {} - message = format_field_alignment_summary( - task_no=task.task_no, - field_alignment=field_alignment, - inventory_row_count=extra.get("inventory_row_count"), - warnings=extra.get("warnings") if isinstance(extra.get("warnings"), list) else None, - lang=lang, - ) - data = { - **serialize_task_for_tool(task), - "field_alignment": field_alignment, - **extra, - } - set_task_step_progress( - task, - step_key="step4_align_confirm", - step_title="确认字段对齐", - status="needs_human", - message="请确认库存字段对齐后再继续匹配", - progress_percent=100, - current=3, - total=3, - detail="系统已识别必填列映射,请先人工确认", - extra={"field_alignment": field_alignment}, - ) - db.session.flush() - # [STEP 2] 明确停在人审检查点。 - # 返回值必须阻止同轮继续调用 match_inventory,确保用户先确认字段对齐。 - return tool_response( - status="needs_human", - task=task, - message=message, - data=data, - next_required_action=( - "向用户原文展示 message(固定 Markdown)后停止本轮;" - "用户确认后调用 submit_decision(decision=confirm_inventory_mapping);" - "禁止在同一轮调用 match_inventory" - ), - forbidden_next_tools=[ - "match_inventory", - "generate_shipment_excel", - "upload_to_freight", - ], - stop_agent_turn=True, - ) - - -def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool: - """auto_progress 路径下自动确认映射并推进 MAPPING_CONFIRMED;成功返回 True。""" - # [STEP 1] 先检查是否满足自动确认前提。 - # 包括开关、当前检查点、阻塞项以及 LLM 映射是否被允许自动接受。 - if not auto_progress_enabled(): - return False - if not mapping_review_enabled(): - return False - if not awaiting_inventory_mapping_confirm(task): - return False - if mapping_confirm_blockers(task): - return False - meta = latest_inventory_column_meta(task) or {} - mapping_source = str(meta.get("mapping_source") or "rules").strip().lower() - if mapping_source == "llm" and not auto_mapping_allow_llm(): - return False - - # [STEP 2] 若映射完整则先落模板,再推进状态机。 - # 这样相同客户/表头的后续上传可以直接复用人工确认过的映射结果。 - headers = meta.get("headers") if isinstance(meta.get("headers"), list) else [] - field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None - if headers and field_mapping and mapping_is_complete(field_mapping): - upsert_inventory_mapping( - task.customer_code, - preview={ - "headers": headers, - "header_row_index": meta.get("header_row_index") or 1, - }, - field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()}, - ) - - # [STEP 3] 最后把任务推进到 mapping_confirmed,并记录自动确认审计事件。 - field_alignment = field_alignment_for_task(task) - apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED) - log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment}) - inv_file = active_inventory_file_for_task(task) - if inv_file: - inv_file.mapping_confirmed = True - for link in inv_file.links or []: - linked_task = link.task - if not link.is_active or not linked_task or linked_task.id == task.id: - continue - if awaiting_inventory_mapping_confirm(linked_task): - apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED) - log_task_event( - linked_task, - "inventory_mapping_auto_confirmed", - { - "field_alignment": field_alignment, - "confirmed_by_task_no": task.task_no, - "inventory_file_no": inv_file.inventory_file_no, - }, - ) - db.session.commit() - if inv_file: - start_inventory_file_linked_tasks(inv_file) - return True - - -def _try_auto_chain_after_inventory_loaded( - task: ShippingTask, - *, - payload: dict[str, Any] | None = None, -) -> dict[str, Any] | None: - """Auto: confirm mapping → match → Excel → RPA upload when allowed.""" - from app.services.shipping_notice.fulfillment_workflow import ( - match_completed, - match_inventory, - try_auto_chain_after_match, - ) - from app.services.shipping_notice.tool_common import merge_tool_payload, prepend_tool_message - - if not should_auto_chain_after_mapping(task, payload): - return None - auto_confirmed = maybe_auto_confirm_inventory_mapping(task) - if auto_confirmed: - db.session.refresh(task) - if awaiting_inventory_mapping_confirm(task): - return None - if not auto_match_enabled() or match_completed(task): - return None - match_result = match_inventory(merge_tool_payload(task, payload)) - if auto_confirmed: - match_result = prepend_tool_message(match_result, "字段对齐已自动确认。") - return try_auto_chain_after_match(task, match_result, payload=payload) def inventory_loaded_response( @@ -279,29 +32,28 @@ def inventory_loaded_response( warnings: list[str] | None = None, column_meta: dict[str, Any] | None = None, source: str, - require_mapping_review: bool, event_type: str, - chain_payload: dict[str, Any] | None = None, field_mapping: dict[str, str] | None = None, mapping_source: str | None = None, commit: bool = True, ) -> dict[str, Any]: """ - 库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。 + 写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。 Args: - require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。 - chain_payload: 传递给 auto-chain 的原始请求体。 - commit: False 时仅 flush,供 batch 外层统一提交,避免中途 commit 破坏事务边界。 - """ - def _persist_inventory_loaded() -> None: - if commit: - db.session.commit() - else: - db.session.flush() + task: 当前正式发货任务。 + inventory_lines: 已通过 published Profile 结构校验和类型转换的库存行。 + warnings: 非阻断解析提示。 + column_meta: 解析审计元数据,仅用于展示和追溯。 + source: 库存来源标识。 + event_type: 库存载入审计事件类型。 + field_mapping: published Profile 的字段映射快照。 + mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。 + commit: False 时仅 flush,供批量回调维持外层事务边界。 - # [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。 - # 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。 + Returns: + Tool 标准响应;成功后任务可直接进入库存匹配。 + """ inv_file = active_inventory_file_for_task(task) linked_tasks: list[ShippingTask] = [] if inv_file: @@ -310,84 +62,27 @@ def inventory_loaded_response( inventory_lines, field_mapping=field_mapping, mapping_source=mapping_source, - mapping_confirmed=False, + mapping_confirmed=True, ) else: task.inventory_lines_json = inventory_lines - field_alignment = field_alignment_for_task(task, column_meta) + + field_alignment = build_field_alignment_preview( + inventory_lines, + read_task_order_lines(task), + column_meta=column_meta, + ) set_task_step_progress( task, step_key="step3_inventory_prepare", step_title="获取库存", - status="running" if require_mapping_review else "completed", + status="completed", message=f"已载入库存 {len(inventory_lines)} 行", progress_percent=100, current=len(inventory_lines), total=len(inventory_lines), - detail="库存快照已就绪,正在进入字段对齐阶段" if require_mapping_review else "库存快照已就绪,可进入匹配阶段", + detail="库存结构校验与解析已完成,可进入匹配阶段", ) - - # [STEP 2] 如果当前策略要求映射复核,则先进入对齐确认检查点。 - # 同时尝试自动串联;只有自动串联没有吃掉结果时,才真正返回给用户确认映射。 - if require_mapping_review and mapping_review_enabled(): - apply_task_transition(task, TaskTransition.INVENTORY_ALIGN_REVIEW) - log_task_event( - task, - event_type, - { - "row_count": len(inventory_lines), - "warnings": warnings or [], - "source": source, - "mapping_review": True, - "column_meta": column_meta, - "inventory_file_no": inv_file.inventory_file_no if inv_file else None, - "linked_task_nos": [item.task_no for item in linked_tasks], - }, - ) - for linked_task in linked_tasks: - if linked_task.id == task.id: - continue - apply_task_transition(linked_task, TaskTransition.INVENTORY_ALIGN_REVIEW) - log_task_event( - linked_task, - event_type, - { - "row_count": len(inventory_lines), - "warnings": warnings or [], - "source": source, - "mapping_review": True, - "inventory_file_no": inv_file.inventory_file_no if inv_file else None, - "owner_task_no": task.task_no, - "column_meta": column_meta, - }, - ) - _persist_inventory_loaded() - if commit: - chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload) - else: - chained = None - if chained is not None: - return chained - lang = None - if chain_payload: - lang = str( - chain_payload.get("lang") - or chain_payload.get("locale") - or chain_payload.get("language") - or "" - ).strip() or None - return inventory_mapping_checkpoint_response( - task, - column_meta=column_meta, - extra_data={ - "inventory_row_count": len(inventory_lines), - "warnings": warnings or [], - }, - lang=lang, - ) - - # [STEP 3] 无需映射复核时,直接推进到 inventory_ready。 - # 这条路径主要服务于明确结构化库存输入,尽快把任务交给后续匹配阶段。 apply_task_transition(task, TaskTransition.INVENTORY_READY) for linked_task in linked_tasks: if linked_task.id != task.id: @@ -404,7 +99,10 @@ def inventory_loaded_response( "linked_task_nos": [item.task_no for item in linked_tasks], }, ) - _persist_inventory_loaded() + if commit: + db.session.commit() + else: + db.session.flush() if commit and inv_file: start_inventory_file_linked_tasks(inv_file) return tool_response( diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/shipping_notice/inventory_parsing_profile.py new file mode 100644 index 00000000..74e6f7d4 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_parsing_profile.py @@ -0,0 +1,208 @@ +""" +backend/app/services/shipping_notice/inventory_parsing_profile.py + +用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。 +依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。 +逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime +from typing import Any + +from sqlalchemy import func + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + ShippingInventoryField, + ShippingInventoryParsingProfile, + ShippingInventorySource, + ShippingOrderField, +) + + +def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]: + """解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。""" + field_ids: list[int] = [] + for raw_id in field_mapping: + try: + field_id = int(raw_id) + except (TypeError, ValueError) as exc: + raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc + if field_id <= 0: + raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + field_ids.append(field_id) + rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else [] + fields = {str(row.id): row for row in rows if row.status == 'active'} + if len(fields) != len(set(str(item) for item in field_ids)): + raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + return fields + + +def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]: + """校验解析方案具备匹配与库存数量能力,不限定字段名称。""" + match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'} + quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'} + if not match_ids or len(quantity_ids) != 1: + raise ValidationError( + 'Parsing profile requires at least one match field and exactly one inventory quantity field', + code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + ) + return match_ids | quantity_ids + + +def _validate_definition(raw: Any) -> dict[str, Any]: + """校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。""" + if not isinstance(raw, dict): + raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + field_mapping = raw.get('field_mapping') + if not isinstance(field_mapping, dict) or not field_mapping: + raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + if any(not str(value or '').strip() for value in field_mapping.values()): + raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + catalog_fields = _catalog_fields(field_mapping) + _required_catalog_field_ids(catalog_fields) + match_keys = raw.get('match_keys') + if not isinstance(match_keys, list) or not match_keys: + raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + normalized_keys: list[dict[str, str]] = [] + seen_order_fields: set[str] = set() + seen_inventory_fields: set[str] = set() + for item in match_keys: + field = db.session.get(ShippingOrderField, str(item.get('order_field_id') or '')) if isinstance(item, dict) else None + inventory_field = str(item.get('inventory_field_id') or item.get('inventory_field') or '') if isinstance(item, dict) else '' + inventory = catalog_fields.get(inventory_field) + if ( + field is None or field.status != 'active' or field.scope != 'line' + or inventory is None or inventory.usage_type != 'match_identity' + ): + raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + if field.id in seen_order_fields or inventory_field in seen_inventory_fields: + raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + seen_order_fields.add(field.id) + seen_inventory_fields.add(inventory_field) + normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field}) + header_row_index = raw.get('header_row_index') + if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1): + raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + return { + 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, + 'header_row_index': header_row_index, + 'field_mapping': {str(int(key)): str(value).strip() for key, value in field_mapping.items()}, + 'match_keys': normalized_keys, + } + + +def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: + """序列化解析 Profile 管理 DTO。""" + return { + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, + 'definition': profile.definition_json or {}, 'checksum': profile.checksum, + 'published_at': profile.published_at.isoformat() if profile.published_at else None, + 'source_count': len(profile.sources), + } + + +def list_profiles() -> list[dict[str, Any]]: + """列出全部解析 Profile 版本。""" + return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by( + ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(), + ).all()] + + +def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: + """创建或更新解析 Profile 草稿;published 版本不可原地修改。""" + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None + if profile_id and profile is None: + raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + if profile is not None and profile.status != 'draft': + raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE') + code = str(data.get('profile_code') or '').strip().upper() + if not code: + raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + if profile is not None and code != profile.profile_code: + raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE') + if profile is None: + next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1 + profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id) + db.session.add(profile) + profile.display_name = str(data.get('display_name') or code).strip() + profile.file_format = str(data.get('file_format') or 'xlsx').lower() + if profile.file_format not in {'xls', 'xlsx', 'csv'}: + raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + definition = _validate_definition(data.get('definition')) + if profile.file_format == 'csv' and definition.get('sheet_name'): + raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + profile.definition_json = definition + db.session.commit() + return payload(profile) + + +def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: + """发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。""" + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + if profile is None: + raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + if profile.status != 'draft': + raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID') + from app.services.shipping_notice.order_schema import service as order_schema_service + + published_field_ids = { + str(item.get('field_id') or '') + for item in order_schema_service.get_published_contract().get('fields', []) + } + referenced_field_ids = { + str(item.get('order_field_id') or '') + for item in (profile.definition_json or {}).get('match_keys', []) + if isinstance(item, dict) + } + if not referenced_field_ids or not referenced_field_ids <= published_field_ids: + raise ValidationError( + 'Parsing profile match keys must reference the current published order schema', + code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID', + ) + encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() + profile.checksum = hashlib.sha256(encoded).hexdigest() + profile.status = 'published' + profile.published_by = actor_id + profile.published_at = datetime.utcnow() + db.session.commit() + return payload(profile) + + +def retire(profile_id: int) -> dict[str, Any]: + """退役无库存源引用的 published Profile,避免使现有 Source 静默失效。""" + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + if profile is None: + raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + if profile.status != 'published': + raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID') + if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count(): + raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED') + profile.status = 'retired' + db.session.commit() + return payload(profile) + + +def delete_draft(profile_id: int) -> None: + """删除从未发布的解析 Profile 草稿。""" + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + if profile is None: + raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + if profile.status != 'draft': + raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED') + db.session.delete(profile) + db.session.commit() + + +def require_source_profile(source: Any) -> ShippingInventoryParsingProfile: + """读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。""" + profile = getattr(source, 'parsing_profile', None) + if profile is None or profile.status != 'published': + raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + return profile diff --git a/backend/app/services/shipping_notice/inventory_profile_matching.py b/backend/app/services/shipping_notice/inventory_profile_matching.py new file mode 100644 index 00000000..9fd072e7 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_profile_matching.py @@ -0,0 +1,74 @@ +""" +services/shipping_notice/inventory_profile_matching.py + +用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。 +依赖:ShippingInventoryParsingProfile、库存结构指纹服务。 +逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ShippingInventoryParsingProfile +from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header + + +def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]: + """读取已发布方案保存的结构表头,缺失时不参与新方案复用推荐。""" + structure = profile.structure_definition_json if isinstance(profile.structure_definition_json, dict) else {} + return [str(header) for header in structure.get('headers', [])] + + +def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> dict[str, list[str]]: + """以业务栏位名称展示新增、缺少和顺序变化,避免只给相似度百分比。""" + structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {} + observed = [normalise_header(header) for header in structure.get('selected_headers', [])] + expected = [normalise_header(header) for header in _profile_headers(profile)] + return { + 'added_columns': [header for header in observed if header and header not in expected], + 'missing_columns': [header for header in expected if header and header not in observed], + 'column_order_changed': ['yes'] if set(observed) == set(expected) and observed != expected else [], + } + + +def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool: + """确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。""" + from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids + + structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {} + observed_headers = {normalise_header(header) for header in structure.get('selected_headers', [])} + definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + expected = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {} + expected_runtime, _ = runtime_field_mapping(expected) + usages = usage_field_ids() + expected_ids = set(expected_runtime) + required = expected_ids & (usages.get('match_identity', set()) | usages.get('inventory_quantity', set())) + if not (required & usages.get('match_identity', set())) or len(required & usages.get('inventory_quantity', set())) != 1: + return False + return all(normalise_header(expected_runtime.get(field)) in observed_headers for field in required) + + +def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]: + """查找已发布方案并返回可解释推荐;库存数据内容、文件名和内容 hash 均不参与判断。""" + exact = str(analysis.get('exact_structure_fingerprint') or '') + compatible = str(analysis.get('compatibility_fingerprint') or '') + profiles = ShippingInventoryParsingProfile.query.filter_by(status='published').all() + candidates: list[dict[str, Any]] = [] + for profile in profiles: + level = None + if exact and profile.exact_structure_fingerprint == exact: + level = 'exact' + elif _core_mapping_matches(analysis, profile): + difference = _difference(analysis, profile) + if not difference['missing_columns']: + level = 'compatible' + if level: + candidates.append({ + 'profile_id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'version': profile.version, 'level': level, 'difference': _difference(analysis, profile), + 'source_count': len(profile.sources), + }) + candidates.sort(key=lambda item: (0 if item['level'] == 'exact' else 1, -item['source_count'], item['profile_code'])) + result = {'status': candidates[0]['level'] if candidates else 'no_match', 'candidates': candidates} + return result diff --git a/backend/app/services/shipping_notice/inventory_routing_engine.py b/backend/app/services/shipping_notice/inventory_routing_engine.py new file mode 100644 index 00000000..5c32ea90 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_routing_engine.py @@ -0,0 +1,113 @@ +""" +services/shipping_notice/inventory_routing_engine.py + +用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。 +依赖:库存路由模型、routing_facts、routing_operators。 +逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +from app.models import ShippingInventoryRoutingRule, ShippingOrderFieldValue, ShippingOrderLine +from app.services.shipping_notice.routing_facts import build_routing_facts, read_system_fact +from app.services.shipping_notice.routing_operators import matches_operator + + +ALLOWED_ACTIONS = frozenset({'add_source_candidates', 'exclude_source_candidates', 'require_manual_review'}) + + +@dataclass(frozen=True) +class InventoryRoutingResult: + """路由引擎输出;evidence 可持久化到任务审计快照。""" + + status: str + source_codes: tuple[str, ...] + matched_rule_ids: tuple[int, ...] + evidence: dict[str, Any] + + +def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None, + facts: dict[str, dict[str, Any]]) -> Any: + """读取受控系统事实或 Task 当前 Extraction 的动态订单字段值。""" + if condition.source_kind == 'system_fact': + return read_system_fact(facts, condition.system_fact_key) + extraction_id = getattr(task, 'current_order_extraction_id', None) + if not extraction_id: + return None + query = ShippingOrderFieldValue.query.filter_by( + extraction_id=int(extraction_id), field_id=condition.order_field_id, + ) + if line is None: + value = query.filter(ShippingOrderFieldValue.line_id.is_(None)).first() + else: + position = int(line.get('_position', 0)) + value = query.join(ShippingOrderLine, ShippingOrderLine.id == ShippingOrderFieldValue.line_id).filter( + ShippingOrderLine.position == position, + ).first() + return value.value_json if value is not None else None + + +def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None, + facts: dict[str, dict[str, Any]]) -> bool: + """判断规则条件按 all/any 语义是否命中。""" + results = [ + matches_operator(_condition_value(condition, task=task, line=line, facts=facts), condition.operator, condition.expected_value_json) + for condition in rule.conditions + ] + if not results: + return False + return all(results) if rule.match_mode == 'all' else any(results) + + +def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None = None, now: datetime | None = None) -> InventoryRoutingResult: + """ + 评估已发布规则并返回最高优先级的 Source 候选集合。 + + Args: + task: 已解析的货代任务。 + line: 行级规则的订单行;任务级规则传 None。 + now: 测试可注入的评估时间,默认当前 UTC 时间。 + + Returns: + InventoryRoutingResult: resolved/unresolved/ambiguous/conflicted 状态及可审计证据。 + """ + moment = now or datetime.utcnow() + scope = 'line' if line is not None else 'task' + facts = build_routing_facts(task=task, line=line) + query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope) + rules = [ + rule for rule in query.order_by(ShippingInventoryRoutingRule.priority.desc(), ShippingInventoryRoutingRule.id.asc()).all() + if (rule.effective_from is None or rule.effective_from <= moment) + and (rule.effective_to is None or rule.effective_to >= moment) + ] + matched = [rule for rule in rules if _rule_matches(rule, task=task, line=line, facts=facts)] + if not matched: + return InventoryRoutingResult('unresolved', (), (), {'facts': facts, 'matched_rules': []}) + priority = matched[0].priority + top_rules = [rule for rule in matched if rule.priority == priority] + source_codes: set[str] = set() + excluded: set[str] = set() + manual = False + for rule in top_rules: + if rule.action_type not in ALLOWED_ACTIONS: + return InventoryRoutingResult('conflicted', (), tuple(item.id for item in top_rules), {'reason': 'unsupported_action'}) + payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {} + codes = {str(code or '').strip().upper() for code in payload.get('source_codes', []) if str(code or '').strip()} + if rule.action_type == 'add_source_candidates': + source_codes.update(codes) + elif rule.action_type == 'exclude_source_candidates': + excluded.update(codes) + else: + manual = True + source_codes.difference_update(excluded) + status = 'conflicted' if manual else ('resolved' if len(source_codes) == 1 else 'ambiguous' if source_codes else 'unresolved') + return InventoryRoutingResult( + status, + tuple(sorted(source_codes)), + tuple(rule.id for rule in top_rules), + {'facts': facts, 'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]}, + ) diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 12e1624b..a06a4dda 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -3,7 +3,7 @@ services/shipping_notice/inventory_rpa_workflow.py 用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。 依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、task_line_store、tool_common、state_machine、tool_response。 -逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory; +逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;tools 门面 re-export rpa_report_inventory; Reservation 门禁订单行经 read_task_order_lines 读取。 """ @@ -23,7 +23,6 @@ from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, CP_PARSE_OK, - CP_PARSE_REVIEW, CP_UPLOAD_REQ, PH_INVENTORY_SOURCE_UNRESOLVED, PH_RPA_PENDING, @@ -53,14 +52,12 @@ from app.services.shipping_notice.inventory_source_gate import ( confirm_task_inventory_source, inventory_identities_match, is_inventory_source_stable, - 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, serialize_task_for_tool, @@ -141,21 +138,16 @@ def _try_reuse_inventory_snapshot( 优先复用未过期库存快照,避免重复触发 RPA。 【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。 - 核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入映射/匹配。 + 核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入待匹配状态。 retry_rpa 必须跳过缓存强制重新导出。 """ if mode == "retry_rpa": return None - from app.services.shipping_notice.inventory_mapping_workflow import ( - awaiting_inventory_mapping_confirm, - inventory_loaded_response, - inventory_mapping_checkpoint_response, - ) + from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response snapshot = find_latest_ready_snapshot( str(rpa_source.get("source_code") or ""), - str(rpa_source.get("site_id") or ""), str(rpa_source.get("warehouse_id") or ""), ) if not snapshot: @@ -187,21 +179,19 @@ def _try_reuse_inventory_snapshot( ] if cached_lines: task.inventory_lines_json = cached_lines - if awaiting_inventory_mapping_confirm(task): - db.session.commit() - return inventory_mapping_checkpoint_response(task) return inventory_loaded_response( task, cached_lines, column_meta={"source": "snapshot_reuse"}, source="snapshot_reuse", - require_mapping_review=not snapshot.mapping_confirmed, event_type="inventory_snapshot_reused", ) path = Path(snapshot.storage_path) if path.is_file(): - lines, column_meta = ingest_inventory_file(path, move_to=None) + from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file + + lines, column_meta = parse_inventory_snapshot_file(snapshot) if lines: snapshot.inventory_lines_json = lines snapshot.line_count = len(lines) @@ -210,7 +200,6 @@ def _try_reuse_inventory_snapshot( lines, column_meta=column_meta, source="snapshot_reuse", - require_mapping_review=True, event_type="inventory_snapshot_reused", ) @@ -218,7 +207,7 @@ def _try_reuse_inventory_snapshot( return tool_response( status="running", task_id=task.task_no, - message="已关联最新库存快照,正在读取字段映射。", + message="已关联最新库存快照,正在读取库存数据。", data=serialize_task_for_tool(task), ) @@ -331,21 +320,19 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works return ensure_inventory_via_rpa(task, mode="auto") -def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str, str]: - """从任务正式库存身份推导快照预期三元组。""" +def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str]: + """从任务正式库存身份推导快照预期二元组。""" return ( str(task.inventory_source_code or "").strip().upper(), - str(task.inventory_site_id or "").strip().upper(), str(task.inventory_warehouse_id or "").strip().upper(), ) -def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str, str]: - """从 RPA/配置源推导快照预期身份三元组,供回调入库前预检。""" +def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str]: + """从 RPA/配置源推导快照预期身份二元组,供回调入库前预检。""" code = str(source.get("source_code") or "").strip().upper() - site = str(source.get("site_id") or "").strip().upper() warehouse = str(source.get("warehouse_id") or "").strip().upper() - return code, site, warehouse + return code, warehouse def _rollback_orphan_inventory_snapshot( @@ -748,8 +735,8 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None: def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None: """ - 成功回调的身份契约:source/site/warehouse/run_no 必须与任务一致。 - 核心逻辑:仅 success 路径调用;skipped/failed 允许 RPA 缺身份字段。 + 成功回调的身份契约:Source 必须与任务一致;fixed Source 的 Warehouse 还须一致。 + 核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。 """ callback_source = str(payload.get("source_code") or "").strip().upper() task_source = str(task.inventory_source_code or "").strip().upper() @@ -768,18 +755,13 @@ def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[st data=serialize_task_for_tool(task), ) - callback_site = str(payload.get("site_id") or "").strip().upper() + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + + source = get_database_inventory_source(task_source) + is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed' callback_wh = str(payload.get("warehouse_id") or "").strip().upper() - task_site = str(task.inventory_site_id or "").strip().upper() task_wh = str(task.inventory_warehouse_id or "").strip().upper() - if not callback_site or callback_site != task_site: - return tool_response( - status="failed", - task=task, - message="RPA 回调 site_id 与任务库存源不一致,已拒绝入库", - data=serialize_task_for_tool(task), - ) - if not callback_wh or callback_wh != task_wh: + if is_fixed and (not callback_wh or callback_wh != task_wh): return tool_response( status="failed", task=task, @@ -853,9 +835,9 @@ def _resolve_batch_callback_source( source_code = str(item.get("source_code") or "").strip().upper() if not source_code: return None - from app.services.shipping_notice.inventory_sources import get_inventory_source + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - return get_inventory_source(source_code) + return get_database_inventory_source(source_code) def _batch_snapshot_verify_warehouse_id( @@ -864,6 +846,8 @@ def _batch_snapshot_verify_warehouse_id( item: dict[str, Any] | None = None, ) -> str | None: """推导批量快照入库前须校验的 Excel Warehouse ID。""" + if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match': + return None if task: warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() return warehouse_id or None @@ -877,36 +861,21 @@ def _batch_snapshot_verify_warehouse_id( def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None: """ - 校验批量回调 Worker 返回的四字段身份与启用配置一致。 - 核心逻辑:定时/无任务成功项必须显式携带 source/site/warehouse;动态库位源校验 allowed_warehouse_ids。 + 校验批量回调 Worker 返回的 Source/Warehouse 身份与启用配置一致。 + 核心逻辑:定时/无任务成功项必须显式携带 source/warehouse;动态仓接受库存文件返回的 Warehouse。 """ - from app.services.shipping_notice.inventory_sources import ( - configured_allowed_warehouse_ids, - source_uses_dynamic_warehouse_id, - ) - callback_source = str(item.get("source_code") or "").strip().upper() - callback_site = str(item.get("site_id") or "").strip().upper() callback_wh = str(item.get("warehouse_id") or "").strip().upper() if not callback_source: return "source_code_missing" - if not callback_site: - return "site_id_missing" if not callback_wh: return "warehouse_id_missing" cfg_source = str(source.get("source_code") or "").strip().upper() - cfg_site = str(source.get("site_id") or "").strip().upper() - cfg_wh = str(source.get("warehouse_id") or "").strip().upper() + cfg_wh = str(source.get("fixed_warehouse_id") or source.get("warehouse_id") or "").strip().upper() if callback_source != cfg_source: return "source_code_mismatch" - if callback_site != cfg_site: - return "site_id_mismatch" - - if source_uses_dynamic_warehouse_id(source): - allowed = configured_allowed_warehouse_ids(source) - if allowed and callback_wh not in allowed: - return "warehouse_id_not_allowed" + if str(source.get('warehouse_resolution_mode') or '') == 'inventory_match': return None if callback_wh != cfg_wh: @@ -916,10 +885,9 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: """ - 确认当前任务的库存 RPA 来源,并在门禁通过后继续触发库存导出。 + 确认当前任务的库存来源,并在门禁通过后等待库存文件可用。 - 【AI 触发时机】:当用户在库存源检查点(通常已先完成解析确认)选择 source_code 后调用。 - 兼容:存量任务若仍带 pending_parse_review_after_source,确认源后会回到 parse_review。 + 【AI 触发时机】:当用户完成解析确认并在库存源检查点选择 source_code 后调用。 """ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -963,60 +931,22 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]: { "source_code": task.inventory_source_code, "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", }, ) - # 存量兼容:旧顺序先确认库存源时延后的低置信度解析复核。 - if task_needs_parse_review(task): - step_payload = dict(task.step_payload_json or {}) - step_payload.pop("pending_parse_review_after_source", None) - task.step_payload_json = step_payload - apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) - task.current_step = "step2_parse_confirm" - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message="库存源已确认,请继续确认解析结果。", - data=serialize_task_for_tool(task), - checkpoint=CP_PARSE_REVIEW, - stop_agent_turn=True, - ) - apply_task_transition(task, TaskTransition.PARSED) task.pending_human_reason = None task.review_status = None task.error_message = None - step_payload = dict(task.step_payload_json or {}) - step_payload.pop("pending_parse_review_after_source", None) - task.step_payload_json = step_payload task.current_step = "step3_inventory_prepare" db.session.commit() - from app.services.shipping_notice.tool_common import auto_rpa_inventory_enabled - - if (not task.inventory_lines_json) and auto_rpa_inventory_enabled(): - rpa_result = ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto")) - rpa_status = str(rpa_result.get("status") or "").strip().lower() - if rpa_status in {"running", "ok"}: - return rpa_result - if rpa_status == "needs_human" and str(task.pending_human_reason or "").strip() == PH_RPA_PENDING: - return rpa_result - return tool_response( - status="ok", - task=task, - message="库存源已确认;自动获取库存暂未完成,请稍后重试或手动上传库存文件。", - data=serialize_task_for_tool(task), - checkpoint=CP_PARSE_OK, - ) - return tool_response( status="ok", task=task, - message="库存源已确认。", + message="库存源已确认;将使用该来源已导出的有效库存文件。", data=serialize_task_for_tool(task), checkpoint=CP_PARSE_OK, ) @@ -1577,7 +1507,28 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if link is None: raise _RpaCallbackItemAbort("inventory_identity_mismatch") - lines, column_meta = ingest_inventory_file(ingest_path, move_to=None) + from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + + structure_check = validate_production_inventory_structure( + source_code=str(rpa_source['source_code']), path=ingest_path, + ) + lines, column_meta = ingest_inventory_file( + ingest_path, move_to=None, + field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile', + header_row_index=structure_check['header_row_index'], sheet_name=structure_check['sheet_name'], + ) + column_meta.update({ + 'sheet_name': structure_check['sheet_name'], + 'header_row_index': structure_check['header_row_index'], + 'structure_validation': { + 'level': structure_check['level'], 'difference': structure_check['difference'], + 'warnings': structure_check['warnings'], + }, + }) + inv_file.schema_preview_json = { + **(inv_file.schema_preview_json or {}), + 'structure_validation': column_meta['structure_validation'], + } set_task_step_progress( task, step_key="step3_inventory_prepare", @@ -1598,6 +1549,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: "origin_file_path": str(path), "inventory_file_no": inv_file.inventory_file_no, "reused_existing_snapshot": not created_new, + "structure_validation": column_meta.get('structure_validation'), }, ) _mark_inventory_rpa_run_no_consumed(task, run_no) @@ -1606,7 +1558,6 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: lines, column_meta=column_meta, source="rpa_callback", - require_mapping_review=True, event_type="inventory_rpa_ready", commit=False, ) @@ -1753,7 +1704,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: merged_item = _merge_batch_callback_item(payload, item) source_code = str(merged_item.get("source_code") or "").strip().upper() warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper() - site_id = str(merged_item.get("site_id") or "").strip().upper() raw_status = _normalize_rpa_inventory_batch_item_status(merged_item) task_no = str(merged_item.get("task_no") or "").strip() task: ShippingTask | None = None @@ -1762,7 +1712,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if task is None: failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error": "task_not_found", @@ -1775,7 +1724,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if gate_resp is not None: failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error": gate_resp.get("message") or "inventory_source_gate_blocked", @@ -1786,7 +1734,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {} failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error": round_data.get("run_no_error") or "run_no_invalid", @@ -1797,7 +1744,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: _handle_rpa_inventory_skipped(task, merged_item, runtime, commit=False) skipped.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "skip_reason": merged_item.get("skip_reason") or "skipped", @@ -1807,7 +1753,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: _handle_rpa_inventory_failed(task, merged_item, runtime, commit=False) failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error_code": merged_item.get("error_code") or "rpa_export_failed", @@ -1819,7 +1764,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if not source: error = { "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "error": "unknown_or_disabled_source", } @@ -1841,7 +1785,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if not path or not path.is_file(): failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "error": "file_missing", }) @@ -1852,21 +1795,21 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if gate_resp is not None: failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error": gate_resp.get("message") or "inventory_source_gate_blocked", }) continue - if not inventory_identities_match( - task, - source_code=str(source.get("source_code") or ""), - site_id=str(source.get("site_id") or ""), - warehouse_id=str(source.get("warehouse_id") or ""), + if ( + str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed' + and not inventory_identities_match( + task, + source_code=str(source.get("source_code") or ""), + warehouse_id=warehouse_id, + ) ): failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error": "inventory_identity_mismatch", @@ -1877,7 +1820,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: if identity_error: failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "error": identity_error, }) @@ -1916,25 +1858,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: ): item_orphan_path = str(inv_file.storage_path) + from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + + ingest_path = _snapshot_ingest_path(inv_file) + structure_check = validate_production_inventory_structure( + source_code=source_code, path=ingest_path, + ) created_entry = { "inventory_file_no": inv_file.inventory_file_no, "source_code": inv_file.source_code or source_code, - "site_id": inv_file.site_id or merged_item.get("site_id"), "warehouse_id": inv_file.warehouse_id or warehouse_id, "reused_existing_snapshot": not created_new, + "structure_validation": { + "level": structure_check["level"], + "difference": structure_check["difference"], + }, } created.append(created_entry) if item_orphan_path: batch_new_storage_paths.append(item_orphan_path) if task_no and task: - if not inventory_identities_match( - task, - source_code=inv_file.source_code, - site_id=inv_file.site_id, - warehouse_id=inv_file.warehouse_id, - ): - raise _RpaCallbackItemAbort("inventory_identity_mismatch") link = link_snapshot_to_task( task, inv_file, @@ -1943,15 +1887,26 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: ) if link is None: raise _RpaCallbackItemAbort("inventory_identity_mismatch") - ingest_path = _snapshot_ingest_path(inv_file) - lines, column_meta = ingest_inventory_file(ingest_path, move_to=None) + lines, column_meta = ingest_inventory_file( + ingest_path, move_to=None, + field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile', + header_row_index=structure_check['header_row_index'], sheet_name=structure_check['sheet_name'], + ) + column_meta.update({ + 'sheet_name': structure_check['sheet_name'], + 'header_row_index': structure_check['header_row_index'], + 'structure_validation': created_entry['structure_validation'], + }) + inv_file.schema_preview_json = { + **(inv_file.schema_preview_json or {}), + 'structure_validation': column_meta['structure_validation'], + } if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}: inventory_loaded_response( task, lines, column_meta=column_meta, source="rpa_batch_callback", - require_mapping_review=True, event_type="inventory_rpa_ready", commit=False, ) @@ -1982,7 +1937,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: created.pop() failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no or None, "error": abort.error, @@ -2000,7 +1954,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: created.pop() failed.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "task_no": task_no, "error": str(exc)[:200] or "batch_ingest_failed", @@ -2009,7 +1962,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: elif raw_status == "skipped": skipped.append({ "source_code": source_code, - "site_id": merged_item.get("site_id"), "warehouse_id": warehouse_id, "skip_reason": merged_item.get("skip_reason") or "skipped", "message": merged_item.get("message") or merged_item.get("error_message") or "", @@ -2017,7 +1969,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: else: failed.append({ "source_code": str(source.get("source_code") or source_code), - "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "error_code": merged_item.get("error_code") or "rpa_export_failed", "error": merged_item.get("error_message"), @@ -2147,13 +2098,16 @@ def _validate_repair_inventory_snapshot( return "snapshot_expired" if not is_inventory_source_stable(task): return "inventory_source_unstable" - if not inventory_identities_match( - task, - source_code=inv_file.source_code, - site_id=inv_file.site_id, - warehouse_id=inv_file.warehouse_id, - ): - return "inventory_identity_mismatch" + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + + source = get_database_inventory_source(task.inventory_source_code) + if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed': + if not inventory_identities_match( + task, + source_code=inv_file.source_code, + warehouse_id=inv_file.warehouse_id, + ): + return "inventory_identity_mismatch" return None diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py index 1609f540..b6c4a15a 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/inventory_snapshot.py @@ -2,7 +2,7 @@ services/shipping_notice/inventory_snapshot.py 用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。 -依赖:openpyxl、reservation_id、Flask current_app 配置、Path 文件操作。 +依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。 逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。 """ @@ -65,6 +65,11 @@ DEFAULT_COLUMN_MAP = { "Qty": "qty", "qty": "qty", "数量": "qty", + # Warehouse:动态 Source 必须保留行级 Warehouse,不能只记录整个文件的单一值。 + "Warehouse ID": "warehouse_id", + "Warehouse": "warehouse_id", + "Warehouse Code": "warehouse_id", + "WH ID": "warehouse_id", # ODM "ODM ID": "odm_id", "ODM Id": "odm_id", @@ -121,7 +126,7 @@ def _map_header(header: str, col_map: dict[str, str]) -> str | None: def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]: - idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = None + idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = idx_warehouse = None for i, h in enumerate(headers): mapped = _map_header(h, col_map) if mapped == "part_number" and idx_part_number is None: @@ -136,6 +141,8 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d idx_qty = i elif mapped == "odm_id" and idx_odm is None: idx_odm = i + elif mapped == "warehouse_id" and idx_warehouse is None: + idx_warehouse = i # 若 reservation 列未命中,按 AWS 模板常见列名再试 if idx_reservation is None: @@ -152,6 +159,7 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d "available_qty": idx_available, "qty": idx_qty, "odm_id": idx_odm, + "warehouse_id": idx_warehouse, } @@ -174,7 +182,38 @@ def _normalize_inventory_row( *, default_part_number_index: int | None = None, default_qty_index: int = 1, + configured_mapping: bool = False, ) -> dict[str, Any] | None: + # Published profiles use inventory field IDs as row keys. Field purpose and + # value type come from the user-maintained catalog, never from a fixed code. + if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns): + from app.models import ShippingInventoryField + + field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()} + catalog = { + str(item.id): item + for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all() + } + parsed = { + field_id: _cell(row, index) + for field_id, index in columns.items() + if index is not None and _cell(row, index) not in (None, '') + } + match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity'] + if not any(str(parsed.get(field_id) or '').strip() for field_id in match_fields): + return None + for field_id, value in list(parsed.items()): + field = catalog.get(field_id) + if field is None: + continue + if field.value_type in {'integer', 'decimal'}: + parsed[field_id] = _parse_qty(value) + elif field.value_type == 'date': + parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip() + else: + parsed[field_id] = str(value).strip() + return parsed + idx_part_number = columns.get("part_number") if idx_part_number is None: idx_part_number = default_part_number_index @@ -227,11 +266,16 @@ def _normalize_inventory_row( odm_id = str(_cell(row, idx_odm) or "").strip() if odm_id: parsed["odm_id"] = odm_id + idx_warehouse = columns.get("warehouse_id") + if idx_warehouse is not None: + warehouse_id = str(_cell(row, idx_warehouse) or "").strip().upper() + if warehouse_id: + parsed["warehouse_id"] = warehouse_id return parsed def _score_header_candidate(cells: list[Any]) -> int: - """Score how likely a row is the inventory column header (not a title row).""" + """按通用表格结构给候选表头评分,固定库存词典只作为旧临时链加分项。""" headers = [str(c or "").strip() for c in cells] non_empty = [h for h in headers if h] if len(non_empty) < 2: @@ -244,7 +288,9 @@ def _score_header_candidate(cells: list[Any]) -> int: if mapped: mapped_fields.add(mapped) - score = len(mapped_fields) * 10 + text_cells = sum(1 for value in non_empty if isinstance(value, str) and str(value).strip()) + unique_cells = len({str(value).strip().casefold() for value in non_empty}) + score = len(non_empty) + text_cells + unique_cells + len(mapped_fields) * 10 if "part_number" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields): score += 30 return score @@ -262,8 +308,10 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40 return best_idx if best_score > 0 else 0 -def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]: - """Load worksheet or CSV rows; returns (rows, total_row_count_hint).""" +def _load_excel_rows( + path: Path, *, max_rows: int | None = None, sheet_name: str | None = None, +) -> tuple[list[list[Any]], int]: + """Load configured worksheet or CSV rows; returns rows and total row count hint.""" suffix = path.suffix.lower() if suffix == ".csv": from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows @@ -275,9 +323,32 @@ def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[l total = len(rows) return rows, int(total) + if suffix == ".xls": + import xlrd + + book = xlrd.open_workbook(filename=str(path), on_demand=True) + try: + if sheet_name: + try: + sheet = book.sheet_by_name(sheet_name) + except xlrd.biffh.XLRDError as exc: + raise ValueError(f'Inventory worksheet not found: {sheet_name}') from exc + else: + sheet = book.sheet_by_index(0) + row_limit = sheet.nrows if max_rows is None else min(sheet.nrows, max_rows) + rows = [ + [_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols)] + for row_index in range(row_limit) + ] + return rows, int(sheet.nrows) + finally: + book.release_resources() + wb = load_workbook(filename=str(path), data_only=True, read_only=True) try: - ws = wb.active + if sheet_name and sheet_name not in wb.sheetnames: + raise ValueError(f'Inventory worksheet not found: {sheet_name}') + ws = wb[sheet_name] if sheet_name else wb.active rows: list[list[Any]] = [] for i, row in enumerate(ws.iter_rows(values_only=True)): if max_rows is not None and i >= max_rows: @@ -289,6 +360,19 @@ def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[l return rows, int(total) +def _xls_cell_value(book: Any, cell: Any) -> Any: + """将 xlrd 单元格值规范为与 openpyxl 接近的 Python 值。""" + import xlrd + + if cell.ctype == xlrd.XL_CELL_EMPTY: + return None + if cell.ctype == xlrd.XL_CELL_DATE: + return xlrd.xldate_as_datetime(cell.value, book.datemode) + if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer(): + return int(cell.value) + return cell.value + + def _rows_from_table_text(raw_text: str) -> list[list[str]]: rows: list[list[str]] = [] for line in raw_text.splitlines(): @@ -315,10 +399,8 @@ def describe_inventory_columns( *, field_mapping: dict[str, str] | None = None, mapping_source: str = "rules", - llm_match_rule: str | None = None, - llm_match_key: list[str] | None = None, ) -> dict[str, Any]: - """生成库存列映射与匹配规则的可读描述,供字段对齐人审展示。""" + """根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。""" if field_mapping: from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping @@ -326,8 +408,6 @@ def describe_inventory_columns( headers, field_mapping, mapping_source=mapping_source, - llm_match_rule=llm_match_rule, - llm_match_key=llm_match_key, ) from app.services.shipping_notice.match_rule_desc import resolve_match_rule @@ -360,11 +440,7 @@ def describe_inventory_columns( if qty_source: inferred_mapping["available_qty"] = qty_source - match_rule, match_key, match_rule_source = resolve_match_rule( - inferred_mapping, - llm_match_rule=llm_match_rule, - llm_match_key=llm_match_key, - ) + match_rule, match_key, match_rule_source = resolve_match_rule(inferred_mapping) return { "headers": [str(h or "").strip() for h in headers], @@ -497,7 +573,9 @@ def parse_inventory_rows( else: col_map = _column_map() columns = _resolve_inventory_columns(headers, col_map) - has_header = columns["part_number"] is not None or columns["available_qty"] is not None or columns["qty"] is not None + has_header = any(index is not None for index in columns.values()) if field_mapping else ( + columns.get("part_number") is not None or columns.get("available_qty") is not None or columns.get("qty") is not None + ) if not has_header and headers and not field_mapping: has_header = any(_map_header(h, _column_map()) for h in headers) @@ -505,7 +583,7 @@ def parse_inventory_rows( for row in data_rows: if not row: continue - parsed = _normalize_inventory_row(list(row), columns) + parsed = _normalize_inventory_row(list(row), columns, configured_mapping=bool(field_mapping)) if parsed: lines.append(parsed) return lines @@ -540,7 +618,7 @@ def parse_inventory_text( else: col_map = _column_map() columns = _resolve_inventory_columns(header, col_map) - has_header = columns["part_number"] is not None or any(_map_header(h, col_map) for h in header) + has_header = columns.get("part_number") is not None or any(_map_header(h, col_map) for h in header) column_meta = describe_inventory_columns(header) if has_header else empty_meta data_rows: list[list[Any]] = rows[1:] if has_header else rows @@ -591,7 +669,6 @@ def read_inventory_schema_preview( "aws_part_number": "AWS Sku / AWS 料号(可选)", "reservation_id": "Reservation ID / COM ID(必填)", "available_qty": "可用数量 / Qty Available / Qty", - "match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)", }, "row_count_hint": data_row_count, } @@ -603,15 +680,14 @@ def parse_inventory_excel_with_meta( field_mapping: dict[str, str] | None = None, mapping_source: str = "rules", header_row_index: int | None = None, - llm_match_rule: str | None = None, - llm_match_key: list[str] | None = None, + sheet_name: str | None = None, ) -> tuple[list[dict[str, Any]], dict[str, Any]]: """ 解析库存 Excel 并返回标准化行与 column_meta。 - 核心逻辑:定位表头行 → describe_inventory_columns → parse_inventory_rows。 + 核心逻辑:选择工作表 → 定位表头行 → describe_inventory_columns → parse_inventory_rows。 """ - rows, _total = _load_excel_rows(path) + rows, _total = _load_excel_rows(path, sheet_name=sheet_name) if not rows: return [], {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]} @@ -640,10 +716,9 @@ def parse_inventory_excel_with_meta( headers, field_mapping=field_mapping, mapping_source=mapping_source if field_mapping else "rules", - llm_match_rule=llm_match_rule, - llm_match_key=llm_match_key, ) meta["header_row_index"] = header_idx + 1 + meta["sheet_name"] = sheet_name return lines, meta @@ -659,6 +734,8 @@ def ingest_inventory_file( move_to: Path | None = None, field_mapping: dict[str, str] | None = None, mapping_source: str = "rules", + header_row_index: int | None = None, + sheet_name: str | None = None, ) -> tuple[list[dict[str, Any]], dict[str, Any]]: """ 解析库存文件并可选择移动至 processed 目录(RPA drop 摄入用)。 @@ -670,6 +747,8 @@ def ingest_inventory_file( source_path, field_mapping=field_mapping, mapping_source=mapping_source, + header_row_index=header_row_index, + sheet_name=sheet_name, ) if move_to: move_to.mkdir(parents=True, exist_ok=True) diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index ee60dc82..973abbb4 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -71,33 +71,23 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = def find_latest_ready_snapshot( source_code: str | None, - site_id: str | None, warehouse_id: str | None = None, ) -> ShippingInventoryFile | None: """ - 查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。 - 核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。 + 查找指定 Source 的最新 ready 且未过期库存快照。 + 核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。 """ code = str(source_code or "").strip().upper() - site = str(site_id or "").strip().upper() warehouse = str(warehouse_id or "").strip().upper() if not code: return None - if not site and not warehouse: - return None query = ShippingInventoryFile.query.filter_by( source_code=code, snapshot_status=_SNAPSHOT_STATUS_READY, ) - if site: - query = query.filter_by(site_id=site) if warehouse: query = query.filter_by(warehouse_id=warehouse) - elif site: - query = query.filter( - (ShippingInventoryFile.warehouse_id.is_(None)) | (ShippingInventoryFile.warehouse_id == "") - ) rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all() for row in rows: @@ -110,24 +100,21 @@ def find_ready_rpa_inventory_snapshot( *, rpa_run_no: str, source_code: str, - site_id: str, warehouse_id: str, ) -> ShippingInventoryFile | None: """ - 按 RPA 轮次 + 四字段身份查找已入库 ready 快照。 + 按 RPA 轮次 + Source/Warehouse 身份查找已入库 ready 快照。 核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。 """ run_no = str(rpa_run_no or "").strip() code = str(source_code or "").strip().upper() - site = str(site_id or "").strip().upper() warehouse = str(warehouse_id or "").strip().upper() - if not run_no or not code or not site or not warehouse: + if not run_no or not code or not warehouse: return None return ( ShippingInventoryFile.query.filter_by( rpa_run_no=run_no, source_code=code, - site_id=site, warehouse_id=warehouse, snapshot_status=_SNAPSHOT_STATUS_READY, ) @@ -162,13 +149,11 @@ def get_or_create_rpa_inventory_snapshot( run_no = str(rpa_run_no or "").strip() code = str(source.get("source_code") or "").strip().upper() - site = str(source.get("site_id") or "").strip().upper() warehouse = str(verify_warehouse_id or source.get("warehouse_id") or "").strip().upper() - if run_no and code and site and warehouse: + if run_no and code and warehouse: existing = find_ready_rpa_inventory_snapshot( rpa_run_no=run_no, source_code=code, - site_id=site, warehouse_id=warehouse, ) if existing: @@ -202,11 +187,10 @@ def get_or_create_rpa_inventory_snapshot( from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path delete_inventory_storage_path(orphan_storage_path) - if run_no and code and site and warehouse: + if run_no and code and warehouse: existing = find_ready_rpa_inventory_snapshot( rpa_run_no=run_no, source_code=code, - site_id=site, warehouse_id=warehouse, ) if existing: @@ -291,12 +275,11 @@ def create_inventory_snapshot_from_rpa( exported_at = datetime.utcnow() inventory_file_no = generate_inventory_file_no() source_code = str(source.get("source_code") or "").strip().upper() - configured_site_id = str(source.get("site_id") or "").strip().upper() export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper() runtime_identity_applied = bool(source.get("_runtime_identity_applied")) excel_warehouse_id = "" warehouse_id = export_warehouse_id - warehouse_code = warehouse_id or configured_site_id + warehouse_code = warehouse_id excel_verified = False if success: @@ -334,7 +317,7 @@ def create_inventory_snapshot_from_rpa( snapshot_status = _SNAPSHOT_STATUS_FAILED storage_path = str(path) if path and path.is_file() else "" - from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version + from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version inv_file = ShippingInventoryFile( inventory_file_no=inventory_file_no, @@ -345,10 +328,10 @@ def create_inventory_snapshot_from_rpa( schema_preview_json=preview, share_mode=share_mode or ("task_only" if trigger_type in {"on_demand", "manual_upload"} else "warehouse_pool"), line_count=0, + # 动态 Source 的文件可含多个 Warehouse;具体 Warehouse 在 link 时从库存行解析。 warehouse_id=warehouse_id or None, warehouse_code=warehouse_code or None, - site_id=configured_site_id or None, - source_config_version=get_inventory_sources_config_version(), + source_config_version=inventory_sources_runtime_version(), identity_status="pending" if success else "unknown", source_code=source_code or None, source_type=str(source.get("connector_type") or "").strip() or None, @@ -361,7 +344,6 @@ def create_inventory_snapshot_from_rpa( "query": source.get("query"), "navigation": source.get("navigation"), "parameters": source.get("parameters"), - "site_id": configured_site_id or None, "export_warehouse_id": export_warehouse_id, "excel_warehouse_id": excel_warehouse_id or None, "warehouse_id_source": ( @@ -419,6 +401,32 @@ def link_snapshot_to_task( if not is_snapshot_fresh(inv_file): return None + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + + source = get_database_inventory_source(task.inventory_source_code) + if source is None: + return None + resolved_warehouse_id = inv_file.warehouse_id + if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match': + from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse + + lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)] + if not lines and Path(inv_file.storage_path).is_file(): + from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file + + lines, _column_meta = parse_inventory_snapshot_file(inv_file) + inv_file.inventory_lines_json = lines + inv_file.line_count = len(lines) + resolution = resolve_dynamic_warehouse( + task=task, + inventory_lines=lines, + fallback_warehouse_id=inv_file.warehouse_id, + ) + if not resolution.warehouse_id: + inv_file.identity_status = resolution.reason + return None + resolved_warehouse_id = resolution.warehouse_id + age_seconds: int | None = None if inv_file.exported_at: age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0) @@ -428,25 +436,27 @@ def link_snapshot_to_task( identity_ok = inventory_identities_match( task, source_code=inv_file.source_code, - site_id=inv_file.site_id, - warehouse_id=inv_file.warehouse_id, + warehouse_id=resolved_warehouse_id, ) inv_file.identity_status = "verified" if identity_ok else "mismatch" if not identity_ok: return None + # 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。 + if not task.inventory_warehouse_id: + task.inventory_warehouse_id = resolved_warehouse_id + link = replace_task_inventory_link(task, inv_file, role=role) link.link_reason = reason - link.matched_warehouse_id = inv_file.warehouse_id + link.matched_warehouse_id = resolved_warehouse_id link.matched_source_code = inv_file.source_code - link.matched_site_id = inv_file.site_id link.identity_check_status = "verified" if identity_ok else "mismatch" link.identity_checked_at = datetime.utcnow() link.snapshot_age_seconds = age_seconds link.audit_payload_json = { **(audit_payload or {}), "source_code": inv_file.source_code, - "warehouse_id": inv_file.warehouse_id, + "warehouse_id": resolved_warehouse_id, "exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None, "expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None, "inventory_file_no": inv_file.inventory_file_no, @@ -461,6 +471,7 @@ def link_snapshot_to_task( "inventory_file_no": inv_file.inventory_file_no, "link_reason": reason, "snapshot_age_seconds": age_seconds, + "warehouse_id": resolved_warehouse_id, **(audit_payload or {}), }, ) @@ -484,7 +495,7 @@ def serialize_inventory_snapshot_link(task: ShippingTask) -> dict[str, Any] | No return { "inventory_file_no": inv_file.inventory_file_no, "source_code": inv_file.source_code, - "warehouse_id": inv_file.warehouse_id, + "warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id, "warehouse_code": inv_file.warehouse_code, "exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None, "expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at 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 682cd81f..ecc1cce9 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -2,7 +2,7 @@ services/shipping_notice/inventory_source_gate.py 用途:库存源稳定性门禁、独立字段写入与路由指纹管理。 -依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。 +依赖:inventory_source_rules、inventory_source_repository、models.ShippingTask、core.errors。 逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review; RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。 """ @@ -14,15 +14,18 @@ from typing import Any from app.core.errors import AppError from app.models import ShippingTask -from app.services.shipping_notice.inventory_source_identity import identity_matches_config from app.services.shipping_notice.inventory_source_rules import ( InventorySourceAdjudication, adjudicate_inventory_source, confirm_inventory_source_by_code, compute_routing_fingerprint, extract_routing_context, + resolve_ambiguous_source_from_ready_snapshots, +) +from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"}) @@ -40,9 +43,9 @@ INVENTORY_SOURCE_ERROR_CODES = { def _inventory_source_config_current(task: ShippingTask) -> bool: - """任务上记录的库存源配置版本须与当前 YAML 版本一致。""" + """任务上记录的库存源配置版本须与当前数据库版本一致。""" stored = str(task.inventory_source_config_version or "").strip() - current = get_inventory_sources_config_version() + current = inventory_sources_runtime_version() if not stored: return False return stored == current @@ -51,7 +54,7 @@ def _inventory_source_config_current(task: ShippingTask) -> bool: def is_inventory_source_stable(task: ShippingTask) -> bool: """ 判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。 - 核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。 + 核心逻辑:Source、Driver 与数据库配置一致即可稳定;动态 Warehouse 在库存行匹配后再确定。 """ status = str(task.inventory_source_status or "").strip() if status not in STABLE_INVENTORY_SOURCE_STATUSES: @@ -64,22 +67,16 @@ def is_inventory_source_stable(task: ShippingTask) -> bool: connector_type = str(task.inventory_connector_type or "").strip() if not connector_type: return False - source = get_inventory_source(code) + source = get_database_inventory_source(code) if not source: return False if connector_type != str(source.get("connector_type") or "").strip(): return False - site_id = str(task.inventory_site_id or "").strip().upper() - task_wh = str(task.inventory_warehouse_id or "").strip().upper() - if not site_id or not task_wh: - return False - if not identity_matches_config( - source, - site_id=site_id, - warehouse_id=task_wh, - context=extract_routing_context(task), - ): + mode = str(source.get('warehouse_resolution_mode') or '').strip().lower() + fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper() + task_warehouse = str(task.inventory_warehouse_id or '').strip().upper() + if mode == 'fixed' and task_warehouse != fixed_warehouse: return False fingerprint = str(task.inventory_routing_fingerprint or "").strip() @@ -105,7 +102,7 @@ def inventory_source_config_changed(task: ShippingTask) -> bool: stored = str(task.inventory_source_config_version or "").strip() if not stored: return bool(str(task.inventory_source_status or "").strip()) - return stored != get_inventory_sources_config_version() + return stored != inventory_sources_runtime_version() def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None: @@ -136,7 +133,6 @@ def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudic method=str(task.inventory_source_method or "").strip() or None, source_code=str(task.inventory_source_code or "").strip().upper() 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, routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip() @@ -162,12 +158,11 @@ def apply_inventory_source_adjudication( task.inventory_source_status = adjudication.status task.inventory_source_method = adjudication.method or None - task.inventory_source_config_version = adjudication.config_version or get_inventory_sources_config_version() + task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version() if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: task.inventory_source_code = adjudication.source_code 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: task.inventory_source_confirmed_by = confirmed_by_user_id @@ -175,7 +170,6 @@ def apply_inventory_source_adjudication( elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES: task.inventory_source_code = None task.inventory_connector_type = None - task.inventory_site_id = None task.inventory_warehouse_id = None payload = dict(task.step_payload_json or {}) payload.pop("rpa_inventory_source", None) @@ -194,9 +188,9 @@ def apply_inventory_source_adjudication( "routing_fingerprint": fingerprint, } if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code: - from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source + from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source - rpa_source = build_task_rpa_inventory_source(task) + rpa_source = task_rpa_inventory_source(task) if rpa_source: payload["rpa_inventory_source"] = rpa_source else: @@ -222,6 +216,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource return _adjudication_from_stable_task(task) adjudication = adjudicate_inventory_source(task) + # Multiple routing candidates may be resolved only from already-exported + # snapshots; this never starts RPA or uses inventory quantity as a signal. + adjudication = resolve_ambiguous_source_from_ready_snapshots(task, adjudication) if ( str(task.inventory_source_status or "").strip() == "user_confirmed" and adjudication.status == "resolved" @@ -234,7 +231,6 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource method="user_confirmed", source_code=adjudication.source_code, connector_type=adjudication.connector_type, - site_id=adjudication.site_id, warehouse_id=adjudication.warehouse_id, config_version=adjudication.config_version, routing_fingerprint=adjudication.routing_fingerprint, @@ -247,35 +243,17 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource return adjudication -def task_needs_parse_review(task: ShippingTask) -> bool: - """ - 判断任务是否仍需完成低置信度解析人工确认。 - - 核心逻辑:仅认显式标记——review/pending 为 parse_review / low_confidence, - 或存量 pending_parse_review_after_source。禁止仅凭 parse_confidence 兜底, - 否则「解析已确认 → 再确认库存源」会被误判回解析复核。 - """ - from app.services.shipping_notice.constants import PH_LOW_CONF, RS_PARSE_REVIEW - - if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF: - return True - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - return bool(payload.get("pending_parse_review_after_source")) - - def transition_task_to_inventory_source_review( task: ShippingTask, adjudication: InventorySourceAdjudication, *, error_message: str | None = None, - mark_pending_parse_review: bool = False, ) -> None: """ 将任务持久化到库存源人工复核检查点,并写入候选裁决信息。 核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。 - mark_pending_parse_review 仅用于存量/兼容路径(旧顺序先源后解析); - 新路径应先完成 parse_review,再进入本检查点,通常不传 True。 + 解析复核必须在进入本检查点前完成,不保存延后复核标记。 """ from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -294,8 +272,6 @@ def transition_task_to_inventory_source_review( "config_version": adjudication.config_version, "routing_fingerprint": adjudication.routing_fingerprint, } - if mark_pending_parse_review: - payload["pending_parse_review_after_source"] = True task.step_payload_json = payload @@ -304,16 +280,11 @@ def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceA 对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。 【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。 - 核心逻辑:新业务顺序是先解析后库存源;仅当仍检测到待解析复核(含存量延后标记)时, - 才写入 pending_parse_review_after_source 以兼容旧任务。 + 核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源确认。 """ adjudication = adjudicate_and_apply_inventory_source(task) if not is_inventory_source_stable(task): - transition_task_to_inventory_source_review( - task, - adjudication, - mark_pending_parse_review=task_needs_parse_review(task), - ) + transition_task_to_inventory_source_review(task, adjudication) return adjudication @@ -372,7 +343,6 @@ def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]: """返回任务当前正式库存身份,供库存文件绑定与匹配校验。""" return { "inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None, - "inventory_site_id": str(task.inventory_site_id or "").strip().upper() or None, "inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None, } @@ -381,10 +351,9 @@ def inventory_identities_match( task: ShippingTask, *, source_code: str | None, - site_id: str | None, warehouse_id: str | None, ) -> bool: - """校验库存文件/链接身份与任务正式库存源是否完全一致。""" + """校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。""" identity = task_inventory_identity(task) if not is_inventory_source_stable(task): return False @@ -392,11 +361,8 @@ def inventory_identities_match( if expected_code != identity["inventory_source_code"]: return False - file_site = str(site_id or "").strip().upper() file_wh = str(warehouse_id or "").strip().upper() - if not file_site or file_site != (identity["inventory_site_id"] or ""): + if not file_wh: return False - if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""): - return False - - return True + expected = identity['inventory_warehouse_id'] + return not expected or expected == file_wh diff --git a/backend/app/services/shipping_notice/inventory_source_identity.py b/backend/app/services/shipping_notice/inventory_source_identity.py index 34677086..df52a012 100644 --- a/backend/app/services/shipping_notice/inventory_source_identity.py +++ b/backend/app/services/shipping_notice/inventory_source_identity.py @@ -1,9 +1,9 @@ """ services/shipping_notice/inventory_source_identity.py -用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。 -依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。 -逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。 +用途:校验库存源与 Warehouse 的两段式身份。 +依赖:无业务模块反向依赖。 +逻辑:路由阶段只确定 Source;fixed Source 立即确定 Warehouse,inventory_match Source 在库存行匹配后确定。 """ from __future__ import annotations @@ -14,143 +14,52 @@ from typing import Any def normalize_destination(value: Any) -> str: - """将 Dify/单据中的目的地线索标准化成可匹配 token。""" - text = str(value or "").strip().upper() - if not text: - return "" - return re.sub(r"[^A-Z0-9]+", " ", text).strip() + """将文本归一为可比较的路由 token。""" + return re.sub(r"[^A-Z0-9]+", " ", str(value or "").strip().upper()).strip() def _matches_alias(candidate: str, alias: str) -> bool: - """别名按词元匹配,避免短 token 误命中更长编码。""" - return _alias_token_match(normalize_destination(candidate), alias) + """按完整词元匹配别名,避免短码误命中。""" + normalized = normalize_destination(alias) + return bool(normalized) and (normalize_destination(candidate) == normalized or normalized in normalize_destination(candidate).split()) @dataclass(frozen=True) class ResolvedInventoryIdentity: - """稳定库存源四元组中的站点/库位解析结果。""" + """已确定的 Source 与可选 Warehouse 身份。""" source_code: str connector_type: str - site_id: str - warehouse_id: str + warehouse_id: str | None @dataclass(frozen=True) class InventoryIdentityResolution: - """身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。""" + """身份解析结果;动态 Warehouse 在路由阶段可合法为空。""" ok: bool identity: ResolvedInventoryIdentity | None = None reason: str = "" - warehouse_candidates: tuple[str, ...] = () -def _alias_token_match(candidate: str, alias: str) -> bool: - """库位别名按词元精确匹配,禁止短别名误命中长编码。""" - alias_norm = normalize_destination(alias) - if not alias_norm: +def resolve_inventory_source_identity(source: dict[str, Any], _context: dict[str, Any]) -> InventoryIdentityResolution: + """解析 Source;仅 fixed 模式从配置直接提供 Warehouse。""" + code = str(source.get('source_code') or '').strip().upper() + connector = str(source.get('connector_type') or '').strip().lower() + mode = str(source.get('warehouse_resolution_mode') or '').strip().lower() + if not code or connector not in {'dbs', 'crane'} or mode not in {'fixed', 'inventory_match'}: + return InventoryIdentityResolution(False, reason='source_incomplete') + warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper() or None + if mode == 'fixed' and not warehouse: + return InventoryIdentityResolution(False, reason='fixed_warehouse_missing') + return InventoryIdentityResolution(True, ResolvedInventoryIdentity(code, connector, warehouse)) + + +def identity_matches_config(source: dict[str, Any], *, warehouse_id: str | None, context: dict[str, Any] | None = None) -> bool: + """验证任务 Warehouse 与 Source 策略一致;动态仓由已匹配库存行决定。""" + resolution = resolve_inventory_source_identity(source, context or {}) + if not resolution.ok or not resolution.identity: return False - if candidate == alias_norm: - return True - return alias_norm in candidate.split() - - -def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) -> InventoryIdentityResolution: - """Crane 库位由订单线索与 match_aliases 唯一命中决定。""" - aliases = [str(alias).strip() for alias in (source.get("match_aliases") or []) if str(alias).strip()] - if not aliases: - return InventoryIdentityResolution(ok=False, reason="crane_aliases_missing") - - destination_candidates = list(context.get("destination_candidates") or []) - hint = normalize_destination(context.get("warehouse_hint")) - if hint: - destination_candidates.append(hint) - - matched: list[str] = [] - for candidate in destination_candidates: - candidate_norm = normalize_destination(candidate) - if not candidate_norm: - continue - for alias in aliases: - if _alias_token_match(candidate_norm, alias): - token = str(alias).strip().upper() - if token and token not in matched: - matched.append(token) - - if len(matched) == 1: - site_id = str(source.get("site_id") or "CRANE").strip().upper() - return InventoryIdentityResolution( - ok=True, - identity=ResolvedInventoryIdentity( - source_code=str(source.get("source_code") or "").strip().upper(), - connector_type=str(source.get("connector_type") or "").strip(), - site_id=site_id, - warehouse_id=matched[0], - ), - ) - if len(matched) > 1: - return InventoryIdentityResolution( - ok=False, - reason="crane_warehouse_ambiguous", - warehouse_candidates=tuple(matched), - ) - return InventoryIdentityResolution(ok=False, reason="crane_warehouse_unresolved") - - -def resolve_inventory_source_identity( - source: dict[str, Any], - context: dict[str, Any], -) -> InventoryIdentityResolution: - """ - 解析库存源在订单上下文下的正式 site_id / warehouse_id。 - 核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。 - """ - source_code = str(source.get("source_code") or "").strip().upper() - 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 connector_type == "crane_footprint": - return _resolve_crane_warehouse_id(source, context) - - site_id = str(source.get("site_id") or "").strip().upper() - warehouse_id = str(source.get("warehouse_id") or "").strip().upper() - if not site_id or not warehouse_id: - return InventoryIdentityResolution(ok=False, reason="identity_incomplete") - return InventoryIdentityResolution( - ok=True, - identity=ResolvedInventoryIdentity( - source_code=source_code, - connector_type=connector_type, - site_id=site_id, - warehouse_id=warehouse_id, - ), - ) - - -def identity_matches_config( - source: dict[str, Any], - *, - site_id: str | None, - warehouse_id: str | None, - context: dict[str, Any] | None = None, -) -> bool: - """校验任务身份与配置一致;Crane 额外要求库位与当前路由上下文唯一解析结果一致。""" - cfg_site = str(source.get("site_id") or "").strip().upper() - cfg_wh = str(source.get("warehouse_id") or "").strip().upper() - task_site = str(site_id or "").strip().upper() - task_wh = str(warehouse_id or "").strip().upper() - if not task_site or not task_wh: - return False - if cfg_site and task_site != cfg_site: - return False - 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) - if not resolution.ok or not resolution.identity: - return False - return resolution.identity.warehouse_id == task_wh - return bool(cfg_wh) and task_wh == cfg_wh + expected = resolution.identity.warehouse_id + actual = str(warehouse_id or '').strip().upper() or None + return bool(actual) and (expected is None or expected == actual) diff --git a/backend/app/services/shipping_notice/inventory_source_repository.py b/backend/app/services/shipping_notice/inventory_source_repository.py new file mode 100644 index 00000000..18319b8d --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_source_repository.py @@ -0,0 +1,148 @@ +""" +services/shipping_notice/inventory_source_repository.py + +用途:提供库存源主数据的最小一致性校验和受控读取入口。 +依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。 +逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。 +""" + +from __future__ import annotations + +from app.core.errors import ValidationError +from app.models import ShippingInventorySource, ShippingRpaProfile + + +def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None: + """ + 校验库存源引用的 RPA Profile 与其 Driver 类型一致。 + + Args: + source: 待保存的库存源;connector_type 只能为 dbs 或 crane。 + profile: Source 绑定的 RPA Profile。 + + Raises: + ValidationError: Source/Profile Driver 不一致或出现未知 Driver。 + """ + source_type = str(source.connector_type or '').strip().lower() + profile_type = str(profile.connector_type or '').strip().lower() + if source_type not in {'dbs', 'crane'} or profile_type not in {'dbs', 'crane'}: + raise ValidationError('Unsupported inventory connector type', code='SHIPPING.INVENTORY_CONNECTOR_INVALID') + if source_type != profile_type: + raise ValidationError( + 'Inventory Source connector_type must match its RPA Profile', + code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH', + ) + + +def get_database_inventory_source(source_code: str, *, enabled_only: bool = True) -> dict | None: + """ + 按业务编码读取数据库库存源及其非敏感 RPA 配置。 + + Args: + source_code: 稳定库存源编码。 + enabled_only: 为 True 时仅返回启用 Source 和 Profile。 + + Returns: + dict | None: 不含任何凭据密文/明文的 Source、Profile 与操作配置快照。 + """ + code = str(source_code or '').strip().upper() + if not code: + return None + source = ShippingInventorySource.query.filter_by(source_code=code).first() + if source is None or (enabled_only and not source.enabled): + return None + profile = source.rpa_profile + if profile is None or (enabled_only and not profile.enabled): + return None + login_config = dict(profile.login_config_json or {'auth_mode': 'password'}) + if login_config.get('auth_mode') != 'password': + return None + # Source owns report navigation and business query values. Driver behavior is + # code/template-owned and never travels through a login connection profile. + source_navigation = dict(source.report_path_json or {}) if source.connector_type == 'dbs' else {} + return { + 'source_code': source.source_code, + 'display_name': source.display_name, + 'connector_type': source.connector_type, + 'warehouse_resolution_mode': source.warehouse_resolution_mode, + 'fixed_warehouse_id': source.fixed_warehouse_id, + # Worker 兼容字段:fixed Source 可直接作为导出目标;动态 Source 保持为空。 + 'warehouse_id': source.fixed_warehouse_id, + 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, + 'config_version': source.config_version, + 'parsing_profile_id': source.parsing_profile_id, + 'excel_template_id': source.excel_template_id, + 'report_path_json': dict(source.report_path_json or {}), + 'query_parameters_json': list(source.query_parameters_json or []), + 'match_aliases_json': list(source.match_aliases_json or []), + 'rpa_profile_code': profile.profile_code, + # 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。 + 'navigation': source_navigation, + 'parameters': list(source.query_parameters_json or []), + 'query': {}, + 'login_url': profile.login_url, + 'login_config': login_config, + } + + +def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = True) -> dict | None: + """构造仅投递给 RPA worker 的 Source 快照;配置测试可显式读取停用站点。""" + source_config = get_database_inventory_source(source_code, enabled_only=enabled_only) + if source_config is None: + return None + source = ShippingInventorySource.query.filter_by(source_code=source_config['source_code']).first() + profile = source.rpa_profile if source else None + if profile is None or (enabled_only and not profile.enabled): + return None + result = dict(source_config) + result['credential_envelope'] = { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + } + return result + + +def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]: + """列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。""" + query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code) + if enabled_only: + query = query.filter_by(enabled=True) + result = [] + for source in query.all(): + item = get_database_inventory_source(source.source_code, enabled_only=enabled_only) + if item: + result.append(item) + return result + + +def inventory_sources_runtime_version() -> str: + """计算启用库存源与其 Profile 配置的稳定版本,用于任务路由失效判断。""" + import hashlib + import json + + rows = [] + for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all(): + profile = source.rpa_profile + rows.append({ + 'source_code': source.source_code, + 'source_version': source.config_version, + 'source_enabled': bool(source.enabled), + 'profile_code': profile.profile_code if profile else None, + 'profile_version': profile.config_version if profile else None, + 'profile_enabled': bool(profile.enabled) if profile else False, + 'source_config': { + 'connector_type': source.connector_type, + 'warehouse_resolution_mode': source.warehouse_resolution_mode, + 'fixed_warehouse_id': source.fixed_warehouse_id, + 'report_path_json': source.report_path_json or {}, + 'query_parameters_json': source.query_parameters_json or [], + 'match_aliases_json': source.match_aliases_json or [], + 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, + }, + 'profile_config': { + 'login_url': profile.login_url if profile else None, + 'login_config': profile.login_config_json if profile else None, + }, + }) + payload = json.dumps(rows, ensure_ascii=True, sort_keys=True, separators=(',', ':')) + return hashlib.sha256(payload.encode('ascii')).hexdigest()[:16] diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/inventory_source_rules.py index 278e345a..cd8aff71 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/inventory_source_rules.py @@ -1,42 +1,38 @@ """ services/shipping_notice/inventory_source_rules.py -用途:根据发货通知路由线索对库存源做确定性裁决。 -依赖:inventory_sources、ShippingTask 目的地字段、task_line_store、step_payload_json。 -逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核; - 订单行路由线索经 read_task_order_lines 读取。 +用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。 +依赖:inventory_routing_engine、inventory_source_repository、task_line_store。 +逻辑:规则只决定 Source;fixed Warehouse 由 Source 给出,inventory_match Warehouse 延后到库存行匹配。 """ from __future__ import annotations import hashlib import json -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace +from pathlib import Path from typing import Any from app.models import ShippingTask -from app.services.shipping_notice.inventory_source_identity import ( - normalize_destination, - resolve_inventory_source_identity, -) -from app.services.shipping_notice.inventory_sources import ( - build_rpa_inventory_source, - get_inventory_source, - get_inventory_sources_config_version, - list_inventory_sources, +from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules +from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity +from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, + list_database_inventory_sources, ) from app.services.shipping_notice.task_line_store import read_task_order_lines @dataclass(frozen=True) class InventorySourceAdjudication: - """库存源裁决结构化结果。""" + """库存源裁决结果;Warehouse 在动态模式下可为空。""" status: str method: str | None = None source_code: str | None = None connector_type: str | None = None - site_id: str | None = None warehouse_id: str | None = None config_version: str | None = None routing_fingerprint: str | None = None @@ -44,501 +40,230 @@ class InventorySourceAdjudication: destination_candidates: list[str] = field(default_factory=list) evidence: list[dict[str, Any]] = field(default_factory=list) conflicts: list[str] = field(default_factory=list) - reason: str = "" + reason: str = '' -# Backward-compatible alias InventorySourceResolution = InventorySourceAdjudication -def compute_routing_fingerprint(context: dict[str, Any]) -> str: - """ - 根据标准化路由上下文与配置版本生成可比较指纹。 - 核心逻辑:相同输入与相同配置版本下指纹必须稳定,用于判断人工确认是否失效。 - """ - normalized = { - "destination_code": str(context.get("destination_code") or "").strip().upper(), - "destination_city": str(context.get("destination_city") or "").strip().upper(), - "destination_country": str(context.get("destination_country") or "").strip().upper(), - "warehouse_hint": str(context.get("warehouse_hint") or "").strip().upper(), - "customer_code": str(context.get("customer_code") or "").strip().upper(), - "customer_name": str(context.get("customer_name") or "").strip().upper(), - "order_type": str(context.get("order_type") or "").strip().upper(), - "config_version": get_inventory_sources_config_version(), - "destination_candidates": sorted( - str(item).strip().upper() - for item in (context.get("destination_candidates") or []) - if str(item).strip() - ), - } - digest = hashlib.sha256(json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode("utf-8")) - return digest.hexdigest()[:32] - - -def normalize_destination(value: Any) -> str: - """将 Dify/单据中的目的地线索标准化成可匹配 token。""" - from app.services.shipping_notice.inventory_source_identity import normalize_destination as _normalize - - return _normalize(value) - - -def _matches_alias(candidate: str, alias: str) -> bool: - from app.services.shipping_notice.inventory_source_identity import _matches_alias as _match - - return _match(candidate, alias) - - -def _append_candidate(candidates: list[str], value: Any) -> None: - text = normalize_destination(value) - if text and text not in candidates: - candidates.append(text) - - -def _extract_destination_object(candidates: list[str], value: Any) -> None: - if not isinstance(value, dict): - _append_candidate(candidates, value) - return - for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text", "destination_code"): - _append_candidate(candidates, value.get(key)) - - -def extract_destination_candidates(task: ShippingTask) -> list[str]: - """ - 从任务解析结果提取目的地/港口/仓库候选。 - 【AI 触发时机】:订单解析后由裁决服务调用,行级 inventory_source_hint 与目的地字段都作为候选证据。 - - 核心逻辑:只读取 orders[].lines[].inventory_source_hint,禁止使用 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 {} - for item in payload.get("destination_candidates") or []: - _append_candidate(candidates, item) - _extract_destination_object(candidates, payload.get("destination")) - _append_candidate(candidates, task.ship_to) - _append_candidate(candidates, task.destination_code) - _append_candidate(candidates, task.destination_city) - _append_candidate(candidates, task.destination_country) - _append_candidate(candidates, task.warehouse_hint) - for line in read_task_order_lines(task): - _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("inventory_source_hint")) - return candidates - - def extract_routing_context(task: ShippingTask) -> dict[str, Any]: - """将任务解析结果标准化为库存路由上下文。""" + """投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。""" payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - destination = payload.get("destination") if isinstance(payload.get("destination"), dict) else {} return { - "destination_code": task.destination_code or destination.get("port_code") or destination.get("destination_code"), - "destination_city": task.destination_city or destination.get("city"), - "destination_country": task.destination_country or destination.get("country"), - "warehouse_hint": task.warehouse_hint or destination.get("warehouse_hint"), - "customer_code": task.customer_code, - "customer_name": task.customer_name, - "order_type": payload.get("order_type"), - "destination_candidates": extract_destination_candidates(task), + 'destination_code': task.destination_code, + 'destination_city': task.destination_city, + 'destination_country': task.destination_country, + 'warehouse_hint': task.warehouse_hint, + 'customer_code': task.customer_code, + 'customer_name': task.customer_name, + 'order_type': payload.get('order_type'), + 'destination_candidates': [], } -def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]: - """人工确认候选项展示字段;前端必须提交 source_code。""" +def compute_routing_fingerprint(context: dict[str, Any]) -> str: + """按路由事实和数据库配置版本生成稳定指纹。""" + payload = {'context': context, 'config_version': inventory_sources_runtime_version()} + return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=True, default=str).encode('ascii')).hexdigest()[:32] + + +def _candidate(source: dict[str, Any]) -> dict[str, Any]: + """构造不泄露凭据的人工确认候选。""" return { - "source_code": source.get("source_code"), - "display_name": source.get("display_name"), - "site_id": source.get("site_id"), - "warehouse_id": source.get("warehouse_id"), - "connector_type": source.get("connector_type"), - "match_score": score, - "matched_by": matched_by, + 'source_code': source['source_code'], + 'display_name': source['display_name'], + 'connector_type': source['connector_type'], + 'warehouse_resolution_mode': source['warehouse_resolution_mode'], + 'fixed_warehouse_id': source['fixed_warehouse_id'], } -def _normalize_token_list(values: Any) -> list[str]: - if not isinstance(values, list): - return [] - return [normalize_destination(item) for item in values if normalize_destination(item)] - - -def _all_enabled_source_candidates() -> list[dict[str, Any]]: - """返回全部启用库存源候选项,供未命中时人工选择。""" - return [ - _candidate_summary(source) - for source in list_inventory_sources() - if source.get("enabled", True) is not False - ] - - -def _source_matches_destination(source: dict[str, Any], destination_candidates: list[str]) -> bool: - """判断库存源别名是否与订单目的地线索有交集。""" - aliases = list(source.get("match_aliases") or []) - match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} - aliases.extend(_normalize_token_list(match_cfg.get("aliases"))) - if not aliases: - return False - return any(_matches_alias(candidate, alias) for candidate in destination_candidates for alias in aliases) - - -def _source_field_excluded(source: dict[str, Any], context: dict[str, Any]) -> bool: - """显式 match 规则已声明但订单字段未命中时,排除该库存源。""" - match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} - for field_name, cfg_key in ( - ("destination_code", "destination_codes"), - ("customer_code", "customers"), - ("order_type", "order_types"), - ("warehouse_hint", "warehouse_hints"), - ): - field_value = normalize_destination(context.get(field_name)) - allowed = _normalize_token_list(match_cfg.get(cfg_key)) - if allowed and field_value: - if not ( - field_value in allowed - or any(field_value in item or item in field_value for item in allowed) - ): - return True - return False - - -def _detect_rule_conflicts( - matches: list[tuple[int, dict[str, Any], list[dict[str, Any]]]], - context: dict[str, Any], -) -> list[str]: - """多候选同分时,检测不同来源对同一订单字段给出互斥规则命中。""" - conflicts: list[str] = [] - field_hits: dict[str, set[str]] = {} - for _, source, _ in matches: - match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} - for field_name, cfg_key in ( - ("destination_code", "destination_codes"), - ("customer_code", "customers"), - ("order_type", "order_types"), - ("warehouse_hint", "warehouse_hints"), - ): - field_value = normalize_destination(context.get(field_name)) - allowed = _normalize_token_list(match_cfg.get(cfg_key)) - if not allowed or not field_value: - continue - hits = { - item - for item in allowed - if field_value in item or item in field_value or field_value == item - } - if hits: - field_hits.setdefault(field_name, set()).update(hits) - for field_name, hits in field_hits.items(): - if len(hits) > 1: - conflicts.append(f"{field_name}_rule_conflict") - return conflicts - - -def _source_match_score(source: dict[str, Any], context: dict[str, Any], destination_candidates: list[str]) -> tuple[int, list[dict[str, Any]]]: - """按配置 match 规则与 match_aliases 计算命中分数与证据。""" - score = 0 - evidence: list[dict[str, Any]] = [] - match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {} - - for field_name, cfg_key in ( - ("destination_code", "destination_codes"), - ("customer_code", "customers"), - ("order_type", "order_types"), - ("warehouse_hint", "warehouse_hints"), - ): - field_value = normalize_destination(context.get(field_name)) - allowed = _normalize_token_list(match_cfg.get(cfg_key)) - if allowed and field_value: - if field_value in allowed or any(field_value in item or item in field_value for item in allowed): - score += 10 - evidence.append({"field": field_name, "value": field_value, "rule": cfg_key}) - - aliases = list(source.get("match_aliases") or []) + _normalize_token_list(match_cfg.get("aliases")) - for candidate in destination_candidates: - for alias in aliases: - if _matches_alias(candidate, alias): - score += 5 - evidence.append({"field": "destination_candidate", "value": candidate, "alias": alias}) - break - - priority = int(source.get("priority") or 0) - if score > 0 and priority: - score += min(priority // 10, 5) - return score, evidence - - -def _stable_from_source( - source: dict[str, Any], - *, - method: str, - evidence: list[dict[str, Any]], - context: dict[str, Any], -) -> InventorySourceAdjudication: - """仅在四元组身份可完整解析时返回 resolved。""" +def _from_source(*, status: str, source: dict[str, Any], method: str, context: dict[str, Any], evidence: list[dict[str, Any]] | None = None) -> InventorySourceAdjudication: + """由数据库 Source 生成 resolved/user_confirmed 裁决。""" resolution = resolve_inventory_source_identity(source, context) - config_version = get_inventory_sources_config_version() - fingerprint = compute_routing_fingerprint(context) - destination_candidates = context.get("destination_candidates") or [] if not resolution.ok or not resolution.identity: - if resolution.reason == "crane_warehouse_ambiguous": - return InventorySourceAdjudication( - status="ambiguous", - method=method, - config_version=config_version, - routing_fingerprint=fingerprint, - candidates=[_candidate_summary(source, matched_by=method)], - destination_candidates=destination_candidates, - evidence=evidence, - reason=resolution.reason, - ) - status = "invalid" if resolution.reason in {"source_incomplete", "crane_aliases_missing"} else "unresolved" - return InventorySourceAdjudication( - status=status, - method=method, - config_version=config_version, - routing_fingerprint=fingerprint, - candidates=[_candidate_summary(source, matched_by=method)], - destination_candidates=destination_candidates, - evidence=evidence, - conflicts=[resolution.reason] if resolution.reason else [], - reason=resolution.reason or "identity_incomplete", - ) + return InventorySourceAdjudication('invalid', reason=resolution.reason, config_version=inventory_sources_runtime_version()) identity = resolution.identity return InventorySourceAdjudication( - status="resolved", + status=status, method=method, source_code=identity.source_code, connector_type=identity.connector_type, - site_id=identity.site_id, warehouse_id=identity.warehouse_id, - config_version=config_version, - routing_fingerprint=fingerprint, - candidates=[_candidate_summary(source, score=100, matched_by=method)], - destination_candidates=destination_candidates, + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate(source)], + evidence=evidence or [], + ) + + +def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication: + """将规则引擎候选集转换为可执行或待人工确认的裁决。""" + sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))] + evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}] + if result.status == 'resolved' and len(sources) == 1: + return _from_source(status='resolved', source=sources[0], method='rule', context=context, evidence=evidence) + return InventorySourceAdjudication( + status=result.status, + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())], evidence=evidence, + reason='routing_rule_' + result.status, + ) + + +def _snapshot_match_key(row: dict[str, Any]) -> tuple[str, str] | None: + """构造库存快照与订单共用的 Reservation ID + Part Number 匹配键。""" + from app.services.shipping_notice.reservation_id import validated_reservation_id + + part_number = str(row.get('part_number') or '').strip().upper() + reservation_id = validated_reservation_id(row.get('reservation_id')) + return (part_number, reservation_id) if part_number and reservation_id else None + + +def resolve_ambiguous_source_from_ready_snapshots( + task: ShippingTask, + adjudication: InventorySourceAdjudication, +) -> InventorySourceAdjudication: + """ + 用已有有效快照从多个规则候选中确定唯一库存源,绝不比较库存数量或触发 RPA。 + + 仅当规则已经给出明确的多个 Source 候选时执行。每个候选只检查其最新有效快照是否 + 覆盖订单全部 ``reservation_id + part_number`` 键;恰好一个候选命中才自动确定 Source。 + 快照缺失、多个候选命中或订单缺少匹配键时保留原人工确认状态。 + """ + if adjudication.status != 'ambiguous': + return adjudication + + candidate_codes = { + str(item.get('source_code') or '').strip().upper() + for item in adjudication.candidates + if isinstance(item, dict) and str(item.get('source_code') or '').strip() + } + order_keys = { + key for row in read_task_order_lines(task) + if isinstance(row, dict) and (key := _snapshot_match_key(row)) + } + if not candidate_codes or not order_keys: + return adjudication + + # A partial or malformed order cannot be silently routed from a file. + if len(order_keys) != len(read_task_order_lines(task)): + return adjudication + + from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file + from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot + + matched: list[tuple[dict[str, Any], Any]] = [] + checked: list[dict[str, Any]] = [] + for source_code in sorted(candidate_codes): + source = get_database_inventory_source(source_code) + if source is None: + continue + warehouse_id = source.get('fixed_warehouse_id') if source.get('warehouse_resolution_mode') == 'fixed' else None + snapshot = find_latest_ready_snapshot(source_code, warehouse_id) + if snapshot is None: + checked.append({'source_code': source_code, 'snapshot': 'missing'}) + continue + lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)] + if not lines: + try: + lines, _column_meta = parse_inventory_snapshot_file(snapshot) + except (OSError, ValueError): + lines = [] + inventory_keys = { + key for row in lines + if isinstance(row, dict) and (key := _snapshot_match_key(row)) + } + is_match = order_keys.issubset(inventory_keys) + checked.append({ + 'source_code': source_code, + 'inventory_file_no': snapshot.inventory_file_no, + 'matched': is_match, + }) + if is_match: + matched.append((source, snapshot)) + + evidence = [*(adjudication.evidence or []), { + 'snapshot_candidate_check': checked, + 'match_key': ['reservation_id', 'part_number'], + 'selection_basis': 'unique_exact_key_coverage', + }] + if len(matched) != 1: + return replace(adjudication, evidence=evidence) + + source, snapshot = matched[0] + resolution = resolve_inventory_source_identity(source, extract_routing_context(task)) + if not resolution.ok or not resolution.identity: + return replace(adjudication, evidence=evidence) + identity = resolution.identity + return InventorySourceAdjudication( + status='resolved', + method='snapshot_match', + source_code=identity.source_code, + connector_type=identity.connector_type, + warehouse_id=identity.warehouse_id, + config_version=inventory_sources_runtime_version(), + routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)), + candidates=adjudication.candidates, + destination_candidates=adjudication.destination_candidates, + evidence=evidence, + reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}', ) def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication: - """ - 根据任务路由上下文与配置规则做确定性库存源裁决。 - 核心逻辑:相同输入与相同配置必须产生相同结果;区分未命中、多命中、冲突与配置无效。 - """ + """先评估任务级规则,再在所有订单行一致时接受行级规则结果。""" context = extract_routing_context(task) - destination_candidates = context.get("destination_candidates") or [] - config_version = get_inventory_sources_config_version() - - scored: list[tuple[int, dict[str, Any], list[dict[str, Any]]]] = [] - for source in list_inventory_sources(): - if _source_field_excluded(source, context): - continue - 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() - ): - continue - score, evidence = _source_match_score(source, context, destination_candidates) - if score > 0: - scored.append((score, source, evidence)) - - if not scored: - # Fallback: legacy match_aliases only - matched_codes: list[str] = [] - alias_evidence: dict[str, list[dict[str, Any]]] = {} - for candidate in destination_candidates: - for source in list_inventory_sources(): - aliases = source.get("match_aliases") or [] - if any(_matches_alias(candidate, alias) for alias in aliases): - code = str(source.get("source_code") or "").strip().upper() - if code and code not in matched_codes: - matched_codes.append(code) - alias_evidence.setdefault(code, []).append( - {"field": "destination_candidate", "value": candidate, "alias_only": True} - ) - if len(matched_codes) == 1: - source = get_inventory_source(matched_codes[0]) - if source: - return _stable_from_source( - source, - method="rule_exact", - evidence=alias_evidence.get(matched_codes[0], []), - context=context, - ) - if len(matched_codes) > 1: - candidates = [ - _candidate_summary(src, matched_by="rule_exact") - for code in matched_codes - for src in [get_inventory_source(code)] - if src - ] - return InventorySourceAdjudication( - status="ambiguous", - config_version=config_version, - routing_fingerprint=compute_routing_fingerprint(context), - candidates=candidates, - destination_candidates=destination_candidates, - evidence=[item for ev in alias_evidence.values() for item in ev], - reason="matched_multiple_sources", - ) + task_result = evaluate_inventory_source_rules(task=task) + if task_result.status != 'unresolved': + return _result_to_adjudication(task_result, context) + line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in read_task_order_lines(task)] + resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1} + if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results): + return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context) + if len(resolved_codes) > 1: return InventorySourceAdjudication( - status="unresolved", - config_version=config_version, - routing_fingerprint=compute_routing_fingerprint(context), - candidates=_all_enabled_source_candidates(), - destination_candidates=destination_candidates, - reason="no_route_rule_matched", + 'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes], + reason='line_rules_resolve_different_sources', ) - - scored.sort(key=lambda item: (-item[0], str(item[1].get("source_code") or ""))) - top_score = scored[0][0] - top_matches = [item for item in scored if item[0] == top_score] - - if len(top_matches) == 1: - _, source, evidence = top_matches[0] - method = "rule_combined" if len(evidence) > 1 else "rule_exact" - return _stable_from_source(source, method=method, evidence=evidence, context=context) - - conflicts = _detect_rule_conflicts(top_matches, context) - if conflicts: - candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches] - return InventorySourceAdjudication( - status="conflicted", - config_version=config_version, - routing_fingerprint=compute_routing_fingerprint(context), - candidates=candidates, - destination_candidates=destination_candidates, - evidence=[ev for _, _, ev in top_matches for ev in ev], - conflicts=conflicts, - reason="matched_conflicting_rules", - ) - - candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches] - return InventorySourceAdjudication( - status="ambiguous", - config_version=config_version, - routing_fingerprint=compute_routing_fingerprint(context), - candidates=candidates, - destination_candidates=destination_candidates, - evidence=[ev for _, _, ev in top_matches for ev in ev], - reason="matched_multiple_sources", - ) + return _result_to_adjudication(task_result, context) def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication: - """ - 用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。 - 【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。 - """ + """人工从已启用数据库 Source 中选择来源;不要求预先确定动态 Warehouse。""" context = extract_routing_context(task) - destination_candidates = context.get("destination_candidates") or [] - code = str(source_code or "").strip().upper() - source = get_inventory_source(code) - if not source or source.get("enabled", True) is False: + source = get_database_inventory_source(source_code) + if not source: return InventorySourceAdjudication( - status="invalid", - config_version=get_inventory_sources_config_version(), - routing_fingerprint=compute_routing_fingerprint(context), - candidates=_all_enabled_source_candidates(), - destination_candidates=destination_candidates, - conflicts=["source_code_not_found"], - reason="source_code_not_found", + 'invalid', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context), + candidates=[_candidate(item) for item in list_database_inventory_sources()], reason='source_code_not_found', ) - 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( - status="invalid", - config_version=get_inventory_sources_config_version(), - routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate_summary(source)], - destination_candidates=destination_candidates, - conflicts=["identity_incomplete_in_config"], - reason="identity_incomplete_in_config", - ) - - resolution = resolve_inventory_source_identity(source, context) - if not resolution.ok or not resolution.identity: - status = "ambiguous" if resolution.reason == "crane_warehouse_ambiguous" else "invalid" - return InventorySourceAdjudication( - status=status, - config_version=get_inventory_sources_config_version(), - routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate_summary(source)], - destination_candidates=destination_candidates, - conflicts=[resolution.reason] if resolution.reason else [], - reason=resolution.reason or "identity_incomplete", - ) - - identity = resolution.identity - return InventorySourceAdjudication( - status="user_confirmed", - method="user_confirmed", - source_code=identity.source_code, - connector_type=identity.connector_type, - site_id=identity.site_id, - warehouse_id=identity.warehouse_id, - config_version=get_inventory_sources_config_version(), - routing_fingerprint=compute_routing_fingerprint(context), - candidates=[_candidate_summary(source, matched_by="user_confirmed")], - destination_candidates=destination_candidates, - evidence=[{"field": "user_selection", "value": code}], - ) + return _from_source(status='user_confirmed', source=source, method='user_confirmed', context=context) -# Backward-compatible wrappers def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication: - """兼容旧调用点:委托 adjudicate_inventory_source。""" + """兼容调用名,委托当前通用规则裁决。""" return adjudicate_inventory_source(task) def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None: - """读取任务当前运行时 RPA source(静态配置 + 任务动态库位)。""" - from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source - - return build_task_rpa_inventory_source(task) + """按任务 Source 从数据库读取 RPA 配置;动态仓由回调库存文件确定。""" + return get_database_inventory_source(task.inventory_source_code) -def save_task_rpa_inventory_source( - task: ShippingTask, - source: dict[str, Any], - *, - resolution: InventorySourceAdjudication | None = None, -) -> None: - """把已确认库存源写入独立字段与 step_payload_json。""" +def save_task_rpa_inventory_source(task: ShippingTask, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None: + """兼容旧入口,将确认结果委托库存源门禁持久化。""" from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication - if resolution: - apply_inventory_source_adjudication(task, resolution) - return - code = str(source.get("source_code") or "").strip().upper() - cfg = get_inventory_source(code) - if not cfg: - return - context = extract_routing_context(task) - resolution = resolve_inventory_source_identity(cfg, context) - if not resolution.ok or not resolution.identity: - return - identity = resolution.identity - adjudication = InventorySourceAdjudication( - status="user_confirmed", - method="user_confirmed", - source_code=identity.source_code, - connector_type=identity.connector_type, - site_id=identity.site_id, - warehouse_id=identity.warehouse_id, - config_version=get_inventory_sources_config_version(), - routing_fingerprint=compute_routing_fingerprint(context), - ) - apply_inventory_source_adjudication(task, adjudication) + selected = resolution or confirm_inventory_source_by_code(task, str(source.get('source_code') or '')) + apply_inventory_source_adjudication(task, selected) def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None: - """库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。""" + """兼容旧入口,写入待人工确认的 Source 候选。""" from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication apply_inventory_source_adjudication(task, resolution) diff --git a/backend/app/services/shipping_notice/inventory_sources.py b/backend/app/services/shipping_notice/inventory_sources.py deleted file mode 100644 index fa3ef7ef..00000000 --- a/backend/app/services/shipping_notice/inventory_sources.py +++ /dev/null @@ -1,457 +0,0 @@ -""" -services/shipping_notice/inventory_sources.py - -用途:从 YAML/JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。 -依赖:Flask current_app、pathlib、PyYAML/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。 -逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.yaml,不改 Python。 -""" - -from __future__ import annotations - -import json -from copy import deepcopy -from pathlib import Path -from typing import Any - -import yaml -from flask import current_app - -_VALID_CONNECTOR_TYPES = { - "dsv360": "dsv360", - "crane_footprint": "crane_footprint", -} -_VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"}) -_CONFIG_CACHE: dict[str, Any] | None = None -_CONFIG_PATH: str | None = None -_CONFIG_RAW_DIGEST: str | None = None - - -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"), - "connector_type": source.get("connector_type"), - "site_id": source.get("site_id"), - "warehouse_id": source.get("warehouse_id"), - "warehouse_resolution": source.get("warehouse_resolution"), - "enabled": source.get("enabled", True), - "priority": source.get("priority", 0), - "entry_url": source.get("entry_url"), - "display_name": source.get("display_name"), - "match_aliases": sorted(source.get("match_aliases") or []), - "allowed_warehouse_ids": sorted(source.get("allowed_warehouse_ids") or []), - "match": { - key: sorted(value) if isinstance(value, list) else value - for key, value in sorted(match_cfg.items()) - }, - "navigation": source.get("navigation"), - "parameters": source.get("parameters"), - "export": source.get("export"), - } - - -def _normalized_config_digest(sources: dict[str, dict[str, Any]]) -> str: - """基于规范化结构计算配置内容哈希。""" - import hashlib - - canonical = [_canonical_source_for_digest(sources[code]) for code in sorted(sources)] - payload = json.dumps(canonical, sort_keys=True, ensure_ascii=False) - return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16] - - -def _config_content_version(payload: dict[str, Any], sources: dict[str, dict[str, Any]]) -> str: - """配置版本 = 声明版本 + 规范化结构哈希。""" - digest = _normalized_config_digest(sources) - declared = str(payload.get("version") or "1").strip() - return f"{declared}-{digest}" - - -class InventorySourceConfigError(ValueError): - """库存源配置校验失败。""" - - -def _config_path() -> Path: - """解析库存源配置文件路径;优先 Flask config,其次默认 backend/config。""" - raw = str(current_app.config.get("SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG") or "").strip() - if raw: - path = Path(raw) - if not path.is_absolute(): - from app.path_utils import resolve_backend_relative_path - - path = Path(resolve_backend_relative_path(raw, path)) - return path - from app.path_utils import resolve_backend_relative_path - - default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.yaml" - return Path(resolve_backend_relative_path(None, default)) - - -def _parse_config_payload(path: Path) -> dict[str, Any]: - """ - 按文件后缀解析库存源配置(默认 YAML;测试夹具仍可用 .json)。 - Raises: - InventorySourceConfigError: 后缀不支持或解析失败 - """ - text = path.read_text(encoding="utf-8") - suffix = path.suffix.lower() - try: - if suffix in {".yaml", ".yml"}: - payload = yaml.safe_load(text) - elif suffix == ".json": - payload = json.loads(text) - else: - raise InventorySourceConfigError( - f"unsupported inventory sources config format: {path.suffix} (use .yaml, .yml, or .json)" - ) - except (yaml.YAMLError, json.JSONDecodeError) as exc: - raise InventorySourceConfigError(f"failed to parse inventory sources config: {path}: {exc}") from exc - if not isinstance(payload, dict): - raise InventorySourceConfigError("inventory sources config root must be a mapping") - return payload - - -def _join_parameter_values(parameter: dict[str, Any]) -> str | None: - """将 multi_text 参数值按 joiner 拼接为单字符串。""" - values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()] - if not values: - return None - joiner = str(parameter.get("joiner") or ",") - return joiner.join(values) - - -def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]: - """ - 从 navigation + parameters 构造 worker 兼容的 query 字段。 - 核心逻辑:保留 DSV/Crane worker 现有读取口径,同时支持新版 parameters 驱动。 - """ - navigation = dict(source.get("navigation") or {}) - query: dict[str, Any] = {} - connector_type = str(source.get("connector_type") or "").strip().lower() - - if connector_type == "dsv360": - for key in ("program_group", "program_label", "report_group", "report_name"): - if navigation.get(key): - query[key] = navigation[key] - elif connector_type == "crane_footprint": - if navigation.get("report_name"): - query["report_name"] = navigation["report_name"] - query["project_code"] = navigation.get("project_code") - - warehouse_id = str(source.get("warehouse_id") or "").strip() - if warehouse_id: - query["warehouse_code"] = warehouse_id - - for parameter in source.get("parameters") or []: - if not isinstance(parameter, dict): - continue - name = str(parameter.get("name") or "").strip() - mode = str(parameter.get("mode") or "single").strip().lower() - if mode == "multi_text": - joined = _join_parameter_values(parameter) - if not joined: - continue - if name.lower() == "owner": - query["owner_code"] = joined - elif name.lower() == "putawayzone": - query["putaway_zone"] = joined - elif name.lower() == "warehouse": - query["warehouse_code"] = joined - continue - values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()] - if not values: - continue - value = values[0] - if name.lower() == "owner": - query["owner_code"] = value - elif name.lower() == "putawayzone": - query["putaway_zone"] = value - elif name.lower() == "warehouse": - query["warehouse_code"] = value - elif name.lower() == "project": - query["project_code"] = value - - return query - - -def effective_warehouse_id(source: dict[str, Any]) -> str: - """返回配置中显式声明的 warehouse_id;禁止用 site_id 回填。""" - return str(source.get("warehouse_id") or "").strip().upper() - - -def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]: - """校验并规范化单条库存源配置。""" - source_code = str(raw.get("source_code") or "").strip().upper() - if not source_code: - raise InventorySourceConfigError("source_code is required") - if source_code in seen_codes: - raise InventorySourceConfigError(f"duplicate source_code: {source_code}") - seen_codes.add(source_code) - - 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 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 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()] - if not aliases: - raise InventorySourceConfigError(f"{source_code}: match_aliases is required for crane_footprint") - allowed_warehouse_ids = [ - str(item).strip() - for item in (raw.get("allowed_warehouse_ids") or []) - if str(item).strip() - ] - if not allowed_warehouse_ids: - raise InventorySourceConfigError( - f"{source_code}: allowed_warehouse_ids is required for crane_footprint" - ) - warehouse_resolution = str(raw.get("warehouse_resolution") or "alias_match").strip().lower() - if warehouse_resolution != "alias_match": - raise InventorySourceConfigError( - f"{source_code}: warehouse_resolution must be alias_match for crane_footprint" - ) - parameters: list[dict[str, Any]] = [] - for item in raw.get("parameters") or []: - if not isinstance(item, dict): - raise InventorySourceConfigError(f"{source_code}: parameters[] must be objects") - mode = str(item.get("mode") or "single").strip().lower() - if mode not in _VALID_PARAMETER_MODES: - raise InventorySourceConfigError(f"{source_code}: invalid parameter mode {mode}") - required = bool(item.get("required", False)) - values = [str(v).strip() for v in (item.get("values") or []) if str(v).strip()] - if required and not values: - raise InventorySourceConfigError(f"{source_code}: required parameter {item.get('name')} has no values") - parameters.append({**item, "mode": mode, "values": values}) - - normalized = { - "source_code": source_code, - "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)), - "priority": int(raw.get("priority") or 0), - "entry_url": str(raw.get("entry_url") or "").strip(), - "warehouse_id": warehouse_id, - "navigation": dict(raw.get("navigation") or {}), - "parameters": parameters, - "match_aliases": [ - str(alias).strip() - for alias in (raw.get("match_aliases") or []) - if str(alias).strip() - ], - } - 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") - if isinstance(match_cfg, dict) and match_cfg: - normalized["match"] = { - "destination_codes": [str(v).strip() for v in (match_cfg.get("destination_codes") or []) if str(v).strip()], - "customers": [str(v).strip() for v in (match_cfg.get("customers") or []) if str(v).strip()], - "order_types": [str(v).strip() for v in (match_cfg.get("order_types") or []) if str(v).strip()], - "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 connector_type == "crane_footprint" and raw.get("export"): - normalized["export"] = dict(raw.get("export") or {}) - normalized["query"] = _build_legacy_query(normalized) - return normalized - - -def _load_config(*, force_reload: bool = False) -> dict[str, Any]: - """加载并缓存 YAML/JSON 配置;路径或文件内容变化时刷新(不依赖 mtime 单独命中)。""" - import hashlib - - global _CONFIG_CACHE, _CONFIG_PATH, _CONFIG_RAW_DIGEST - path = _config_path() - if not path.is_file(): - raise InventorySourceConfigError(f"inventory sources config not found: {path}") - - path_str = str(path.resolve()) - raw_digest = hashlib.sha256(path.read_bytes()).hexdigest()[:16] - if ( - _CONFIG_CACHE is not None - and not force_reload - and _CONFIG_PATH == path_str - and _CONFIG_RAW_DIGEST == raw_digest - ): - return _CONFIG_CACHE - - payload = _parse_config_payload(path) - sources_raw = payload.get("sources") - if not isinstance(sources_raw, list): - raise InventorySourceConfigError("sources must be a list") - - seen_codes: set[str] = set() - sources: dict[str, dict[str, Any]] = {} - for item in sources_raw: - if not isinstance(item, dict): - raise InventorySourceConfigError("each source must be an object") - normalized = _validate_source(item, seen_codes=seen_codes) - sources[normalized["source_code"]] = normalized - - _CONFIG_CACHE = { - "version": _config_content_version(payload, sources), - "sources": sources, - "path": path_str, - "raw_digest": raw_digest, - } - _CONFIG_PATH = path_str - _CONFIG_RAW_DIGEST = raw_digest - return _CONFIG_CACHE - - -def get_inventory_sources_config_version() -> str: - """返回当前加载的库存源配置版本字符串。""" - return str(_load_config().get("version") or "1") - - -def reload_inventory_sources_config() -> dict[str, Any]: - """强制重新加载库存源配置(管理/测试用)。""" - return _load_config(force_reload=True) - - -def get_inventory_source(source_code: str | None) -> dict[str, Any] | None: - """按 source_code 返回启用的库存源配置副本。""" - code = str(source_code or "").strip().upper() - if not code: - return None - source = _load_config()["sources"].get(code) - if not source or not source.get("enabled", True): - return None - return deepcopy(source) - - -def source_uses_dynamic_warehouse_id(source: dict[str, Any] | None) -> bool: - """判断库存源是否采用运行时动态库位(如 CRANE alias_match)。""" - if not source: - return False - if str(source.get("warehouse_id") or "").strip(): - return False - resolution = str(source.get("warehouse_resolution") or "").strip().lower() - return resolution in {"alias_match", "dynamic", "runtime"} - - -def configured_warehouse_aliases(source: dict[str, Any] | None) -> set[str]: - """返回配置中的路由匹配别名集合(大写),供订单目的地裁决使用。""" - if not source: - return set() - return { - str(alias).strip().upper() - for alias in (source.get("match_aliases") or []) - if str(alias).strip() - } - - -def configured_allowed_warehouse_ids(source: dict[str, Any] | None) -> set[str]: - """ - 返回 Worker 回调允许落库的库位 ID 集合(大写)。 - 核心逻辑:优先读 allowed_warehouse_ids;静态源回退 warehouse_id;与 match_aliases 解耦。 - """ - if not source: - return set() - allowed = source.get("allowed_warehouse_ids") - if allowed: - return {str(item).strip().upper() for item in allowed if str(item).strip()} - # fallback for static DSV 等源 - warehouse_id = str(source.get("warehouse_id") or "").strip().upper() - if warehouse_id: - return {warehouse_id} - return set() - - -def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]: - """返回库存源配置副本,供人工检查点展示候选项。""" - sources = _load_config()["sources"].values() - if enabled_only: - sources = [item for item in sources if item.get("enabled", True)] - return [deepcopy(item) for item in sources] - - -def build_rpa_inventory_source( - source_code: str | None, - *, - query_override: dict[str, Any] | None = None, - site_id: str | None = None, - warehouse_id: str | None = None, -) -> dict[str, Any] | None: - """ - 构造 RPA trigger 使用的 rpa_inventory_source。 - 【AI 触发时机】:HXOPS 已确定库存源后,写 RPA trigger 或确认人工选择时调用。 - """ - source = get_inventory_source(source_code) - if not source: - return None - if query_override: - query = dict(source.get("query") or {}) - for key, value in query_override.items(): - if value is not None and str(value).strip(): - query[key] = value - source["query"] = query - return merge_runtime_inventory_identity(source, site_id=site_id, warehouse_id=warehouse_id) - - -def merge_runtime_inventory_identity( - source: dict[str, Any], - *, - site_id: str | None = None, - warehouse_id: str | None = None, -) -> dict[str, Any]: - """ - 将任务已解析的 site/warehouse 合并进 RPA source,并同步 query.warehouse_code。 - 核心逻辑:Crane 动态库位、DSV 子仓均通过本函数进入 trigger/回调/快照复用。 - """ - merged = deepcopy(source) - site = str(site_id or merged.get("site_id") or "").strip().upper() - warehouse = str(warehouse_id or merged.get("warehouse_id") or "").strip().upper() - if site: - merged["site_id"] = site - if warehouse: - merged["warehouse_id"] = warehouse - merged["_runtime_identity_applied"] = True - query = dict(merged.get("query") or {}) - query["warehouse_code"] = warehouse - merged["query"] = query - 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 - query["project_code"] = warehouse - merged["query"] = query - return merged - - -def build_task_rpa_inventory_source(task: "ShippingTask") -> dict[str, Any] | None: - """ - 基于任务正式库存身份构造运行时 RPA source(配置 + 动态库位)。 - 【AI 触发时机】:ensure_inventory_via_rpa、RPA 回调、快照复用统一调用。 - """ - from app.models import ShippingTask - - if not isinstance(task, ShippingTask): - return None - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} - code = str(task.inventory_source_code or "").strip().upper() - site_id = str(task.inventory_site_id or "").strip().upper() or None - warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() or None - if not code: - legacy = payload.get("rpa_inventory_source") - if isinstance(legacy, dict) and legacy.get("source_code"): - return merge_runtime_inventory_identity(legacy, site_id=site_id, warehouse_id=warehouse_id) - return None - base = get_inventory_source(code) - if not base: - return None - return merge_runtime_inventory_identity(base, site_id=site_id, warehouse_id=warehouse_id) diff --git a/backend/app/services/shipping_notice/inventory_structure_analysis.py b/backend/app/services/shipping_notice/inventory_structure_analysis.py new file mode 100644 index 00000000..a7cf78af --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_structure_analysis.py @@ -0,0 +1,426 @@ +""" +services/shipping_notice/inventory_structure_analysis.py + +用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。 +依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。 +逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。 +""" + +from __future__ import annotations + +import csv +import hashlib +import re +import shutil +import uuid +from collections import Counter +from datetime import datetime +from pathlib import Path +from typing import Any + +from openpyxl import load_workbook +from openpyxl.cell.cell import MergedCell +from werkzeug.datastructures import FileStorage + +from app.core.errors import NotFoundError, ValidationError +from app.extensions import db +from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis +from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix +from app.services.shipping_notice.inventory_mapping import suggest_field_mapping +from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index +from app.services.shipping_notice.inventory_structure_fingerprint import ( + compatibility_fingerprint, + exact_fingerprint, + structure_definition, +) + +MAX_UPLOAD_BYTES = 20 * 1024 * 1024 +MAX_SCAN_ROWS = 40 +MAX_SAMPLE_ROWS = 5 +MAX_COLUMNS = 200 +_SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', 'temporary_conversation'} + + +def _has_required_suggestions(mapping: dict[str, str]) -> bool: + """确认自动建议至少覆盖一个匹配字段和一个库存数量字段。""" + rows = ShippingInventoryField.query.filter( + ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([ + int(field_id) for field_id in mapping if str(field_id).isdigit() + ]), + ).all() if mapping else [] + usages = {row.usage_type for row in rows} + return 'match_identity' in usages and 'inventory_quantity' in usages + + +def _analysis_root() -> Path: + """返回库存结构分析样本的受控托管目录。""" + from app.services.shipping_notice.export import _storage_root + + return _storage_root() / 'inventory_structure_analyses' + + +def _safe_filename(value: str) -> str: + """清理上传文件名,避免分析样本路径包含目录穿越字符。""" + return re.sub(r'[^A-Za-z0-9._-]+', '_', Path(str(value or '')).name) or 'inventory.xlsx' + + +def _normalise_header(value: Any) -> str: + """规范表头展示文本;结构指纹阶段会在此基础上做更严格标准化。""" + return re.sub(r'\s+', ' ', str(value or '').replace('\u3000', ' ').strip()) + + +def _value_type(values: list[Any]) -> str: + """依据非空样本推断列类型,只供管理员确认,不能取代字段映射。""" + non_empty = [value for value in values if value not in (None, '')] + if not non_empty: + return 'empty' + numeric_count = 0 + date_count = 0 + for value in non_empty: + if hasattr(value, 'year') and hasattr(value, 'month'): + date_count += 1 + continue + try: + float(str(value).replace(',', '').strip()) + numeric_count += 1 + except (TypeError, ValueError): + pass + if date_count == len(non_empty): + return 'date' + if numeric_count == len(non_empty): + return 'number' + return 'text' + + +def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[dict[str, Any]]: + """生成来源栏位的业务预览,包括样例、空值率和建议字段。""" + suggestions = suggest_field_mapping(headers, as_catalog=True) + catalog = { + str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all() + } + reverse_suggestions = {header: catalog[field_id].display_name for field_id, header in suggestions.items() if field_id in catalog} + duplicates = Counter(header for header in headers if header) + rows_total = len(sample_rows) + columns: list[dict[str, Any]] = [] + for index, header in enumerate(headers, start=1): + values = [row[index - 1] if len(row) >= index else None for row in sample_rows] + non_empty = [value for value in values if value not in (None, '')] + columns.append({ + 'index': index, + 'header': header, + 'sample_values': [str(value)[:120] for value in non_empty[:MAX_SAMPLE_ROWS]], + 'sample_empty_rate': round((rows_total - len(non_empty)) / rows_total, 4) if rows_total else 1, + 'inferred_type': _value_type(non_empty), + 'duplicate': bool(header and duplicates[header] > 1), + 'suggested_inventory_field': reverse_suggestions.get(header), + }) + return columns + + +def _workbook_structure(path: Path, *, legacy_xls: bool = False) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]: + """读取 xlsx 或旧 xls 的所有工作表并选择最可能的库存表头。""" + if legacy_xls: + import xlrd + + book = xlrd.open_workbook(filename=str(path), on_demand=True) + worksheets = [ + ( + str(book.sheet_by_index(index).name), + [ + [ + _xls_cell_value(book, book.sheet_by_index(index).cell(row_index, column_index)) + for column_index in range(book.sheet_by_index(index).ncols) + ] + for row_index in range(min(MAX_SCAN_ROWS, book.sheet_by_index(index).nrows)) + ], + book.sheet_by_index(index).nrows, + book.sheet_by_index(index).ncols, + ) + for index in range(book.nsheets) + ] + try: + return _build_workbook_structure(worksheets) + finally: + book.release_resources() + + workbook = load_workbook(path, read_only=True, data_only=True) + try: + worksheets = [] + for worksheet in workbook.worksheets: + rows = [list(row) for _, row in zip(range(MAX_SCAN_ROWS), worksheet.iter_rows(values_only=True))] + worksheets.append((worksheet.title, rows, worksheet.max_row or 0, worksheet.max_column or 0)) + return _build_workbook_structure(worksheets) + finally: + workbook.close() + + +def _build_workbook_structure( + worksheets: list[tuple[str, list[list[Any]], int, int]], +) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]: + """将任意 Excel 行迭代结果归一为统一的库存结构分析输出。""" + sheets: list[dict[str, Any]] = [] + candidates: list[dict[str, Any]] = [] + warnings: list[str] = [] + for sheet_name, rows, row_count, column_count in worksheets: + if len(rows) and max(len(row) for row in rows) > MAX_COLUMNS: + warnings.append(f'工作表“{sheet_name}”栏位数超过分析上限,仅可人工处理') + continue + header_index = find_inventory_header_row_index(rows) + headers = [_normalise_header(value) for value in (rows[header_index] if rows else [])] + samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS] if rows else [] + suggested = suggest_field_mapping(headers, as_catalog=True) + score = len(suggested) * 10 + (30 if _has_required_suggestions(suggested) else 0) + candidate = { + 'sheet_name': sheet_name, + 'header_row_index': header_index + 1, + 'headers': headers, + 'columns': _column_summary(headers, samples), + 'sample_row_count': len(samples), + 'row_count_hint': row_count, + 'score': score, + } + sheets.append({'sheet_name': sheet_name, 'row_count_hint': row_count, 'column_count': column_count}) + if headers: + candidates.append(candidate) + if not candidates: + raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + selected = max(candidates, key=lambda item: (item['score'], item['sample_row_count'])) + structure = { + 'sheets': sheets, + 'candidates': candidates, + 'selected_sheet_name': selected['sheet_name'], + 'selected_header_row_index': selected['header_row_index'], + 'selected_headers': selected['headers'], + 'selected_columns': selected['columns'], + } + mapping = suggest_field_mapping(selected['headers'], as_catalog=True) + summary = { + 'candidate_count': len(candidates), + 'sample_row_count': selected['sample_row_count'], + 'valid_inventory_field_suggestions': len(mapping), + 'has_required_suggestions': _has_required_suggestions(mapping), + } + return structure, mapping, summary, warnings + + +def _xlsx_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]: + """读取 xlsx 工作簿的结构摘要。""" + return _workbook_structure(path) + + +def _xls_cell_value(book: Any, cell: Any) -> Any: + """将 xlrd 单元格值转换为与 openpyxl 接近的 Python 值。""" + import xlrd + + if cell.ctype == xlrd.XL_CELL_EMPTY: + return None + if cell.ctype == xlrd.XL_CELL_DATE: + return xlrd.xldate_as_datetime(cell.value, book.datemode) + if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer(): + return int(cell.value) + return cell.value + + +def _xls_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]: + """读取旧 .xls 工作簿结构;与 xlsx 产出完全相同的分析契约。""" + return _workbook_structure(path, legacy_xls=True) + + +def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]: + """读取 CSV 样本,使用与 Excel 一致的表头和列统计逻辑。""" + try: + with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as handle: + rows = [row for _, row in zip(range(MAX_SCAN_ROWS), csv.reader(handle))] + except OSError as exc: + raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc + if not rows: + raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + header_index = find_inventory_header_row_index(rows) + headers = [_normalise_header(value) for value in rows[header_index]] + samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS] + mapping = suggest_field_mapping(headers, as_catalog=True) + candidate = { + 'sheet_name': None, + 'header_row_index': header_index + 1, + 'headers': headers, + 'columns': _column_summary(headers, samples), + 'sample_row_count': len(samples), + 'row_count_hint': len(rows), + 'score': len(mapping) * 10 + (30 if _has_required_suggestions(mapping) else 0), + } + return { + 'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None, + 'selected_header_row_index': header_index + 1, 'selected_headers': headers, + 'selected_columns': candidate['columns'], + }, mapping, { + 'candidate_count': 1, 'sample_row_count': len(samples), + 'valid_inventory_field_suggestions': len(mapping), + 'has_required_suggestions': _has_required_suggestions(mapping), + }, [] + + +def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]: + """按受控文件格式分派结构分析,禁止根据内容猜测不支持的格式。""" + if suffix == '.xlsx': + return _xlsx_structure(path) + if suffix == '.xls': + return _xls_structure(path) + if suffix == '.csv': + return _csv_structure(path) + raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + + +def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]: + """输出管理端需要的分析结果,不暴露服务器存储路径。""" + return { + 'id': item.id, + 'source_kind': item.source_kind, + 'source_file_name': item.source_file_name, + 'file_checksum': item.file_checksum, + 'file_format': item.file_format, + 'analysis_status': item.analysis_status, + 'structure': item.structure_json or {}, + 'suggested_mapping': item.suggested_mapping_json or {}, + 'validation_summary': item.validation_summary_json or {}, + 'warnings': item.warning_json or [], + 'match_result': item.match_result_json or {}, + 'created_at': item.created_at.isoformat() if item.created_at else None, + } + + +def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]: + """上传并分析管理员选择的库存样本文件,创建后端权威分析记录。""" + if upload is None or not str(upload.filename or '').strip(): + raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED') + suffix = resolve_inventory_upload_suffix(str(upload.filename)) + raw = upload.stream.read(MAX_UPLOAD_BYTES + 1) + if len(raw) > MAX_UPLOAD_BYTES: + raise ValidationError('Inventory sample file is too large', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_TOO_LARGE') + if not raw: + raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + analysis_dir = _analysis_root() / uuid.uuid4().hex + analysis_dir.mkdir(parents=True, exist_ok=False) + path = analysis_dir / f'sample{suffix}' + try: + path.write_bytes(raw) + structure, suggested, summary, warnings = _analyse_path(path, suffix) + except ValidationError: + shutil.rmtree(analysis_dir, ignore_errors=True) + raise + except Exception as exc: + shutil.rmtree(analysis_dir, ignore_errors=True) + raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc + selected_headers = structure.get('selected_headers', []) + selected_definition = structure_definition( + file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), + header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers, + ) + item = ShippingInventoryStructureAnalysis( + source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=str(path), + file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', + structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary, + warning_json=warnings, created_by=actor_id, + exact_structure_fingerprint=exact_fingerprint(selected_definition), + compatibility_fingerprint=compatibility_fingerprint( + definition=selected_definition, field_mapping=suggested, match_keys=[], + ), + ) + db.session.add(item) + db.session.flush() + from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + + item.match_result_json = recommend_profiles({ + 'structure': structure, + 'suggested_mapping': suggested, + 'exact_structure_fingerprint': item.exact_structure_fingerprint, + 'compatibility_fingerprint': item.compatibility_fingerprint, + }) + db.session.commit() + return serialize_analysis(item) + + +def get_analysis(analysis_id: int) -> dict[str, Any]: + """读取既有结构分析,供管理员选择工作表、表头和来源栏位。""" + item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + if item is None: + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') + return serialize_analysis(item) + + +def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """用已分析的真实栏位创建库存文件解析方案草稿,禁止前端编造来源栏位。""" + analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + if analysis is None: + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') + structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} + sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None + header_row_index = data.get('header_row_index') or structure.get('selected_header_row_index') + candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else [] + candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') == sheet_name and item.get('header_row_index') == header_row_index), None) + if candidate is None and sheet_name is None: + candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') is None and item.get('header_row_index') == header_row_index), None) + if not isinstance(candidate, dict): + raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + headers = {str(value).strip() for value in candidate.get('headers', []) if str(value).strip()} + mapping = data.get('field_mapping') if isinstance(data.get('field_mapping'), dict) else analysis.suggested_mapping_json or {} + if any(str(value or '').strip() not in headers for value in mapping.values()): + raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + duplicates = { + str(column.get('header') or '').strip() + for column in candidate.get('columns', []) + if isinstance(column, dict) and column.get('duplicate') + } + if any(str(value or '').strip() in duplicates for value in mapping.values()): + raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + from app.services.shipping_notice import inventory_parsing_profile + + saved = inventory_parsing_profile.save_draft({ + 'profile_code': data.get('profile_code'), + 'display_name': data.get('display_name'), + 'file_format': analysis.file_format, + 'definition': { + 'sheet_name': sheet_name, + 'header_row_index': header_row_index, + 'field_mapping': mapping, + 'match_keys': data.get('match_keys'), + }, + }, actor_id=actor_id, profile_id=data.get('profile_id')) + profile = db.session.get(ShippingInventoryParsingProfile, saved['id']) + selected_definition = structure_definition( + file_format=analysis.file_format, sheet_name=sheet_name, header_row_index=header_row_index, + headers=[str(value) for value in candidate.get('headers', [])], + ) + profile.structure_definition_json = selected_definition + profile.exact_structure_fingerprint = exact_fingerprint(selected_definition) + profile.compatibility_fingerprint = compatibility_fingerprint( + definition=selected_definition, field_mapping=mapping, + match_keys=data.get('match_keys') if isinstance(data.get('match_keys'), list) else [], + ) + profile.fingerprint_version = selected_definition['fingerprint_version'] + db.session.commit() + return inventory_parsing_profile.payload(profile) + + +def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]: + """确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。""" + analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + if analysis is None: + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + if profile is None or profile.status != 'published': + raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + match = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {} + candidate_ids = {int(item.get('profile_id')) for item in match.get('candidates', []) if isinstance(item, dict) and item.get('profile_id')} + same_test_structure = bool( + analysis.exact_structure_fingerprint + and analysis.exact_structure_fingerprint == profile.exact_structure_fingerprint + ) + if profile_id not in candidate_ids and not same_test_structure: + raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + analysis.match_result_json = { + **match, + 'adopted_profile_id': profile.id, + 'adopted_profile_checksum': profile.checksum, + } + db.session.commit() + return serialize_analysis(analysis) diff --git a/backend/app/services/shipping_notice/inventory_structure_drift.py b/backend/app/services/shipping_notice/inventory_structure_drift.py new file mode 100644 index 00000000..b292b828 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_structure_drift.py @@ -0,0 +1,92 @@ +""" +services/shipping_notice/inventory_structure_drift.py + +用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。 +依赖:库存源/解析方案模型、库存结构分析和方案复用服务。 +逻辑:RPA 与后续人工受控入库复用本服务;一致文件可继续解析,核心栏位变化必须阻断,绝不回退至猜列。 +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from app.core.errors import ConflictError +from app.models import ShippingInventorySource + + +def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]: + """核验正式库存文件结构并返回已绑定方案的确定性解析参数。 + + Args: + source_code: 已启用库存站点编码,必须绑定已发布解析方案。 + path: RPA 下载的库存文件,必须是受控 xls/xlsx/csv 格式且存在。 + + Returns: + 包含 mapping、sheet_name、header_row_index 和可展示差异的字典。 + + Raises: + ConflictError: 文件结构缺关键栏位、格式不一致或与已绑定方案不兼容时抛出。 + """ + source = ShippingInventorySource.query.filter_by(source_code=str(source_code or '').strip().upper()).first() + profile = source.parsing_profile if source is not None else None + if source is None or not source.enabled or profile is None or profile.status != 'published': + raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED') + + from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix + from app.services.shipping_notice.inventory_structure_analysis import _analyse_path + from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition + from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + + suffix = resolve_inventory_upload_suffix(path.name) + actual_format = suffix.lstrip('.') + if actual_format != profile.file_format: + raise ConflictError('Inventory file format changed', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED') + structure, suggested, _summary, warnings = _analyse_path(path, suffix) + configured = profile.definition_json if isinstance(profile.definition_json, dict) else {} + expected_sheet = configured.get('sheet_name') + expected_header_row = configured.get('header_row_index') + candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else [] + selected = next((item for item in candidates if isinstance(item, dict) + and item.get('sheet_name') == expected_sheet + and item.get('header_row_index') == expected_header_row), None) + if selected is None: + raise ConflictError( + 'Configured inventory worksheet or header row is unavailable', + code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED', + details={'source_code': source.source_code, 'profile_id': profile.id}, + ) + # Compare the configured worksheet rather than the analyser's best guess. + structure = {**structure, 'selected_sheet_name': selected['sheet_name'], + 'selected_header_row_index': selected['header_row_index'], + 'selected_headers': selected.get('headers', []), 'selected_columns': selected.get('columns', [])} + from app.services.shipping_notice.inventory_mapping import suggest_field_mapping + + suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True) + definition = structure_definition( + file_format=actual_format, sheet_name=structure.get('selected_sheet_name'), + header_row_index=structure.get('selected_header_row_index') or 1, + headers=structure.get('selected_headers', []), + ) + analysis = { + 'structure': structure, + 'suggested_mapping': suggested, + 'exact_structure_fingerprint': exact_fingerprint(definition), + 'compatibility_fingerprint': '', + } + recommendation = recommend_profiles(analysis) + candidate = next((item for item in recommendation.get('candidates', []) if item.get('profile_id') == profile.id), None) + if candidate is None: + raise ConflictError( + 'Inventory file structure is incompatible with the bound parsing profile', + code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED', + details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings}, + ) + return { + 'field_mapping': dict(configured.get('field_mapping') or {}), + 'sheet_name': configured.get('sheet_name'), + 'header_row_index': configured.get('header_row_index'), + 'level': candidate.get('level'), + 'difference': candidate.get('difference') or {}, + 'warnings': warnings, + } diff --git a/backend/app/services/shipping_notice/inventory_structure_fingerprint.py b/backend/app/services/shipping_notice/inventory_structure_fingerprint.py new file mode 100644 index 00000000..13eaf036 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_structure_fingerprint.py @@ -0,0 +1,71 @@ +""" +services/shipping_notice/inventory_structure_fingerprint.py + +用途:为库存文件结构和解析定义生成稳定、可审计的指纹。 +依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。 +逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。 +""" + +from __future__ import annotations + +import hashlib +import json +import re +import unicodedata +from typing import Any + + +FINGERPRINT_VERSION = 'inventory-structure-v1' +def normalise_header(value: Any) -> str: + """将表头统一为可比文本,处理全半角、大小写、空白和常见分隔符。""" + text = unicodedata.normalize('NFKC', str(value or '')).strip().lower() + text = re.sub(r'[\s_\-./\\]+', ' ', text) + return re.sub(r'\s+', ' ', text).strip() + + +def _digest(payload: dict[str, Any]) -> str: + """对排序后的确定性结构内容生成 SHA-256,不含库存业务数据。""" + encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() + return hashlib.sha256(encoded).hexdigest() + + +def structure_definition(*, file_format: str, sheet_name: str | None, header_row_index: int, headers: list[str]) -> dict[str, Any]: + """提取文件客观结构;列顺序和重复列保留,确保完全相同判断严格。""" + return { + 'fingerprint_version': FINGERPRINT_VERSION, + 'file_format': str(file_format).lower(), + 'sheet_name': str(sheet_name or ''), + 'header_row_index': int(header_row_index), + 'headers': [normalise_header(header) for header in headers], + } + + +def exact_fingerprint(definition: dict[str, Any]) -> str: + """生成完整文件结构指纹,用于准确识别相同库存模板布局。""" + return _digest(definition) + + +def compatibility_fingerprint(*, definition: dict[str, Any], field_mapping: dict[str, str], match_keys: list[dict[str, Any]]) -> str: + """按匹配与数量用途生成兼容指纹,忽略普通导出列但保留用户字段 ID。""" + from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids + + runtime_mapping, catalog = runtime_field_mapping(field_mapping) + usages = usage_field_ids() + capability_ids = usages.get('match_identity', set()) | usages.get('inventory_quantity', set()) + core_mapping = { + field_id: normalise_header(runtime_mapping.get(field_id)) + for field_id in sorted(capability_ids) + if field_id in catalog and runtime_mapping.get(field_id) + } + return _digest({ + 'fingerprint_version': FINGERPRINT_VERSION, + 'file_format': definition.get('file_format'), + 'core_mapping': core_mapping, + 'match_keys': sorted([ + { + 'order_field_id': str(item.get('order_field_id') or ''), + 'inventory_field_id': str(item.get('inventory_field_id') or item.get('inventory_field') or ''), + } + for item in match_keys if isinstance(item, dict) + ], key=lambda item: (item['order_field_id'], item['inventory_field_id'])), + }) diff --git a/backend/app/services/shipping_notice/inventory_temporary_session.py b/backend/app/services/shipping_notice/inventory_temporary_session.py new file mode 100644 index 00000000..314904b2 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_temporary_session.py @@ -0,0 +1,553 @@ +""" +services/shipping_notice/inventory_temporary_session.py + +用途:处理对话上传库存候选文件的身份初检与临时会话状态。 +依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。 +逻辑:Dify 先用统一运行态上下文创建会话;后端验证文件归属并分析结构, + 仅返回脱敏表头预览和候选站点,不创建生产库存快照或修改库存站点配置。 +""" + +from __future__ import annotations + +import hashlib +import copy +import math +import shutil +import uuid +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + Agent, + ChatSession, + FileAsset, + ShippingInventoryStructureAnalysis, + ShippingTemporaryInventorySession, + ShippingInventoryField, + ShippingInventoryParsingProfile, +) +from app.services.agent_runtime_context.parser import parse_agent_runtime_context +from app.services.file_assets.service import read_asset_bytes +from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix +from app.services.shipping_notice.inventory_structure_analysis import ( + MAX_UPLOAD_BYTES, + _analyse_path, + _analysis_root, + _safe_filename, + serialize_analysis, +) +from app.services.shipping_notice.inventory_structure_fingerprint import ( + compatibility_fingerprint, + exact_fingerprint, + structure_definition, +) +from app.services.shipping_notice.inventory_mapping import ( + mapping_is_complete, + runtime_field_mapping, + suggest_field_mapping, + validate_field_mapping_against_headers, +) +from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta + +_CONTEXT_PATHS = ['agent_code', 'platform.session_id'] +_TTL_HOURS = 24 +def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession: + """从 Dify 运行态上下文解析货代会话,并以本地会话反查用户身份。""" + parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS) + values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {} + if str(values.get('agent_code') or '') != 'shipping_notice': + raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID') + session_id = str(values.get('platform.session_id') or '').strip() + session = ( + db.session.query(ChatSession) + .join(Agent, Agent.id == ChatSession.agent_id) + .filter(ChatSession.session_id == session_id, Agent.agent_code == 'shipping_notice') + .one_or_none() + ) + if session is None: + raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID') + return session + + +def _session_no() -> str: + """生成临时库存会话编号;编号仅用于审计和 Tool 引用,不承载业务单号语义。""" + return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}' + + +def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]: + """输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。""" + analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + return { + 'session_no': item.session_no, + 'status': item.status, + 'file_classification_status': item.file_classification_status, + 'classification_reason': item.classification_reason, + 'analysis': _serialize_dify_analysis_preview(analysis) if analysis else None, + 'available_inventory_fields': _available_inventory_fields(), + 'mapping_suggestion': _mapping_suggestion(item), + 'confirmed_usage': _confirmed_usage(item), + 'expires_at': item.expires_at.isoformat() if item.expires_at else None, + } + + +def _available_inventory_fields() -> list[dict[str, Any]]: + """返回 Dify 可建议的库存业务字段目录,不暴露稳定内部字段编码。""" + return [{ + 'id': item.id, + 'display_name': item.display_name, + 'description': item.description or '', + 'value_type': item.value_type, + 'usage_type': item.usage_type, + } for item in ShippingInventoryField.query.filter_by(status='active').order_by( + ShippingInventoryField.sort_order, ShippingInventoryField.id, + ).all()] + + +def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None: + """提取已保存的候选映射;未建议时返回空,不伪造可运行的映射。""" + result = item.result_json if isinstance(item.result_json, dict) else {} + value = result.get('mapping_suggestion') + return value if isinstance(value, dict) else None + + +def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None: + """输出已确认的临时使用摘要,不返回库存行或文件内部路径。""" + result = item.result_json if isinstance(item.result_json, dict) else {} + value = result.get('confirmed_usage') + if not isinstance(value, dict): + return None + return { + 'usage_scope': 'conversation', + 'mapping_origin': value.get('mapping_origin'), + 'profile_id': value.get('profile_id'), + 'quality': value.get('quality'), + 'confirmed_at': value.get('confirmed_at'), + } + + +def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]: + """返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。""" + preview = copy.deepcopy(serialize_analysis(analysis)) + structure = preview.get('structure') + if not isinstance(structure, dict): + return preview + for candidate in structure.get('candidates') or []: + if not isinstance(candidate, dict): + continue + for column in candidate.get('columns') or []: + if isinstance(column, dict): + column.pop('sample_values', None) + for column in structure.get('selected_columns') or []: + if isinstance(column, dict): + column.pop('sample_values', None) + return preview + + +def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis: + """对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。""" + if int(asset.file_size or 0) > MAX_UPLOAD_BYTES: + raise ValidationError( + 'Temporary inventory file is too large', + code='SHIPPING.TEMP_INVENTORY_FILE_TOO_LARGE', + ) + suffix = resolve_inventory_upload_suffix(asset.original_filename) + raw = read_asset_bytes(asset) + analysis_dir = _analysis_root() / uuid.uuid4().hex + analysis_dir.mkdir(parents=True, exist_ok=False) + path = analysis_dir / f'conversation{suffix}' + try: + path.write_bytes(raw) + structure, suggested_catalog, summary, warnings = _analyse_path(path, suffix) + except ValidationError: + shutil.rmtree(analysis_dir, ignore_errors=True) + raise + except Exception as exc: + shutil.rmtree(analysis_dir, ignore_errors=True) + raise ValidationError( + 'Temporary inventory file cannot be analysed', + code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID', + ) from exc + # 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。 + suggested, _catalog = runtime_field_mapping(suggested_catalog) + definition = structure_definition( + file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), + header_row_index=structure.get('selected_header_row_index') or 1, + headers=structure.get('selected_headers', []), + ) + analysis = ShippingInventoryStructureAnalysis( + source_kind='temporary_conversation', source_file_name=_safe_filename(asset.original_filename), + storage_path=str(path), file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), + analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, + validation_summary_json=summary, warning_json=warnings, created_by=owner_id, + exact_structure_fingerprint=exact_fingerprint(definition), + compatibility_fingerprint=compatibility_fingerprint( + definition=definition, field_mapping=suggested, match_keys=[], + ), + ) + db.session.add(analysis) + db.session.flush() + from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + + analysis.match_result_json = recommend_profiles({ + 'structure': structure, + 'suggested_mapping': suggested, + 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, + 'compatibility_fingerprint': analysis.compatibility_fingerprint, + }) + return analysis + + +def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]: + """在用户已明确声明库存文件后,仅按通用表格结构判断是否可进入候选映射。""" + structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} + headers = structure.get('selected_headers') if isinstance(structure.get('selected_headers'), list) else [] + columns = structure.get('selected_columns') if isinstance(structure.get('selected_columns'), list) else [] + has_sample_values = any( + isinstance(column, dict) and bool(column.get('sample_values')) for column in columns + ) + if len([item for item in headers if str(item).strip()]) >= 2 and columns and has_sample_values: + return 'inventory_candidate', '已识别可维护的表格结构,待确认库存字段映射后才能使用。' + return 'not_inventory', '文件缺少可确认的表头或数据行,不能作为库存候选。' + + +def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]: + """ + 创建对话库存候选会话并执行后端结构初检。 + + 【AI 触发时机】:用户在货代对话中明确说明上传的 .xls/.xlsx/.csv 是库存文件时调用。 + 核心逻辑:通过 agent_runtime_context 反查真实会话和用户,验证 FileAsset 所有权,分析受控副本; + 不创建库存快照、不绑定库存站点、不执行订单匹配。 + + Args: + payload: 必须含 agent_runtime_context 与 asset_no;asset_no 必须属于当前会话用户。 + + Returns: + 临时会话编号、分类结论和脱敏结构分析。 + """ + session = _runtime_session(payload.get('agent_runtime_context')) + asset_no = str(payload.get('asset_no') or '').strip().upper() + if not asset_no: + raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_INVENTORY_ASSET_REQUIRED') + asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).one_or_none() + if asset is None or int(asset.owner_user_id) != int(session.user_id): + raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_FOUND') + if str(asset.upload_status or '') != 'ready': + raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_READY') + try: + resolve_inventory_upload_suffix(asset.original_filename) + except Exception as exc: + raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_INVENTORY_FILE_TYPE_INVALID') from exc + + active = ShippingTemporaryInventorySession.query.filter( + ShippingTemporaryInventorySession.user_id == session.user_id, + ShippingTemporaryInventorySession.conversation_id == session.session_id, + ShippingTemporaryInventorySession.asset_id == asset.id, + ShippingTemporaryInventorySession.status.in_([ + 'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion', + 'awaiting_mapping_confirmation', + ]), + ShippingTemporaryInventorySession.expires_at > datetime.utcnow(), + ).order_by(ShippingTemporaryInventorySession.id.desc()).first() + if active: + return _serialize(active) + + analysis = _persist_analysis(asset=asset, owner_id=int(session.user_id)) + classification, reason = _classify(analysis) + expires_at = datetime.utcnow() + timedelta(hours=_TTL_HOURS) + # 临时会话和上传资产在同一有效期内存活,避免清理任务提前删除仍待确认的文件。 + if asset.expires_at is None or asset.expires_at < expires_at: + asset.expires_at = expires_at + match_result = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {} + has_exact_profile = classification == 'inventory_candidate' and str(match_result.get('status') or '') == 'exact' + item = ShippingTemporaryInventorySession( + session_no=_session_no(), user_id=int(session.user_id), conversation_id=session.session_id, + asset_id=int(asset.id), analysis_id=analysis.id, declared_intent='inventory_candidate', + file_classification_status=classification, + status=( + 'awaiting_profile_confirmation' if has_exact_profile + else ('awaiting_mapping_suggestion' if classification == 'inventory_candidate' else 'rejected') + ), + classification_reason=reason, + candidate_source_ids_json=[], + result_json={}, expires_at=expires_at, + ) + db.session.add(item) + db.session.commit() + return _serialize(item) + + +def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]: + """ + 查询临时库存会话的脱敏分析状态。 + + 【AI 触发时机】:创建临时库存会话后,需要读取结构预览、方案候选或后端分类结论时调用。 + Args: + payload: 必须含 agent_runtime_context 与 temporary_session_no。 + Returns: + 仅属于当前会话用户的临时会话投影。 + """ + session = _runtime_session(payload.get('agent_runtime_context')) + session_no = str(payload.get('temporary_session_no') or '').strip().upper() + item = ShippingTemporaryInventorySession.query.filter_by( + session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id, + ).one_or_none() + if item is None: + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}: + item.status = 'expired' + db.session.commit() + return _serialize(item) + + +def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> dict[str, Any]: + """ + 保存 Dify 给出的临时库存映射建议,但不使其进入正式库存运行链路。 + + 【AI 触发时机】:仅当临时会话没有可直接复用的 published 方案,且 LLM 已基于真实表头和字段目录给出候选时调用。 + 核心逻辑:校验当前会话、字段目录 ID、真实来源表头、重复映射和匹配/数量能力;只保存待用户确认的建议。 + + Args: + payload: 必须含 agent_runtime_context、temporary_session_no 与 field_mapping(库存字段目录 ID 到真实表头)。 + + Returns: + 更新后的临时会话投影;不含发布、库存站点绑定或订单匹配结果。 + """ + session = _runtime_session(payload.get('agent_runtime_context')) + session_no = str(payload.get('temporary_session_no') or '').strip().upper() + item = ShippingTemporaryInventorySession.query.filter_by( + session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id, + ).one_or_none() + if item is None: + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + if item.status != 'awaiting_mapping_suggestion': + raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_INVENTORY_MAPPING_STATE_INVALID') + raw_mapping = payload.get('field_mapping') + if not isinstance(raw_mapping, dict) or not raw_mapping: + raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID') + mapping = { + str(field_id).strip(): str(header).strip() + for field_id, header in raw_mapping.items() + if str(field_id).strip() and str(header).strip() + } + analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + structure = analysis.structure_json if analysis and isinstance(analysis.structure_json, dict) else {} + headers = [str(header).strip() for header in structure.get('selected_headers', []) if str(header).strip()] + if not headers or len(mapping) != len(raw_mapping) or len(set(mapping.values())) != len(mapping): + raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID') + errors = validate_field_mapping_against_headers(headers, mapping) + if errors or not mapping_is_complete(mapping): + raise ValidationError( + 'Temporary inventory mapping suggestion is incomplete or invalid', + code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID', details={'errors': errors}, + ) + item.result_json = { + **(item.result_json if isinstance(item.result_json, dict) else {}), + 'mapping_suggestion': {'field_mapping': mapping, 'origin': 'dify_candidate'}, + } + item.status = 'awaiting_mapping_confirmation' + db.session.commit() + return _serialize(item) + + +def _select_confirmed_mapping( + item: ShippingTemporaryInventorySession, + *, + selected_profile_id: Any, +) -> tuple[dict[str, str], str, int | None]: + """按会话状态选择 exact 已发布方案或已校验建议,禁止请求直接传映射覆盖。""" + analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + if analysis is None: + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + if item.status == 'awaiting_profile_confirmation': + try: + profile_id = int(selected_profile_id) + except (TypeError, ValueError) as exc: + raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') from exc + candidates = (analysis.match_result_json or {}).get('candidates', []) if isinstance(analysis.match_result_json, dict) else [] + exact_ids = { + int(candidate.get('profile_id')) + for candidate in candidates if isinstance(candidate, dict) + and str(candidate.get('level') or '') == 'exact' + and str(candidate.get('profile_id') or '').isdigit() + } + profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + if profile is None or profile.status != 'published' or profile_id not in exact_ids: + raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + return dict((profile.definition_json or {}).get('field_mapping') or {}), f'published_profile:{profile.profile_code}:v{profile.version}', profile.id + if item.status == 'awaiting_mapping_confirmation': + suggestion = _mapping_suggestion(item) or {} + mapping = suggestion.get('field_mapping') if isinstance(suggestion.get('field_mapping'), dict) else {} + if not mapping: + raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + return dict(mapping), 'dify_candidate', None + raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + + +def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]: + """按字段目录用途验证临时解析行;旧编码仅保留给无目录映射的受控内部调用。""" + runtime_mapping, catalog = runtime_field_mapping(field_mapping) + if catalog: + match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity'] + quantity_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'inventory_quantity'] + else: + match_fields = ['part_number', 'reservation_id'] + quantity_fields = ['available_qty'] + invalid_rows = 0 + for line in lines: + try: + quantities = [line.get(field_id) for field_id in quantity_fields] + quantity_valid = len(quantities) == 1 and math.isfinite(float(quantities[0])) and float(quantities[0]) >= 0 + except (TypeError, ValueError): + quantity_valid = False + identities_valid = bool(match_fields) and all(str(line.get(field_id) or '').strip() for field_id in match_fields) + if not identities_valid or not quantity_valid: + invalid_rows += 1 + return { + 'parsed_line_count': len(lines), + 'valid_line_count': len(lines) - invalid_rows, + 'invalid_line_count': invalid_rows, + 'passed': bool(lines) and invalid_rows == 0, + } + + +def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: + """ + 经用户明确确认后,锁定当前会话临时库存文件的确定性解析定义与质量结果。 + + 【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。 + 核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁; + 只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。 + + Args: + payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。 + + Returns: + 已确认临时使用会话的安全投影,含质量摘要但不含库存行。 + """ + session = _runtime_session(payload.get('agent_runtime_context')) + session_no = str(payload.get('temporary_session_no') or '').strip().upper() + item = ShippingTemporaryInventorySession.query.filter_by( + session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id, + ).one_or_none() + if item is None: + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + if item.expires_at <= datetime.utcnow(): + item.status = 'expired' + db.session.commit() + raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_INVENTORY_SESSION_EXPIRED') + mapping, mapping_origin, profile_id = _select_confirmed_mapping(item, selected_profile_id=payload.get('selected_profile_id')) + analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + if analysis is None: + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} + try: + lines, column_meta = parse_inventory_excel_with_meta( + Path(analysis.storage_path), field_mapping=mapping, mapping_source=mapping_origin, + header_row_index=structure.get('selected_header_row_index'), sheet_name=structure.get('selected_sheet_name'), + ) + except Exception as exc: + raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID') from exc + quality = _quality_report(lines, mapping) + if not quality['passed']: + raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID', details={'quality': quality}) + item.task_id = None + item.result_json = { + **(item.result_json if isinstance(item.result_json, dict) else {}), + 'confirmed_usage': { + 'usage_scope': 'conversation', + 'mapping_origin': mapping_origin, 'profile_id': profile_id, 'field_mapping': mapping, + 'column_meta': column_meta, 'quality': quality, 'file_checksum': analysis.file_checksum, + 'confirmed_at': datetime.utcnow().isoformat(), + }, + } + item.status = 'confirmed_for_temporary_use' + db.session.commit() + return _serialize(item) + + +def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]: + """返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。""" + rows = ShippingTemporaryInventorySession.query.filter_by( + status='confirmed_for_temporary_use', + ).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all() + result: list[dict[str, Any]] = [] + for item in rows: + analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + confirmed = _confirmed_usage(item) + result.append({ + 'session_no': item.session_no, + 'analysis_id': item.analysis_id, + 'source_file_name': analysis.source_file_name if analysis else None, + 'file_format': analysis.file_format if analysis else None, + 'analysis': _serialize_dify_analysis_preview(analysis) if analysis else None, + 'confirmed_usage': confirmed, + 'locked_mapping': ((item.result_json or {}).get('confirmed_usage', {}).get('field_mapping', {}) if isinstance(item.result_json, dict) else {}), + 'created_at': item.created_at.isoformat() if item.created_at else None, + 'expires_at': item.expires_at.isoformat() if item.expires_at else None, + 'promoted_profile_draft_id': ((item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None), + }) + return result + + +def create_parsing_profile_draft_from_temporary_session( + session_no: str, + data: dict[str, Any], + *, + actor_id: int | None, +) -> dict[str, Any]: + """ + 管理员把已确认临时库存会话沉淀为库存文件解析方案草稿。 + + 核心逻辑:只接受已通过确定性质量校验的临时会话,强制复用其锁定映射和结构; + 管理员仍需维护方案编码、显示名称和订单匹配键。创建结果始终是 draft,不能绕过原有发布/站点启用门禁。 + + Args: + session_no: 已确认的临时库存会话编号。 + data: 管理员填写的 profile_code、display_name、match_keys;字段映射由后端忽略客户端输入并锁定会话版本。 + actor_id: 当前管理员用户 ID。 + + Returns: + 新建的库存文件解析方案草稿。 + """ + normalized_no = str(session_no or '').strip().upper() + item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none() + if item is None: + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + if item.status != 'confirmed_for_temporary_use': + raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + confirmed = (item.result_json or {}).get('confirmed_usage') if isinstance(item.result_json, dict) else None + if not isinstance(confirmed, dict) or not isinstance(confirmed.get('field_mapping'), dict): + raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + existing_draft_id = (item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None + if existing_draft_id: + existing_draft = db.session.get(ShippingInventoryParsingProfile, existing_draft_id) + if existing_draft is not None: + from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload + + return profile_payload(existing_draft) + analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + if analysis is None: + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} + payload = { + 'profile_code': data.get('profile_code'), + 'display_name': data.get('display_name'), + 'sheet_name': structure.get('selected_sheet_name'), + 'header_row_index': structure.get('selected_header_row_index'), + 'field_mapping': confirmed['field_mapping'], + 'match_keys': data.get('match_keys'), + } + from app.services.shipping_notice import inventory_structure_analysis + + draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id) + item.result_json = { + **(item.result_json if isinstance(item.result_json, dict) else {}), + 'promoted_profile_draft_id': draft['id'], + 'promoted_at': datetime.utcnow().isoformat(), + 'promoted_by': actor_id, + } + db.session.commit() + return draft diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/inventory_upload.py index d875d93a..b5df3522 100644 --- a/backend/app/services/shipping_notice/inventory_upload.py +++ b/backend/app/services/shipping_notice/inventory_upload.py @@ -22,12 +22,7 @@ from werkzeug.datastructures import FileStorage from app.models import ShippingInventoryFile, ShippingTask from app.services.shipping_notice.export import _storage_root from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path -from app.services.shipping_notice.inventory_snapshot import ( - parse_inventory_excel_with_meta, - read_inventory_schema_preview, -) - -_TASK_INVENTORY_SUFFIXES = (".xlsx", ".csv") +_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv") _TASK_INVENTORY_MARKER = ".current_inventory" _TASK_INVENTORY_VERSION_PREFIX = "inventory_" @@ -214,7 +209,7 @@ def _task_inventory_upload_dir(task_no: str) -> Path: def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path: """ 任务级库存附件标准落盘路径(默认 inventory.xlsx)。 - suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。 + suffix 仅允许 .xls / .xlsx / .csv,用于 RPA 回调保留源文件格式。 """ normalized = (suffix or ".xlsx").lower() if normalized not in _TASK_INVENTORY_SUFFIXES: @@ -261,8 +256,8 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path: """保存 werkzeug FileStorage 库存上传并返回落盘路径。""" suffix = ".xlsx" filename = str(getattr(upload, "filename", "") or "").lower() - if filename.endswith(".csv"): - suffix = ".csv" + if filename.endswith((".xls", ".csv")): + suffix = Path(filename).suffix staging_dir = _task_inventory_upload_dir(task_no) / ".staging" staging_dir.mkdir(parents=True, exist_ok=True) staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}" @@ -278,8 +273,8 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat 保存本地已存在的库存文件到任务标准库存目录。 【AI 触发时机】:当 RPA 或其他后台流程已经拿到本地 Excel,需要把它正式纳入系统托管目录时调用。 - 核心逻辑:校验 source_path 存在后,统一复制到 inventory_uploads/{task_no}/inventory.xlsx, - 让 RPA 下载与人工上传共用同一套任务级库存附件路径。 + 核心逻辑:校验 source_path 存在后,按源文件格式复制到版本化任务附件路径, + 让 RPA 下载与人工上传共用同一套任务级库存附件路径,并保留 .xls/.xlsx/.csv 格式。 Args: task_no: 发货任务号,禁止为空。 @@ -314,7 +309,7 @@ def stage_task_inventory_callback_file( ) -> Path: """ 将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。 - 核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。 + 核心逻辑:按源文件格式落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}{suffix}。 Args: task_no: 发货任务号。 @@ -393,47 +388,3 @@ def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None: path.parent.rmdir() except OSError: pass - - -def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]: - """读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。""" - path = resolve_task_inventory_upload_path(task_no) - if path is None: - raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件") - preview = read_inventory_schema_preview(path) - preview["upload_filename"] = path.name - return preview - - -def parse_uploaded_task_inventory( - task_no: str, - *, - field_mapping: dict[str, str] | None = None, - mapping_source: str = "rules", - header_row_index: int | None = None, - llm_match_rule: str | None = None, - llm_match_key: list[str] | None = None, -) -> tuple[list[dict[str, Any]], dict[str, Any], Path]: - """ - 解析已上传的任务库存 Excel。 - - Returns: - tuple: (inventory_lines, column_meta, 文件路径)。 - """ - path = resolve_task_inventory_upload_path(task_no) - if path is None: - raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件") - lines, column_meta = parse_inventory_excel_with_meta( - path, - field_mapping=field_mapping, - mapping_source=mapping_source, - header_row_index=header_row_index, - llm_match_rule=llm_match_rule, - llm_match_key=llm_match_key, - ) - return lines, column_meta, path - - -def has_uploaded_task_inventory(task_no: str) -> bool: - """任务是否已有落盘的库存附件(.xlsx 或 .csv)。""" - return resolve_task_inventory_upload_path(task_no) is not None diff --git a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py b/backend/app/services/shipping_notice/inventory_warehouse_resolution.py new file mode 100644 index 00000000..626facf4 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_warehouse_resolution.py @@ -0,0 +1,70 @@ +""" +services/shipping_notice/inventory_warehouse_resolution.py + +用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。 +依赖:ShippingInventoryField/Source、动态订单字段投影、task_line_store。 +逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from app.models import ShippingInventoryField, ShippingInventorySource +from app.services.shipping_notice.export import order_field_id_values + + +@dataclass(frozen=True) +class WarehouseResolution: + """动态 Warehouse 决策结果;不唯一或缺失时不可继续链接。""" + + warehouse_id: str | None + reason: str = '' + + +def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: + """按配置字段 ID 构造大小写不敏感的精确匹配键。""" + values = tuple(str(row.get(field) or '').strip().casefold() for field in fields) + return values if values and all(values) else None + + +def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution: + """按站点已发布解析方案为全部订单行寻找唯一 Warehouse。""" + source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first() + definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} + match_keys = definition.get('match_keys') if isinstance(definition, dict) else [] + order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)] + inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys if isinstance(item, dict)] + mapped_ids = { + int(field_id) for field_id in (definition.get('field_mapping') or {}) + if str(field_id).isdigit() + } if isinstance(definition, dict) else set() + warehouse_fields = ShippingInventoryField.query.filter( + ShippingInventoryField.id.in_(mapped_ids), ShippingInventoryField.status == 'active', + ShippingInventoryField.usage_type == 'warehouse_identity', + ).all() if mapped_ids else [] + if not order_fields or len(order_fields) != len(inventory_fields) or len(warehouse_fields) != 1: + return WarehouseResolution(None, 'warehouse_configuration_invalid') + + warehouse_field_id = str(warehouse_fields[0].id) + rows_by_key: dict[tuple[str, ...], set[str]] = {} + fallback = str(fallback_warehouse_id or '').strip().upper() + for row in inventory_lines: + if not isinstance(row, dict): + continue + key = _key(row, inventory_fields) + warehouse = str(row.get(warehouse_field_id) or fallback).strip().upper() + if key and warehouse: + rows_by_key.setdefault(key, set()).add(warehouse) + + warehouses: set[str] = set() + _header_values, order_lines = order_field_id_values(task) + for order_line in order_lines: + key = _key(order_line, order_fields) + if not key or not rows_by_key.get(key): + return WarehouseResolution(None, 'warehouse_not_found_for_order_line') + warehouses.update(rows_by_key[key]) + if len(warehouses) != 1: + return WarehouseResolution(None, 'warehouse_ambiguous' if warehouses else 'warehouse_not_found') + return WarehouseResolution(next(iter(warehouses))) diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 7999dc5b..decae7c8 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -1,10 +1,9 @@ """ services/shipping_notice/inventory_workflow.py -用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。 -依赖:customer_identity_gate、reservation_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine、task_line_store。 -逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain; - Reservation 门禁订单行经 read_task_order_lines 读取。 +用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。 +依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、task_line_store。 +逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。 """ from __future__ import annotations @@ -16,43 +15,12 @@ from app import db from app.core.errors import AppError from app.models import ShippingTask from app.services.shipping_notice.constants import ( - AUTO_MAP, CP_INVENTORY_SOURCE_REVIEW, - CP_MAP_INFER, - CP_UPLOAD_REQ, - SUGGEST_OK, - payload_map_json, -) -from app.services.shipping_notice.inventory_mapping import ( - mapping_is_complete, - normalize_field_mapping, - validate_field_mapping_against_headers, -) -from app.services.shipping_notice.inventory_mapping_store import ( - resolve_inventory_mapping, - upsert_inventory_mapping, -) -from app.services.shipping_notice.inventory_mapping_workflow import ( - awaiting_inventory_mapping_confirm, - inventory_loaded_response, - inventory_mapping_checkpoint_response, ) +from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response from app.services.shipping_notice.inventory_file_store import ( - active_inventory_file_for_task, - has_uploaded_inventory_file, - parse_linked_inventory_file, - read_linked_inventory_schema_preview, save_batch_inventory_upload, ) -from app.services.shipping_notice.inventory_snapshot import parse_inventory_text -from app.services.shipping_notice.inventory_upload import ( - has_uploaded_task_inventory, - inventory_text_max_chars, - parse_uploaded_task_inventory, - read_task_inventory_schema_preview, - save_task_inventory_upload, -) -from app.services.shipping_notice.match_rule_desc import extract_mapping_payload_extras from app.services.shipping_notice.query_service import ( get_task_by_ref, resolve_task_from_payload, @@ -89,43 +57,6 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non return None -def _resolve_inventory_field_mapping(payload: dict[str, Any]) -> tuple[dict[str, str] | None, str]: - raw = payload_map_json(payload) - field_mapping = normalize_field_mapping(raw) - if field_mapping: - return field_mapping, "llm" - return None, "rules" - - -def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]: - data: dict[str, Any] | None = None - if isinstance(raw, dict): - data = raw - elif isinstance(raw, str) and raw.strip(): - try: - parsed = json.loads(raw) - if isinstance(parsed, dict): - data = parsed - except json.JSONDecodeError: - data = None - if not data: - return {} - - inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data - if not isinstance(inner, dict): - return {} - - result: dict[str, str] = {} - for key in ("part_number", "aws_part_number", "reservation_id", "available_qty"): - value = inner.get(key) - if value is None: - continue - text = str(value).strip() - if text: - result[key] = text - return result - - def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, Any] | None: """ 库存入口统一检查订单侧 Reservation ID。 @@ -192,312 +123,8 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: return None -def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: - """Parse inventory from uploaded file, chat text, or structured JSON.""" - lang = resolve_lang(payload) - task = resolve_task_from_payload(payload) - if not task: - return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) - - gate_resp = _inventory_source_gate_response(task, operation="parse_inventory", lang=lang) - if gate_resp is not None: - return gate_resp - - # [STEP 1] 先归一化库存输入来源与映射提示。 - # 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。 - use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in { - "1", - "true", - "yes", - } - raw_text = str(payload.get("raw_inventory_text") or "").strip() - inventory_lines = parse_inventory_lines(payload) - warnings: list[str] = [] - column_meta: dict[str, Any] | None = None - source = "parse" - field_mapping, mapping_source = _resolve_inventory_field_mapping(payload) - mapping_extras = extract_mapping_payload_extras(payload_map_json(payload)) - if mapping_extras.get("match_rule"): - mapping_source = "llm" - - # [STEP 2] 按来源解析库存内容。 - # 优先复用已上传文件;否则再回退到 structured 或 raw_text,避免大 Excel 直接走 LLM 文本链路。 - has_uploaded_file = has_uploaded_inventory_file(task) or has_uploaded_task_inventory(task.task_no) - if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_file): - if not has_uploaded_file: - return tool_response( - status="needs_human", - task=task, - message=t("workflow.inventory.uploaded_file_missing", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, - stop_agent_turn=True, - ) - inv_file = active_inventory_file_for_task(task) - if inv_file: - inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file( - task, - field_mapping=field_mapping, - mapping_source=mapping_source, - llm_match_rule=mapping_extras.get("match_rule"), - llm_match_key=mapping_extras.get("match_key"), - ) - else: - inventory_lines, column_meta, path = parse_uploaded_task_inventory( - task.task_no, - field_mapping=field_mapping, - mapping_source=mapping_source, - llm_match_rule=mapping_extras.get("match_rule"), - llm_match_key=mapping_extras.get("match_key"), - ) - source = "uploaded_file" - warnings.append(f"parsed from uploaded file: {path.name}") - elif not inventory_lines: - structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None - if structured and isinstance(structured.get("lines"), list): - inventory_lines = structured["lines"] - source = "structured" - elif raw_text: - max_chars = inventory_text_max_chars() - if len(raw_text) > max_chars: - log_task_event( - task, - "inventory_text_too_large", - {"chars": len(raw_text), "max_chars": max_chars}, - ) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=t("workflow.inventory.text_too_large", lang=lang).format( - chars=len(raw_text), - max_chars=max_chars, - ), - data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, - next_required_action=t("workflow.inventory.upload_then_parse", lang=lang), - forbidden_next_tools=["match_inventory"], - stop_agent_turn=True, - ) - inventory_lines, warnings, column_meta = parse_inventory_text( - raw_text, - field_mapping=field_mapping, - ) - - # [STEP 3] 对解析失败和成功分别进入下一阶段。 - # 失败时停在人审检查点;成功时统一委托 inventory_loaded_response 进入字段对齐/自动串联。 - if not inventory_lines: - log_task_event(task, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded}) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message=t("workflow.inventory.parse_failed", lang=lang), - data={**serialize_task_for_tool(task), "warnings": warnings}, - checkpoint=CP_MAP_INFER, - ) - - return inventory_loaded_response( - task, - inventory_lines, - warnings=warnings, - column_meta=column_meta, - source=source, - require_mapping_review=True, - event_type="inventory_parsed", - chain_payload=payload, - ) - - -def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]: - """Return headers + sample rows for LLM column mapping (small payload).""" - lang = resolve_lang(payload) - task = resolve_task_from_payload(payload) - if not task: - return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) - - gate_resp = _inventory_source_gate_response(task, operation="get_inventory_schema_preview", lang=lang) - if gate_resp is not None: - return gate_resp - - if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no): - return tool_response( - status="needs_human", - task=task, - message=t("workflow.inventory.uploaded_file_missing", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, - stop_agent_turn=True, - ) - - try: - if has_uploaded_inventory_file(task): - preview = read_linked_inventory_schema_preview(task) - else: - preview = read_task_inventory_schema_preview(task.task_no) - except OSError as exc: - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc), - ) - - log_task_event(task, "inventory_schema_preview", {"headers": preview.get("headers")}) - db.session.commit() - return tool_response( - status="ok", - task=task, - message=t("workflow.inventory.preview_ready", lang=lang), - data={**serialize_task_for_tool(task), "schema_preview": preview}, - checkpoint=CP_MAP_INFER, - next_required_action=t("workflow.inventory.preview_next", lang=lang), - forbidden_next_tools=["match_inventory"], - ) - - -def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]: - """Apply LLM/manual column mapping and parse full uploaded inventory file.""" - lang = resolve_lang(payload) - task = resolve_task_from_payload(payload) - if not task: - return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) - - gate_resp = _inventory_source_gate_response(task, operation="apply_inventory_mapping", lang=lang) - if gate_resp is not None: - return gate_resp - - # [STEP 1] 先校验上传文件与 schema preview 是否存在。 - # 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。 - if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no): - return tool_response( - status="needs_human", - task=task, - message=t("workflow.inventory.uploaded_file_missing_short", lang=lang), - data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, - stop_agent_turn=True, - ) - - try: - if has_uploaded_inventory_file(task): - preview = read_linked_inventory_schema_preview(task) - else: - preview = read_task_inventory_schema_preview(task.task_no) - except OSError as exc: - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc), - ) - - raw = payload_map_json(payload) - - # [STEP 2] 汇总映射候选来源。 - # direct/partial 来自本次 map_json,template/suggested 来自历史模板和表头预判,按完整度决定优先级。 - direct = normalize_field_mapping(raw) - partial = _extract_partial_inventory_field_mapping(raw) - template: dict[str, str] = {} - if task.customer_code: - resolved = resolve_inventory_mapping(task.customer_code, preview=preview) - if isinstance(resolved, dict): - template = {k: str(v).strip() for k, v in resolved.items() if str(v or "").strip()} - - suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {} - suggested = {k: str(v).strip() for k, v in suggested.items() if str(v or "").strip()} - - base: dict[str, str] = {} - if mapping_is_complete(template): - base = template - elif mapping_is_complete(suggested): - base = suggested - else: - base = {**template, **suggested} - - field_mapping = direct or {**base, **partial} - mapping_extras = extract_mapping_payload_extras(raw) - if direct or partial or mapping_extras.get("match_rule"): - mapping_source = "llm" - else: - mapping_source = "rules" - if not mapping_is_complete(field_mapping): - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.inventory.mapping_invalid", lang=lang), - data={ - **serialize_task_for_tool(task), - "schema_preview": preview, - "suggested_mapping": suggested, - "template_mapping": template if template else None, - "received_mapping": partial or None, - }, - ) - - # [STEP 3] 确认映射与真实表头一致,再解析整份上传文件。 - # 只有列名校验通过后才允许落地库存明细,避免错误映射污染后续匹配链路。 - mapping_errors = validate_field_mapping_against_headers( - preview.get("headers") or [], - field_mapping, - ) - if mapping_errors: - header_row = preview.get("header_row_index") or 1 - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.inventory.mapping_header_mismatch", lang=lang).format( - row=header_row, - errors=" ".join(mapping_errors), - ), - data={**serialize_task_for_tool(task), "schema_preview": preview}, - ) - - try: - inv_file = active_inventory_file_for_task(task) - if inv_file: - inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file( - task, - field_mapping=field_mapping, - mapping_source=mapping_source, - header_row_index=preview.get("header_row_index"), - llm_match_rule=mapping_extras.get("match_rule"), - llm_match_key=mapping_extras.get("match_key"), - ) - else: - inventory_lines, column_meta, path = parse_uploaded_task_inventory( - task.task_no, - field_mapping=field_mapping, - mapping_source=mapping_source, - header_row_index=preview.get("header_row_index"), - llm_match_rule=mapping_extras.get("match_rule"), - llm_match_key=mapping_extras.get("match_key"), - ) - except FileNotFoundError as exc: - return tool_response(status="failed", task_id=task.task_no, message=str(exc)) - except OSError as exc: - return tool_response( - status="failed", - task_id=task.task_no, - message=t("workflow.inventory.parse_failed_detail", lang=lang).format(error=exc), - ) - - warnings = [f"parsed with mapping from uploaded file: {path.name}"] - upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping) - return inventory_loaded_response( - task, - inventory_lines, - warnings=warnings, - column_meta=column_meta, - source="uploaded_file_mapping", - require_mapping_review=True, - event_type="inventory_mapping_applied", - chain_payload=payload, - field_mapping=field_mapping, - mapping_source=mapping_source, - ) - - def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: - """Save multipart Excel; return schema preview for LLM mapping (no full parse).""" + """按任务库存站点的 published Profile 保存并确定性解析人工库存文件。""" task = get_task_by_ref(str(task_id or "")) if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh")) @@ -522,7 +149,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: ) filename = str(upload.filename or "").strip() - if not filename.lower().endswith((".xlsx", ".csv")): + if not filename.lower().endswith((".xls", ".xlsx", ".csv")): return tool_response( status="failed", task_id=task.task_no, @@ -541,14 +168,20 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: ) db.session.flush() inv_file = save_batch_inventory_upload(task, upload) - preview = read_linked_inventory_schema_preview(task) + inventory_lines = [ + item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict) + ] + preview = dict(inv_file.schema_preview_json or {}) except AppError as exc: db.session.rollback() + message = str(exc.message or "库存上传被拒绝") + if exc.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED': + message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。' return tool_response( status="failed", task=task, task_id=task.task_no, - message=str(exc.message or "库存上传被拒绝"), + message=message, data=serialize_task_for_tool(task), stop_agent_turn=True, ) @@ -560,39 +193,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: message=t("workflow.inventory.save_failed", lang=lang).format(error=exc), ) - template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview) - if template_mapping and mapping_is_complete(template_mapping): - try: - inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file( - task, - field_mapping=template_mapping, - mapping_source="template", - ) - if inventory_lines: - warnings = [f"parsed from template mapping: {path.name}"] - return inventory_loaded_response( - task, - inventory_lines, - warnings=warnings, - column_meta=column_meta, - source="uploaded_file_template", - require_mapping_review=True, - event_type="inventory_template_mapping_used", - field_mapping=template_mapping, - mapping_source="template", - ) - except Exception: - pass - - suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {} - suggested_clean = {k: str(v).strip() for k, v in suggested.items() if str(v).strip()} - suggested_complete = mapping_is_complete(suggested_clean) - auto_map = ( - json.dumps(suggested_clean, ensure_ascii=False) if suggested_complete else None - ) - - apply_task_transition(task, TaskTransition.MAP_INFER) - log_task_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")}) + structure_validation = preview.get('structure_validation') if isinstance( + preview.get('structure_validation'), dict + ) else {} + column_meta = { + 'structure_validation': structure_validation, + } + log_task_event(task, "inventory_file_uploaded", { + "filename": filename, + "headers": preview.get("headers"), + "structure_validation": structure_validation, + "parser_contract": "published_profile", + }) log_task_event( task, "inventory_snapshot_created", @@ -602,33 +214,15 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: "batch_no": task.batch.batch_no if task.batch else None, }, ) - db.session.commit() - upload_message = t("workflow.inventory.uploaded", lang=lang) - if suggested_complete: - upload_message += t("workflow.inventory.uploaded_suggested_complete", lang=lang) - else: - upload_message += t("workflow.inventory.uploaded_need_llm", lang=lang) - return tool_response( - status="ok", - task=task, - message=upload_message, - data={ - **serialize_task_for_tool(task), - "batch_no": task.batch.batch_no if task.batch else None, - "batch": serialize_batch_for_tool(task.batch) if task.batch else None, - "schema_preview": preview, - "inventory_file_no": inv_file.inventory_file_no, - "share_mode": inv_file.share_mode, - "linked_task_nos": [ - link.task.task_no - for link in (inv_file.links or []) - if link.is_active and link.task - ], - SUGGEST_OK: suggested_complete, - AUTO_MAP: auto_map, - }, - next_required_action=t("workflow.inventory.apply_mapping_next", lang=lang), - forbidden_next_tools=["match_inventory"], + return inventory_loaded_response( + task, + inventory_lines, + warnings=list(structure_validation.get('warnings') or []), + column_meta=column_meta, + source='manual_upload_published_profile', + event_type='inventory_manual_upload_ready', + field_mapping=dict(inv_file.field_mapping_json or {}), + mapping_source='parsing_profile', ) @@ -652,23 +246,31 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: task, inventory_lines, source="manual_json", - require_mapping_review=False, event_type="inventory_uploaded", ) - # [STEP 2] 如果允许自动模式,就优先交给 RPA 获取库存。 - # auto / retry_rpa 都属于“先尝试系统拉取库存”,避免不必要地要求用户手工上传。 - if mode == "retry_rpa" or mode == "auto": + # [STEP 2] 正常流程只复用已完成的库存快照,绝不隐式触发 RPA。 + # 库存导出由独立排程生产;用户明确选择 retry_rpa 才允许本任务发起刷新。 + if mode == "retry_rpa": from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa return ensure_inventory_via_rpa(task, mode=mode) - # [STEP 3] 最后处理已有快照与彻底缺库存两种兜底分支。 + if mode == "auto": + from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + + reused = _try_reuse_inventory_snapshot( + task, + task_rpa_inventory_source(task) or {}, + mode=mode, + ) + if reused is not None: + return reused + + # [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。 # 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。 if task.inventory_lines_json: - if awaiting_inventory_mapping_confirm(task): - lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() - return inventory_mapping_checkpoint_response(task, lang=lang or None) apply_task_transition(task, TaskTransition.INVENTORY_READY) db.session.commit() return tool_response( @@ -679,6 +281,15 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) apply_task_transition(task, TaskTransition.INV_UNAVAIL) + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="needs_human", + message=t("workflow.inventory.unavailable", lang=lang), + progress_percent=0, + detail=t("workflow.inventory.unavailable", lang=lang), + ) log_task_event(task, "inventory_missing", {}) db.session.commit() return tool_response( diff --git a/backend/app/services/shipping_notice/match.py b/backend/app/services/shipping_notice/match.py index 35378cd0..ff274131 100644 --- a/backend/app/services/shipping_notice/match.py +++ b/backend/app/services/shipping_notice/match.py @@ -1,9 +1,9 @@ """ services/shipping_notice/match.py -用途:执行订单行与库存行的匹配、缺货判断与匹配结果汇总。 -依赖:shipping_notice.i18n、reservation_id 归一化工具、标准聚合逻辑。 -逻辑:由 fulfillment_workflow.match_inventory 调用本文件,把通知订单行与库存快照比对后返回匹配状态和缺货明细。 +用途:按解析方案配置的字段关系执行库存匹配、缺货判断与结果汇总。 +依赖:shipping_notice.i18n、动态订单字段投影、标准聚合逻辑。 +逻辑:由 fulfillment_workflow 传入订单字段 ID、库存字段 ID 和数量字段 ID,字段名称不参与匹配。 """ from __future__ import annotations @@ -11,69 +11,56 @@ from __future__ import annotations from typing import Any, Callable from app.services.shipping_notice.i18n import resolve_lang, t -from app.services.shipping_notice.reservation_id import validated_reservation_id - - def _norm(value: Any) -> str: return str(value or "").strip() -def _norm_reservation(value: Any) -> str: - return validated_reservation_id(value) +def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: + """按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。""" + values = tuple(_norm(row.get(field)).casefold() for field in fields) + return values if values and all(values) else None -def _line_key(part_number: str, reservation_id: str | None) -> tuple[str, str]: - """构造内部料号与 Reservation 的库存定位键。""" - return (_norm(part_number), _norm_reservation(reservation_id)) - - -def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]: - """按库存 part_number 与 reservation_id 汇总 available_qty。""" - totals: dict[tuple[str, str], float] = {} +def _aggregate_inventory( + inventory_lines: list[dict[str, Any]], *, match_fields: list[str], quantity_field: str, +) -> dict[tuple[str, ...], float]: + """按用户配置的库存匹配字段组合汇总唯一数量字段。""" + totals: dict[tuple[str, ...], float] = {} for row in inventory_lines: - part_number = _norm(row.get("part_number")) - if not part_number: - continue - reservation_id = _norm_reservation(row.get("reservation_id")) - if not reservation_id: + key = _line_key(row, match_fields) + if key is None: continue try: - qty = float(row.get("available_qty") or 0) + qty = float(row.get(quantity_field) or 0) except (TypeError, ValueError): qty = 0.0 - key = _line_key(part_number, reservation_id) totals[key] = totals.get(key, 0.0) + qty return totals -def _available_for_notice_line( - part_number: str, - reservation_id: str | None, - inv_totals: dict[tuple[str, str], float], -) -> float: - part_number_normalized = _norm(part_number) - rid = _norm_reservation(reservation_id) - if not rid: - return 0.0 - return inv_totals.get((part_number_normalized, rid), 0.0) - - def match_notice_lines( notice_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], *, + match_keys: list[dict[str, str]], + quantity_field_id: str, progress_callback: Callable[[int, int], None] | None = None, ) -> tuple[str, list[dict[str, Any]], dict[str, Any]]: """ - 将订单行与库存行按 (part_number, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。 + 按订单字段 ID 到库存字段 ID 的配置关系匹配,计算 fulfillable/partial/unfulfillable。 核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。 Returns: tuple: (match_status, line_results, shortage_json)。 """ - # [STEP 1] 库存 Supplier Sku 已规范为 part_number,与订单内部料号直接配对。 - inv_totals = _aggregate_inventory(inventory_lines) + order_fields = [str(item.get('order_field_id') or '') for item in match_keys] + inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys] + if not order_fields or any(not item for item in order_fields + inventory_fields) or not quantity_field_id: + raise ValueError('库存解析方案缺少有效的匹配字段或库存数量字段') + inv_totals = _aggregate_inventory( + inventory_lines, match_fields=inventory_fields, quantity_field=quantity_field_id, + ) line_results: list[dict[str, Any]] = [] shortages: list[dict[str, Any]] = [] @@ -83,14 +70,13 @@ def match_notice_lines( # [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。 total_lines = len(notice_lines) for index, line in enumerate(notice_lines, start=1): - part_number = _norm(line.get("part_number")) - reservation_id = _norm_reservation(line.get("reservation_id")) or None + order_key = _line_key(line, order_fields) try: - required = float(line.get("qty") or 0) + required = float(line.get("__required_qty") or 0) except (TypeError, ValueError): required = 0.0 - available = _available_for_notice_line(part_number, reservation_id, inv_totals) + available = inv_totals.get(order_key, 0.0) if order_key is not None else 0.0 if available >= required: line_status = "ok" shortage = 0.0 @@ -104,8 +90,11 @@ def match_notice_lines( has_shortage = True result = { - "part_number": part_number, - "reservation_id": reservation_id or "", + "part_number": _norm(line.get("__display_part_number")), + "reservation_id": _norm(line.get("__display_reservation_id")), + "order_match_values": { + order_field: line.get(order_field) for order_field in order_fields + }, "required_qty": required, "available_qty": available, "shortage_qty": shortage, diff --git a/backend/app/services/shipping_notice/match_rule_desc.py b/backend/app/services/shipping_notice/match_rule_desc.py index 8c7e02b4..a9481271 100644 --- a/backend/app/services/shipping_notice/match_rule_desc.py +++ b/backend/app/services/shipping_notice/match_rule_desc.py @@ -1,65 +1,13 @@ """ services/shipping_notice/match_rule_desc.py -用途:解析 map_json 中的匹配规则扩展字段,并生成用户可读的匹配规则说明。 -依赖:标准 `json` 解析与 `typing` 工具。 -逻辑:由 inventory_mapping、field_alignment_summary 等模块调用本文件,把匹配规则和附加说明渲染成展示文案。 +用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。 +依赖:标准类型能力。 +逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。 """ from __future__ import annotations -from typing import Any - - -def _payload_root(raw: Any) -> dict[str, Any] | None: - data: dict[str, Any] | None = None - if isinstance(raw, dict): - data = raw - elif isinstance(raw, str) and raw.strip(): - import json - - try: - parsed = json.loads(raw) - if isinstance(parsed, dict): - data = parsed - except json.JSONDecodeError: - return None - return data - - -def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]: - """从 map_json 读取 match_rule / match_key 等 LLM 扩展字段(非列名映射)。""" - data = _payload_root(raw) - if not data: - return {} - - inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data - if not isinstance(inner, dict): - inner = data - - match_rule = str( - data.get("match_rule") - or data.get("matching_rule") - or inner.get("match_rule") - or inner.get("matching_rule") - or "" - ).strip() - - match_key_raw = data.get("match_key") or inner.get("match_key") - match_key: list[str] | None = None - if isinstance(match_key_raw, list): - match_key = [str(k).strip() for k in match_key_raw if str(k).strip()] - elif isinstance(match_key_raw, str) and match_key_raw.strip(): - match_key = [part.strip() for part in match_key_raw.split(",") if part.strip()] - - extras: dict[str, Any] = {} - if match_rule: - extras["match_rule"] = match_rule - if match_key: - extras["match_key"] = match_key - return extras - - def infer_match_key(field_mapping: dict[str, str]) -> list[str]: """根据库存列映射推断业务匹配键列表(默认 part_number + reservation_id)。""" keys = ["part_number"] @@ -73,7 +21,7 @@ def build_match_rule_fallback( *, match_key: list[str] | None = None, ) -> str: - """LLM 未提供 match_rule 时,根据列映射动态生成中文规则说明。""" + """根据已确认的栏位映射动态生成中文规则说明。""" part_number_col = str(field_mapping.get("part_number") or "Supplier Sku").strip() or "Supplier Sku" qty_col = str(field_mapping.get("available_qty") or "可用数量").strip() or "可用数量" keys = match_key or infer_match_key(field_mapping) @@ -92,12 +40,7 @@ def build_match_rule_fallback( def resolve_match_rule( field_mapping: dict[str, str], - *, - llm_match_rule: str | None = None, - llm_match_key: list[str] | None = None, ) -> tuple[str, list[str], str]: - """返回 (match_rule, match_key, match_rule_source);优先 LLM 规则,否则 fallback。""" - keys = llm_match_key or infer_match_key(field_mapping) - if llm_match_rule and str(llm_match_rule).strip(): - return str(llm_match_rule).strip(), keys, "llm" - return build_match_rule_fallback(field_mapping, match_key=keys), keys, "fallback" + """返回由已确认栏位映射生成的匹配说明、匹配键及规则来源。""" + keys = infer_match_key(field_mapping) + return build_match_rule_fallback(field_mapping, match_key=keys), keys, "configured_mapping" diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py index 79ceb0a7..ede27caa 100644 --- a/backend/app/services/shipping_notice/openapi_spec.py +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -10,9 +10,6 @@ from __future__ import annotations from typing import Any -from app.services.shipping_notice.constants import MAP_JSON - - def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]: prop: dict[str, Any] = {"type": "string", "description": description} if enum: @@ -77,6 +74,30 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: runtime_context = _str_prop( "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改" ) + observation_schema = { + "type": "object", + "required": ["value", "document_id", "quote"], + "properties": { + "value": {"description": "从证据原文提取的字段值,类型必须符合动态字段契约"}, + "document_id": _int_prop("证据来源 Document ID,必须来自抽取上下文"), + "quote": _str_prop("证据原文中的逐字引用,HXOPS 将验证其确实存在"), + "confidence": {"type": "number", "minimum": 0, "maximum": 1}, + }, + "additionalProperties": False, + } + extracted_field_schema = { + "type": "object", + "required": ["field_id", "observations"], + "properties": { + "field_id": _str_prop("动态字段契约中的稳定 field_id,禁止传 field_code 或显示名称"), + "observations": { + "type": "array", + "minItems": 1, + "items": observation_schema, + }, + }, + "additionalProperties": False, + } return { "openapi": "3.0.0", @@ -107,7 +128,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: required=["agent_runtime_context"], description=( "仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户," - "并返回 input_snapshot_hash、documents 与固定输出契约;禁止让 LLM 传 user_id。" + "并返回 input_snapshot_hash、documents 与当前 published 动态 Schema 契约;禁止让 LLM 传 user_id。" ), ), "/tools/submit_order_extraction": _post_op( @@ -123,61 +144,43 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "items": { "type": "object", "required": [ + "schema_version_id", + "schema_checksum", "source_intake_no", "primary_document_id", "classification", "classification_confidence", - "field_confidence", + "header_fields", "lines", - "evidence", ], "properties": { "source_intake_no": _str_prop("来源 Intake 编号,必须来自上下文"), + "schema_version_id": _int_prop("context.contract.schema_version_id,必须原样回传"), + "schema_checksum": _str_prop("context.contract.checksum,必须原样回传"), "primary_document_id": _int_prop("主来源 Document ID,必须来自上下文"), "candidate_key_hint": _str_prop("可选稳定订单标识,如 PO/订单号;不得使用随机值"), "classification": _str_prop("仅 shipping_request 可自动建单", enum=["shipping_request", "non_shipping_request", "uncertain"]), "classification_confidence": {"type": "number", "minimum": 0, "maximum": 1}, - "field_confidence": { - "type": "object", - "required": ["part_number", "qty"], - "properties": { - "part_number": {"type": "number", "minimum": 0, "maximum": 1}, - "qty": {"type": "number", "minimum": 0, "maximum": 1}, - }, + "header_fields": { + "type": "array", + "description": "Header scope 动态字段;仅可使用 context.contract.fields 中的稳定 field_id", + "items": extracted_field_schema, }, - "po_number": _str_prop("可为空的 PO/订单号"), "lines": { "type": "array", "items": { "type": "object", - "required": ["part_number", "qty"], + "required": ["fields"], "properties": { - "part_number": _str_prop("内部料号/主匹配料号"), - "qty": {"type": "number", "exclusiveMinimum": 0}, - "reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"), - "inventory_source_hint": _str_prop( - "可选库存来源提示;仅在原文有可靠证据时填写," - "不代表任务通知来源或已确认的库存连接器类型" - ), - "customer_part_number": _str_prop("可选客户料号"), - "aws_part_number": _str_prop("可选 AWS 料号"), + "fields": { + "type": "array", + "description": "Line scope 动态字段;每项含 field_id 与 observations[]", + "items": extracted_field_schema, + }, }, "additionalProperties": False, }, }, - "evidence": { - "type": "array", - "description": "至少分别提供内部料号与 Qty 原文证据,元素含 field 与非空 quote", - "items": { - "type": "object", - "required": ["field", "quote"], - "properties": { - "field": _str_prop("证据字段,如 lines[0].part_number 或 lines[0].qty"), - "quote": _str_prop("原文片段,禁止改写"), - "document_id": _int_prop("证据来源 Document ID"), - }, - }, - }, "conflicts": { "type": "array", "items": {"type": "object", "additionalProperties": True}, @@ -189,13 +192,73 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: }, required=["agent_runtime_context", "input_snapshot_hash", "orders"], description=( - "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、内部料号/Qty 置信度及原文证据均达标," - "且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失," - "订单行 inventory_source_hint 是可选路由线索并独立持久化。" + "只接受同一快照和同一 Schema checksum。Dify 必须逐字段返回稳定 field_id 与 observations[];" + "每个 Observation 包含 value、document_id、逐字 quote 和可选 confidence。" + "HXOPS 验证原文、执行类型/validator/证据策略与跨 Document 裁决后,才按 field_code 投影给下游。" "响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、" "non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。" ), ), + "/tools/create_temporary_inventory_session": _post_op( + "create_temporary_inventory_session", + "创建对话上传库存文件的临时分析会话", + { + "agent_runtime_context": runtime_context, + "asset_no": _str_prop("当前用户上传的 FileAsset 编号;必须是 xls、xlsx 或 csv"), + }, + required=["agent_runtime_context", "asset_no"], + description=( + "仅在用户明确说明附件为库存文件的 temporary_inventory 分支调用。" + "后端按会话用户校验资产归属并执行结构初检;不会创建生产库存快照、" + "不会绑定库存站点、不会执行库存匹配。" + ), + ), + "/tools/get_temporary_inventory_session": _post_op( + "get_temporary_inventory_session", + "读取临时库存文件的脱敏结构分析和方案候选", + { + "agent_runtime_context": runtime_context, + "temporary_session_no": _str_prop("create_temporary_inventory_session 返回的临时会话编号"), + }, + required=["agent_runtime_context", "temporary_session_no"], + description=( + "返回后端已分析的工作表、表头、字段目录和已发布方案候选,不返回样例库存值。" + "Dify 不得读取文件路径、全量库存行,也不得据此直接宣称库存已可用于订单匹配。" + ), + ), + "/tools/submit_temporary_inventory_mapping_suggestion": _post_op( + "submit_temporary_inventory_mapping_suggestion", + "保存对话临时库存的候选字段映射", + { + "agent_runtime_context": runtime_context, + "temporary_session_no": _str_prop("临时库存会话编号"), + "field_mapping": { + "type": "object", + "description": "库存字段目录 ID 到真实来源表头的映射;只能使用 get_temporary_inventory_session 返回的字段 ID 和表头", + "additionalProperties": {"type": "string"}, + }, + }, + required=["agent_runtime_context", "temporary_session_no", "field_mapping"], + description=( + "仅在没有 exact 已发布方案可复用时调用。HXOPS 校验字段目录、真实表头、重复列和核心字段完整性," + "只保存待用户确认的候选;不会发布方案、绑定库存站点、创建库存快照或执行订单匹配。" + ), + ), + "/tools/confirm_temporary_inventory_use": _post_op( + "confirm_temporary_inventory_use", + "确认当前对话临时库存文件使用", + { + "agent_runtime_context": runtime_context, + "temporary_session_no": _str_prop("临时库存会话编号"), + "selected_profile_id": _int_prop("仅 exact 已发布方案候选时由用户选择的方案 ID"), + }, + required=["agent_runtime_context", "temporary_session_no"], + description=( + "仅在用户明确确认本次使用后调用。HXOPS 重新确定性解析文件并校验料号、预约号、库存数量;" + "只锁定当前对话的临时会话审计,不接受任务编号,绝不创建生产库存快照、绑定库存站点、" + "写入任务库存行或执行库存匹配。" + ), + ), "/tools/parse_notice": _post_op( "parse_notice", "解析发货通知文本", @@ -267,38 +330,18 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: }, required=["task_id", "line_index"], ), - "/tools/get_inventory_schema_preview": _post_op( - "get_inventory_schema_preview", - "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)", - {"task_id": task_id}, - required=["task_id"], - ), - "/tools/apply_inventory_mapping": _post_op( - "apply_inventory_mapping", - "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑", - { - "task_id": task_id, - MAP_JSON: _str_prop( - "Dify Tool 参数使用 JSON 字符串,内容含 part_number/reservation_id/available_qty," - "可选 aws_part_number;" - "可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。" - ), - }, - required=["task_id", MAP_JSON], - ), "/tools/confirm_inventory_source": _post_op( "confirm_inventory_source", "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)", { "task_id": task_id, "source_code": _str_prop( - "启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;" - "站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传" + "启用配置中的库存源编码;Warehouse 由 fixed Source 配置或库存行匹配解析,禁止前端直传" ), }, required=["task_id", "source_code"], description=( - "库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id," + "库存连接器门禁:稳定身份须具备 source_code、connector_type;fixed Source 同时具备 warehouse_id," "且 routing_fingerprint 与当前配置版本一致。" "Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。" "若返回 needs_human,说明身份未完整解析或需先完成解析确认。" @@ -324,8 +367,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "task_id": task_id, "conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"), "decision": _str_prop( - "confirm=确认继续;reject=驳回;retry_rpa=重新获取库存(清理旧库存解析状态并重新触发 RPA);rematch=重新匹配;reparse=重新解析;" - "confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存", + "confirm=确认继续;reject=驳回;retry_rpa=按已发布解析方案重新获取库存;rematch=重新匹配;reparse=重新解析", enum=[ "confirm", "confirm_parse", @@ -333,9 +375,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "retry_rpa", "rematch", "reparse", - "confirm_inventory_mapping", - "correct_inventory_mapping", - "reparse_inventory", ], ), "comment": _str_prop("备注(可选)"), @@ -358,7 +397,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]: "conversation_id": _str_prop("Dify 会话 ID"), }, description=( - "返回 inventory_source_code、inventory_connector_type、inventory_site_id、" + "返回 inventory_source_code、inventory_connector_type、" "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_customer_matching.py b/backend/app/services/shipping_notice/order_customer_matching.py new file mode 100644 index 00000000..92ba2025 --- /dev/null +++ b/backend/app/services/shipping_notice/order_customer_matching.py @@ -0,0 +1,246 @@ +""" +backend/app/services/shipping_notice/order_customer_matching.py + +用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。 +依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。 +逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerSite, + ShippingCustomerSiteIdentifier, + ShippingOrderCustomerMatch, + ShippingOrderExtraction, +) +from app.services.shipping_notice.customer_normalization import normalize_customer_name + +ROLE_FIELDS = { + 'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'}, + 'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'}, +} + + +def _normalized_code(value: Any) -> str: + """规范外部客户/站点编码,保留业务符号并统一大小写。""" + return str(value or '').strip().upper() + + +def _customer_candidates(raw_name: str) -> list[dict[str, Any]]: + """按标准名称和 approved 名称别名返回稳定去重的启用客户候选。""" + normalized = normalize_customer_name(raw_name) + if not normalized: + return [] + customers = db.session.query(ShippingCustomer).filter_by(status='active').all() + matched: dict[int, dict[str, Any]] = {} + for customer in customers: + if normalize_customer_name(customer.standard_name) == normalized: + matched[customer.id] = { + 'customer_id': customer.id, + 'standard_name': customer.standard_name, + 'short_code': customer.short_code, + 'matched_by': ['standard_name'], + } + aliases = db.session.query(ShippingCustomerIdentifier).filter_by( + identifier_type='name_alias', normalized_value=normalized, status='approved', + ).all() + active_by_id = {customer.id: customer for customer in customers} + for alias in aliases: + customer = active_by_id.get(int(alias.customer_id)) + if customer is None: + continue + candidate = matched.setdefault(customer.id, { + 'customer_id': customer.id, + 'standard_name': customer.standard_name, + 'short_code': customer.short_code, + 'matched_by': [], + }) + if 'name_alias' not in candidate['matched_by']: + candidate['matched_by'].append('name_alias') + return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id'])) + + +def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]: + """优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。""" + code = _normalized_code(external_code) + source = _normalized_code(source_system) + if code and source: + refs = db.session.query(ShippingCustomerExternalRef).filter_by( + source_system=source, legacy_customer_key=code, + ).all() + candidates = [] + for ref in refs: + customer = db.session.get(ShippingCustomer, int(ref.customer_id)) + if customer and customer.status == 'active': + candidates.append({ + 'customer_id': customer.id, 'standard_name': customer.standard_name, + 'short_code': customer.short_code, 'site_id': None, 'site_name': None, + 'site_code': None, 'matched_by': ['external_customer_code'], + }) + if candidates: + return candidates + return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)] + + +def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]: + """优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。""" + code = _normalized_code(external_code) + source = _normalized_code(source_system) + sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all() + matched: dict[int, dict[str, Any]] = {} + matched_site_ids: dict[int, str] = {} + if code: + identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by( + identifier_type='external_code', source_system=source, normalized_value=code, status='approved', + ).all() + for identifier in identifiers: + matched_site_ids[int(identifier.site_id)] = 'external_site_code' + for site in sites: + if _normalized_code(site.site_code) == code: + matched_site_ids[site.id] = 'site_code' + if not matched_site_ids: + normalized = normalize_customer_name(raw_name) if raw_name else '' + for site in sites: + if normalized and normalize_customer_name(site.site_name) == normalized: + matched_site_ids[site.id] = 'site_name' + if normalized: + identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by( + identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved', + ).all() + for identifier in identifiers: + matched_site_ids[int(identifier.site_id)] = 'site_name_alias' + by_id = {site.id: site for site in sites} + for site_id, matched_by in matched_site_ids.items(): + site = by_id.get(site_id) + customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None + if site is None or customer is None or customer.status != 'active': + continue + matched[site.id] = { + 'customer_id': customer.id, 'standard_name': customer.standard_name, + 'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name, + 'site_code': site.site_code, 'matched_by': [matched_by], + } + return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id'])) + + +def refresh_order_customer_matches( + extraction: ShippingOrderExtraction, + header: dict[str, Any], +) -> list[dict[str, Any]]: + """ + 根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。 + + Args: + extraction: 已持久化的动态订单解析记录。 + header: 已通过证据裁决的订单头字段投影。 + Returns: + 两种角色的匹配摘要;客户简称只来自客户主数据快照。 + """ + results: list[dict[str, Any]] = [] + for role, fields in ROLE_FIELDS.items(): + raw_name = str(header.get(fields['name']) or '').strip() + external_code = _normalized_code(header.get(fields['code'])) + source_system = _normalized_code(header.get(fields['source'])) + candidates = ( + _bill_to_candidates(raw_name, external_code, source_system) + if role == 'bill_to' + else _ship_to_candidates(raw_name, external_code, source_system) + ) + row = db.session.query(ShippingOrderCustomerMatch).filter_by( + extraction_id=extraction.id, role=role, + ).one_or_none() + if row is None: + row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role) + db.session.add(row) + row.raw_name = raw_name or None + row.normalized_name = normalize_customer_name(raw_name) if raw_name else None + row.source_system = source_system or None + row.external_code = external_code or None + row.candidates_json = candidates + if len(candidates) == 1: + candidate = candidates[0] + row.status = 'unique_candidate' + row.customer_id = int(candidate['customer_id']) + row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None + row.customer_name_snapshot = str(candidate['standard_name']) + row.customer_short_code_snapshot = str(candidate['short_code']) + row.resolution_method = str(candidate['matched_by'][0]) + else: + row.status = 'ambiguous' if candidates else 'unmatched' + row.customer_id = None + row.site_id = None + row.customer_name_snapshot = None + row.customer_short_code_snapshot = None + row.resolution_method = None + row.confirmed_by_id = None + row.confirmed_at = None + row.updated_at = datetime.utcnow() + db.session.flush() + results.append(serialize_order_customer_match(row)) + return results + + +def confirm_order_customer_match( + extraction_id: int, + *, + role: str, + customer_id: int, + site_id: int | None = None, + actor_id: int | None, +) -> dict[str, Any]: + """人工确认某个订单客户角色;Ship-to 必须同时选择所属客户的启用站点。""" + if role not in ROLE_FIELDS: + raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID') + row = db.session.query(ShippingOrderCustomerMatch).filter_by( + extraction_id=extraction_id, role=role, + ).one_or_none() + if row is None: + raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_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 used', code='SHIPPING.CUSTOMER_INACTIVE') + selected_site = None + if role == 'ship_to': + selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None + if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active': + raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID') + row.status = 'confirmed' + row.customer_id = customer.id + row.site_id = selected_site.id if selected_site else None + row.customer_name_snapshot = customer.standard_name + row.customer_short_code_snapshot = customer.short_code + row.resolution_method = 'manual' + row.confirmed_by_id = actor_id + row.confirmed_at = datetime.utcnow() + db.session.commit() + return serialize_order_customer_match(row) + + +def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]: + """输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。""" + return { + 'id': row.id, + 'extraction_id': row.extraction_id, + 'role': row.role, + 'raw_name': row.raw_name, + 'status': row.status, + 'customer_id': row.customer_id, + 'site_id': row.site_id, + 'source_system': row.source_system, + 'external_code': row.external_code, + 'standard_name': row.customer_name_snapshot, + 'short_code': row.customer_short_code_snapshot, + 'candidates': list(row.candidates_json or []), + 'resolution_method': row.resolution_method, + } diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 14030f26..cfe73f87 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -27,6 +27,8 @@ from app.models import ( ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, + ShippingOrderExtraction, + ShippingTask, ) from app.services.agent_runtime_context.parser import parse_agent_runtime_context from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates @@ -42,16 +44,7 @@ from app.services.shipping_notice.duplicate_detection import ( detect_duplicates_for_candidate, ) from app.services.shipping_notice.document_candidate_persist import generate_candidate_no -from app.services.shipping_notice.order_extraction_evidence import ( - adjudicate_order_reservations, - verify_reservation_evidence, -) -from app.services.shipping_notice.field_adjudication import ( - adjudicate_order_fields, - merge_observation_history, - trusted_required_fields, -) -from app.services.shipping_notice.reservation_id import validated_reservation_id +from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version _CONTEXT_PATHS = [ 'agent_code', @@ -120,9 +113,15 @@ def _load_intakes( for row in rows: if row.conversation_id and row.conversation_id != session.session_id: raise ForbiddenError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话') + if row.parse_status == 'consumed' or row.consumed_at is not None: + if allow_consumed: + continue + raise ConflictError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED', + message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果', + ) ready = row.parse_status == 'parsed' and row.consumed_at is None - replayable = allow_consumed and row.parse_status == 'consumed' - if not ready and not replayable: + if not ready: raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理') if row.conversation_id is None: row.conversation_id = session.session_id @@ -276,7 +275,13 @@ def start_order_extraction( now = datetime.utcnow() intake_ids: list[int] = [] for intake in intakes: - if intake.parse_status != 'parsed' or intake.consumed_at is not None: + if intake.parse_status == 'consumed' or intake.consumed_at is not None: + db.session.rollback() + raise ConflictError( + code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED', + message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果', + ) + if intake.parse_status != 'parsed': db.session.rollback() raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理') if intake.conversation_id and intake.conversation_id != session_value: @@ -686,13 +691,7 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]: row.intake_no: dict(row.structured_result_json or {}).get('rule_hints') or {} for row in intakes }, - 'contract': { - 'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'], - 'auto_create_required_line_fields': ['part_number', 'qty'], - 'required_process_line_fields': ['reservation_id'], - 'optional_routing_line_fields': ['inventory_source_hint'], - 'allowed_missing_process_fields': ['reservation_id'], - }, + 'contract': dify_contract(published_version()), } @@ -900,52 +899,32 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: document_non_shipping_indexes[int(document.id)].append(index) continue - summary = dict(raw_order) - summary.pop('evidence', None) - summary.pop('field_confidence', None) - summary.pop('classification_confidence', None) - summary.pop('candidate_key_hint', None) - summary.pop('classification', None) - summary.pop('source_intake_no', None) - summary.pop('primary_document_id', None) - field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {} - field_adjudication = adjudicate_order_fields( - summary, + dynamic = persist_dynamic_order( raw_order=raw_order, + intake_id=int(intake.id), + snapshot_hash=current_snapshot, documents=owned_docs, - field_confidence=field_confidence, + actor_id=int(session.user_id), ) - normalized = field_adjudication['summary'] - blocking_conflicts.extend(field_adjudication['conflicts']) - assessment = assess_candidate_business_summary(normalized) - normalized, backend_conflicts = adjudicate_order_reservations( - assessment['normalized_summary'], - documents=owned_docs, - ) - assessment = assess_candidate_business_summary(normalized) + summary = {**dynamic['header'], 'lines': dynamic['lines']} + # Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。 + if summary.get('bill_to_customer'): + summary['customer_name'] = summary['bill_to_customer'] + if dynamic['blocked_fields']: + blocking_conflicts.extend([ + { + 'field': item.get('field_code'), + 'severity': 'blocking', + 'reason': item.get('reason_code') or 'dynamic_schema_required_or_evidence_gate', + } + for item in dynamic['decisions'] + if item.get('status') not in {'accepted', 'corroborated'} + ] or [{ + 'field': ','.join(dynamic['blocked_fields']), 'severity': 'blocking', + 'reason': 'dynamic_schema_required_or_evidence_gate', + }]) + assessment = assess_candidate_business_summary(summary) normalized = assessment['normalized_summary'] - blocking_conflicts.extend(backend_conflicts) - # [STEP] 证据核验对齐裁决后的行值,门禁比较 (line_index, reservation_id) pair, - # 避免仅比 index 时把被裁决改写过的 Reservation 误判为已核验。 - order_for_evidence = dict(raw_order) - order_for_evidence['lines'] = list(normalized.get('lines') or []) - verified_reservation_evidence = verify_reservation_evidence( - order_for_evidence, - documents=owned_docs, - ) - reservation_pairs = { - (line_index, reservation_id) - for line_index, line in enumerate(normalized.get('lines') or []) - if isinstance(line, dict) - for reservation_id in [validated_reservation_id(line.get('reservation_id'))] - if reservation_id - } - verified_reservation_pairs = { - (int(item['line_index']), validated_reservation_id(item.get('reservation_id'))) - for item in verified_reservation_evidence - if str(item.get('line_index', '')).isdigit() - and validated_reservation_id(item.get('reservation_id')) - } reasons: list[str] = [] if classification != 'shipping_request': reasons.append('not_shipping_request') @@ -953,10 +932,8 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: reasons.append('missing_or_invalid_part_number_qty') if classification_confidence < class_threshold: reasons.append('low_classification_confidence') - if not trusted_required_fields(field_adjudication): - reasons.append('untrusted_part_number_qty_adjudication') - if reservation_pairs - verified_reservation_pairs: - reasons.append('unverified_reservation_evidence') + if dynamic['blocked_fields']: + reasons.append('dynamic_schema_gate') if blocking_conflicts: reasons.append('blocking_conflict') @@ -978,32 +955,13 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: candidate_key=candidate_key, ) db.session.add(candidate) - previous_structured = ( - candidate.structured_result_json - if isinstance(candidate.structured_result_json, dict) - else {} - ) - previous_extraction = ( - previous_structured.get('extraction') - if isinstance(previous_structured.get('extraction'), dict) - else {} - ) - previous_adjudication = ( - previous_extraction.get('field_adjudication') - if isinstance(previous_extraction.get('field_adjudication'), dict) - else {} - ) - observation_history = merge_observation_history( - previous_adjudication.get('observation_history') or previous_adjudication.get('observations'), - field_adjudication['observations'], - ) candidate.primary_document_id = int(document.id) candidate.source_order_index = index candidate.extraction_source = 'dify_chatflow' candidate.classification_confidence = classification_confidence - candidate.field_confidence_json = dict(field_confidence) + candidate.field_confidence_json = {} candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields']) - candidate.evidence_json = [item for item in (raw_order.get('evidence') or []) if isinstance(item, dict)] + candidate.evidence_json = list(dynamic['observations']) candidate.po_number = str(normalized.get('po_number') or '').strip() or None candidate.confidence = classification_confidence candidate.conflicts_json = blocking_conflicts @@ -1024,19 +982,36 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: 'request_id': request_id, 'classification': classification, 'classification_confidence': classification_confidence, - 'field_confidence': field_confidence, + 'field_confidence': {}, 'field_adjudication': { - 'schema_version': field_adjudication['schema_version'], - 'observations': field_adjudication['observations'], - 'observation_history': observation_history, - 'decisions': field_adjudication['decisions'], - 'conflicts': field_adjudication['conflicts'], + 'schema_version_id': int(dynamic['extraction'].schema_version_id), + 'extraction_id': int(dynamic['extraction'].id), + 'observations': dynamic['observations'], + 'decisions': dynamic['decisions'], + 'conflicts': blocking_conflicts, }, + 'customer_matches': dynamic['customer_matches'], 'missing_required_fields': assessment['missing_required_fields'], 'missing_process_fields': assessment['missing_process_fields'], 'process_issues': assessment['process_issues'], 'auto_create_reasons': reasons, - 'verified_reservation_evidence': verified_reservation_evidence, + 'verified_reservation_evidence': [ + { + 'line_index': int(item.get('line_position') or 0), + 'reservation_id': item.get('value'), + 'document_id': next( + ( + observation.get('document_id') + for observation in dynamic['observations'] + if observation.get('id') in set(item.get('observation_ids') or []) + ), + None, + ), + } + for item in dynamic['decisions'] + if item.get('status') in {'accepted', 'corroborated'} + and item.get('field_code') == 'reservation_id' + ], }, } duplicate = detect_duplicates_for_candidate( @@ -1135,6 +1110,21 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]: candidate_nos=auto_candidate_nos, create_idempotency_key=idem, ) + # [STEP 4A] Candidate 被创建或打开到 Task 后,回填当前动态订单真相版本。 + for candidate in auto_candidates: + if candidate.consumed_task_id is None: + continue + extraction_data = ( + candidate.structured_result_json.get('extraction', {}).get('field_adjudication', {}) + if isinstance(candidate.structured_result_json, dict) + else {} + ) + extraction_id = extraction_data.get('extraction_id') if isinstance(extraction_data, dict) else None + task = db.session.get(ShippingTask, int(candidate.consumed_task_id)) + if task is not None and str(extraction_id or '').isdigit(): + task.current_order_extraction_id = int(extraction_id) + db.session.get(ShippingOrderExtraction, int(extraction_id)).task_id = int(task.id) + db.session.commit() else: # [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。 if not pending: diff --git a/backend/app/services/shipping_notice/order_schema/__init__.py b/backend/app/services/shipping_notice/order_schema/__init__.py new file mode 100644 index 00000000..cb70205b --- /dev/null +++ b/backend/app/services/shipping_notice/order_schema/__init__.py @@ -0,0 +1,11 @@ +""" +backend/app/services/shipping_notice/order_schema/__init__.py + +用途:货代订单唯一 Schema 领域服务入口。 +依赖:registry、service。 +逻辑:管理 API 和后续订单抽取链从本包读取受控字段能力与已发布契约。 +""" + +from app.services.shipping_notice.order_schema.service import get_published_contract + +__all__ = ['get_published_contract'] diff --git a/backend/app/services/shipping_notice/order_schema/diff.py b/backend/app/services/shipping_notice/order_schema/diff.py new file mode 100644 index 00000000..5b34a78c --- /dev/null +++ b/backend/app/services/shipping_notice/order_schema/diff.py @@ -0,0 +1,114 @@ +""" +backend/app/services/shipping_notice/order_schema/diff.py + +用途:计算订单 Schema 版本定义之间可直接展示的语义化字段差异。 +依赖:无数据库依赖,仅处理 version definition JSON。 +逻辑:以稳定 field_id 配对字段;集合属性与顺序分别比较,避免字段重命名被误判为删除和新增。 +""" + +from __future__ import annotations + +from typing import Any + + +_SCALAR_KEYS = ( + 'field_code', 'scope', 'value_type', 'enabled', 'display_name', 'description', + 'required', 'normalizer_key', 'relation_role', 'comparator_key', + 'extraction_instruction', 'sequence', +) +_SET_KEYS = ('aliases', 'validator_keys', 'enum_options') +_EVIDENCE_POLICY_KEYS = ('required', 'source_precedence', 'conflict_policy', 'allow_single_source') + + +def _field_map(definition: dict[str, Any] | None) -> dict[str, dict[str, Any]]: + """按稳定 field_id 索引字段,忽略不完整的历史快照条目。""" + return { + str(field['field_id']): field + for field in (definition or {}).get('fields', []) + if isinstance(field, dict) and field.get('field_id') is not None + } + + +def _set_change(key: str, before: Any, after: Any) -> dict[str, Any] | None: + """比较无序字符串集合,并显式返回新增、移除和原始值以便界面呈现。""" + before_items = list(before or []) + after_items = list(after or []) + before_set = set(before_items) + after_set = set(after_items) + if before_set == after_set and before_items == after_items: + return None + return { + 'key': key, + 'kind': 'set', + 'before': before_items, + 'after': after_items, + 'added': sorted(after_set - before_set), + 'removed': sorted(before_set - after_set), + 'order_changed': before_set == after_set and before_items != after_items, + } + + +def _field_changes(before: dict[str, Any], after: dict[str, Any]) -> list[dict[str, Any]]: + """返回同一字段的属性级变更,证据策略按子属性而非整个对象展示。""" + changes: list[dict[str, Any]] = [] + for key in _SCALAR_KEYS: + if before.get(key) != after.get(key): + changes.append({'key': key, 'kind': 'value', 'before': before.get(key), 'after': after.get(key)}) + for key in _SET_KEYS: + change = _set_change(key, before.get(key), after.get(key)) + if change: + changes.append(change) + before_policy = before.get('evidence_policy') or {} + after_policy = after.get('evidence_policy') or {} + for key in _EVIDENCE_POLICY_KEYS: + qualified_key = f'evidence_policy.{key}' + if key == 'source_precedence': + change = _set_change(qualified_key, before_policy.get(key), after_policy.get(key)) + if change: + changes.append(change) + elif before_policy.get(key) != after_policy.get(key): + changes.append({ + 'key': qualified_key, + 'kind': 'value', + 'before': before_policy.get(key), + 'after': after_policy.get(key), + }) + return changes + + +def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]: + """ + 计算两个 Schema 定义的字段级差异。 + + Args: + before: 作为基线的完整版本 definition。 + after: 用来比较的完整版本 definition。 + Returns: + 包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构。 + """ + before_fields = _field_map(before) + after_fields = _field_map(after) + field_ids = sorted(set(before_fields) | set(after_fields)) + fields: list[dict[str, Any]] = [] + counts = {'added': 0, 'removed': 0, 'modified': 0, 'unchanged': 0} + for field_id in field_ids: + previous = before_fields.get(field_id) + current = after_fields.get(field_id) + if previous is None: + change_type = 'added' + changes: list[dict[str, Any]] = [] + elif current is None: + change_type = 'removed' + changes = [] + else: + changes = _field_changes(previous, current) + change_type = 'modified' if changes else 'unchanged' + counts[change_type] += 1 + fields.append({ + 'field_id': field_id, + 'change_type': change_type, + 'before': previous, + 'after': current, + 'changes': changes, + }) + return {'summary': counts, 'fields': fields} diff --git a/backend/app/services/shipping_notice/order_schema/registry.py b/backend/app/services/shipping_notice/order_schema/registry.py new file mode 100644 index 00000000..737b5f49 --- /dev/null +++ b/backend/app/services/shipping_notice/order_schema/registry.py @@ -0,0 +1,74 @@ +""" +backend/app/services/shipping_notice/order_schema/registry.py + +用途:维护订单字段类型、规范化器、校验器、比较器和证据策略白名单。 +依赖:无。 +逻辑:管理员配置只能引用本模块声明的安全能力;运行期解析器在后续阶段复用同一目录。 +""" + +from __future__ import annotations + +FIELD_TYPES = {'string', 'decimal', 'integer', 'date', 'boolean', 'enum'} +FIELD_SCOPES = {'header', 'line'} +NORMALIZERS = { + 'trim', 'uppercase_trim', 'lowercase_trim', 'decimal', 'integer', 'iso_date', + 'boolean', 'reservation_id', +} +VALIDATORS = { + 'non_empty', 'positive_decimal', 'non_negative_decimal', 'positive_integer', + 'reservation_id', 'atomic_part_number', 'iso_date', +} +COMPARATORS = {'normalized_text', 'case_insensitive_text', 'decimal', 'integer', 'date', 'boolean', 'reservation_id'} +RELATION_ROLES = {None, 'primary_link', 'secondary_link', 'line_match'} +SOURCE_TYPES = { + 'attachment_table', 'attachment_text', 'email_body_table', 'email_body_text', + 'backend_table', 'dify_llm', +} +CONFLICT_POLICIES = {'block', 'review', 'prefer_attachment', 'prefer_email'} +TYPE_NORMALIZERS = { + 'string': {'trim', 'uppercase_trim', 'lowercase_trim', 'reservation_id'}, + 'decimal': {'decimal'}, + 'integer': {'integer'}, + 'date': {'iso_date'}, + 'boolean': {'boolean'}, + 'enum': {'trim', 'uppercase_trim', 'lowercase_trim'}, +} +TYPE_COMPARATORS = { + 'string': {'normalized_text', 'case_insensitive_text', 'reservation_id'}, + 'decimal': {'decimal'}, + 'integer': {'integer'}, + 'date': {'date'}, + 'boolean': {'boolean'}, + 'enum': {'normalized_text', 'case_insensitive_text'}, +} +TYPE_VALIDATORS = { + 'string': {'non_empty', 'reservation_id', 'atomic_part_number'}, + 'decimal': {'non_empty', 'positive_decimal', 'non_negative_decimal'}, + 'integer': {'non_empty', 'positive_integer'}, + 'date': {'non_empty', 'iso_date'}, + 'boolean': set(), + 'enum': {'non_empty'}, +} +ADMIN_HIDDEN_RULES = {'reservation_id'} + + +def _admin_rules(values: set[str]) -> list[str]: + """隐藏字段专用的内部兼容规则,避免管理员将其误用到普通文本字段。""" + return sorted(values - ADMIN_HIDDEN_RULES) + + +def catalog() -> dict[str, list[str] | dict[str, list[str]]]: + """返回管理端字段编辑器可选目录及按字段类型收窄后的兼容矩阵。""" + return { + 'field_types': sorted(FIELD_TYPES), + 'field_scopes': sorted(FIELD_SCOPES), + 'normalizers': _admin_rules(NORMALIZERS), + 'validators': _admin_rules(VALIDATORS), + 'comparators': _admin_rules(COMPARATORS), + 'relation_roles': sorted(item for item in RELATION_ROLES if item), + 'source_types': sorted(SOURCE_TYPES), + 'conflict_policies': sorted(CONFLICT_POLICIES), + 'type_normalizers': {key: _admin_rules(value) for key, value in TYPE_NORMALIZERS.items()}, + 'type_validators': {key: _admin_rules(value) for key, value in TYPE_VALIDATORS.items()}, + 'type_comparators': {key: _admin_rules(value) for key, value in TYPE_COMPARATORS.items()}, + } diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py new file mode 100644 index 00000000..1df0ebd5 --- /dev/null +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -0,0 +1,423 @@ +""" +backend/app/services/shipping_notice/order_schema/runtime.py + +用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。 +依赖:订单 Schema 动态模型、ShippingNoticeDocument、registry、订单客户匹配服务。 +逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from decimal import Decimal, InvalidOperation +from typing import Any + +from app.core.errors import ConflictError, ValidationError +from app.extensions import db +from app.models import ( + ShippingNoticeDocument, + ShippingOrderExtraction, + ShippingOrderFieldDecision, + ShippingOrderFieldObservation, + ShippingOrderFieldValue, + ShippingOrderLine, + ShippingOrderSchemaVersion, +) +from app.services.shipping_notice.notice_lines import parse_notice_table_text +from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches +from app.services.shipping_notice.reservation_id import validated_reservation_id + + +def published_version() -> ShippingOrderSchemaVersion: + """读取当前唯一 published 订单 Schema;未发布时阻断解析。""" + version = ShippingOrderSchemaVersion.query.filter_by(status='published').first() + if version is None: + raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED') + return version + + +def dify_contract(version: ShippingOrderSchemaVersion) -> dict[str, Any]: + """编译 Dify 动态抽取契约;仅输出发布快照中 enabled 的字段。""" + fields = [ + dict(item) for item in (version.definition_json or {}).get('fields') or [] + if item.get('enabled', True) + ] + return { + 'schema_version_id': int(version.id), + 'schema_version': int(version.version), + 'checksum': version.checksum, + 'fields': fields, + 'submission_contract': { + 'field': {'field_id': '', 'observations': ''}, + 'observation': { + 'value': '', + 'document_id': '', + 'quote': '', + 'confidence': '', + }, + 'order': {'header_fields': '', 'lines': [{'fields': ''}]}, + }, + } + + +def _json_value(value: Any) -> Any: + """将 Decimal/date 转为 JSON 可安全持久化的标量。""" + if isinstance(value, Decimal): + return format(value, 'f') + if isinstance(value, date): + return value.isoformat() + return value + + +def _input_snapshot(*, intake_id: int, snapshot_hash: str, documents: list[ShippingNoticeDocument]) -> dict[str, Any]: + """冻结本次裁决使用的文档文本和指纹,供管理员重建输入证据而不回读可变 Document。""" + return { + 'intake_id': intake_id, + 'snapshot_hash': snapshot_hash, + 'documents': [ + { + 'id': int(document.id), + 'filename': document.filename, + 'document_type': document.document_type, + 'content_hash': document.content_hash, + 'extracted_text': document.extracted_text, + } + for document in documents + ], + } + + +def _normalize(value: Any, config: dict[str, Any]) -> Any: + """按发布字段类型与 normalizer 规范化候选值。""" + if value in (None, ''): + return None + value_type = str(config['value_type']) + normalizer = str(config.get('normalizer_key') or 'trim') + try: + if value_type == 'decimal': + return Decimal(str(value).replace(',', '').strip()) + if value_type == 'integer': + return int(str(value).replace(',', '').strip()) + if value_type == 'date': + return date.fromisoformat(str(value).strip()) + if value_type == 'boolean': + if isinstance(value, bool): + return value + lowered = str(value).strip().lower() + if lowered in {'true', '1', 'yes', 'y'}: + return True + if lowered in {'false', '0', 'no', 'n'}: + return False + raise ValueError('invalid boolean') + except (InvalidOperation, ValueError, TypeError) as exc: + raise ValidationError( + 'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT' + ) from exc + text = str(value).strip() + if normalizer == 'uppercase_trim': + text = text.upper() + elif normalizer == 'lowercase_trim': + text = text.lower() + if normalizer == 'reservation_id': + text = validated_reservation_id(text) or '' + if value_type == 'enum' and text not in set(config.get('enum_options') or []): + raise ValidationError('Dynamic enum value is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT') + return text or None + + +def _validate(value: Any, config: dict[str, Any]) -> bool: + """执行发布契约中受控 validator;返回值决定字段是否可被接受。""" + for key in config.get('validator_keys') or []: + if key == 'non_empty' and value in (None, ''): + return False + if key in {'positive_decimal', 'positive_integer'} and Decimal(str(value)) <= 0: + return False + if key == 'non_negative_decimal' and Decimal(str(value)) < 0: + return False + if key == 'reservation_id' and not validated_reservation_id(value): + return False + if key == 'atomic_part_number' and '/' in str(value): + return False + if key == 'iso_date' and not isinstance(value, date): + return False + return True + + +def _source_type(document: ShippingNoticeDocument) -> str: + """把 Document 技术类型映射为 Schema 证据来源类型。""" + return 'email_body_text' if document.document_type == 'body' else 'attachment_text' + + +def _verified_observations(raw: dict[str, Any], config: dict[str, Any], + documents: dict[int, ShippingNoticeDocument]) -> list[dict[str, Any]]: + """验证动态 Observation 的字段值、Document 归属、逐字 quote 与值包含关系。""" + items = raw.get('observations') if isinstance(raw.get('observations'), list) else [] + verified: list[dict[str, Any]] = [] + for item in items: + if not isinstance(item, dict) or not str(item.get('document_id') or '').isdigit(): + continue + document = documents.get(int(item['document_id'])) + value = _normalize(item.get('value'), config) + quote = str(item.get('quote') or '').strip() + if document is None or value is None or not _validate(value, config): + continue + if not quote or quote not in str(document.extracted_text or ''): + continue + if str(_json_value(value)).upper() not in quote.upper(): + continue + try: + confidence = max(0.0, min(float(item.get('confidence')), 1.0)) + except (TypeError, ValueError): + confidence = 0.0 + verified.append({ + 'value': value, + 'document': document, + 'quote': quote, + 'confidence': confidence, + 'source_type': _source_type(document), + }) + return verified + + +def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]: + """按一致性、来源优先级和冲突策略选择字段值。""" + if not observations: + return None, 'missing', 'evidence_missing' + groups: dict[str, list[dict[str, Any]]] = {} + for item in observations: + groups.setdefault(str(_json_value(item['value'])), []).append(item) + policy = dict(config.get('evidence_policy') or {}) + if len(groups) == 1: + value = observations[0]['value'] + distinct_documents = {int(item['document'].id) for item in observations} + if not policy.get('allow_single_source', True) and len(distinct_documents) < 2: + return value, 'needs_review', 'cross_document_evidence_required' + return value, 'corroborated' if len(distinct_documents) > 1 else 'accepted', None + + conflict_policy = str(policy.get('conflict_policy') or 'block') + preferred = { + 'prefer_attachment': {'attachment_text', 'attachment_table'}, + 'prefer_email': {'email_body_text', 'email_body_table'}, + }.get(conflict_policy) + if preferred: + hits = [item for item in observations if item['source_type'] in preferred] + preferred_values = {str(_json_value(item['value'])) for item in hits} + if len(preferred_values) == 1: + return hits[0]['value'], 'accepted', f'{conflict_policy}_resolved' + return observations[0]['value'], 'blocked' if conflict_policy == 'block' else 'needs_review', 'cross_source_conflict' + + +def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, raw: dict[str, Any], + config: dict[str, Any], documents: dict[int, ShippingNoticeDocument], + backend_candidates: list[dict[str, Any]]) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]: + """持久化字段全部 Observation、最终 Decision 和可查询类型化 Value。""" + candidates = _verified_observations(raw, config, documents) + candidates.extend(backend_candidates) + observation_rows: list[ShippingOrderFieldObservation] = [] + for item in candidates: + row = ShippingOrderFieldObservation( + extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], + source_document_id=int(item['document'].id), source_type=item['source_type'], + extractor=item.get('extractor') or 'dify_dynamic_schema', raw_value_json=_json_value(item['value']), + normalized_value_json=_json_value(item['value']), evidence_quote=item['quote'], + confidence=Decimal(str(item['confidence'])), evidence_verified=True, + ) + db.session.add(row) + observation_rows.append(row) + db.session.flush() + value, status, reason = _choose_value(candidates, config) + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], decision_status=status, + selected_observation_id=observation_rows[0].id if observation_rows else None, + supporting_observation_ids_json=[int(item.id) for item in observation_rows], + resolved_value_json=_json_value(value), reason_code=reason, + ) + db.session.add(decision) + db.session.flush() + if value is not None and status in {'accepted', 'corroborated'}: + value_type = str(config['value_type']) + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], decision_id=decision.id, + value_text=str(value) if value_type in {'string', 'enum'} else None, + value_decimal=value if value_type == 'decimal' else None, + value_integer=value if value_type == 'integer' else None, + value_date=value if value_type == 'date' else None, + value_boolean=value if value_type == 'boolean' else None, + value_json=_json_value(value), + )) + observations = [{ + 'id': int(item.id), 'field_id': config['field_id'], 'line_id': line_id, + 'source_type': item.source_type, 'document_id': item.source_document_id, + 'value': item.normalized_value_json, 'evidence_verified': bool(item.evidence_verified), + } for item in observation_rows] + decision_payload = { + 'id': int(decision.id), 'field_id': config['field_id'], 'field_code': config['field_code'], 'line_id': line_id, + 'status': status, 'value': _json_value(value), 'reason_code': reason, + 'observation_ids': list(decision.supporting_observation_ids_json or []), + } + return value, status, observations, decision_payload + + +def _backend_rows(documents: list[ShippingNoticeDocument]) -> list[dict[str, Any]]: + """从 EML/PDF Document 保留列边界的文本生成后端表格观察原料。""" + rows: list[dict[str, Any]] = [] + for document in documents: + for position, raw in enumerate(parse_notice_table_text(str(document.extracted_text or ''))): + if isinstance(raw, dict): + rows.append({**raw, '_document': document, '_position': position}) + return rows + + +def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, Any]], + rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """使用当前动态行任一稳定字段值关联后端表格行,避免按行号或目标字段自证。""" + signatures: list[tuple[str, str]] = [] + for raw in raw_fields: + if not isinstance(raw, dict): + continue + config = configs.get(str(raw.get('field_id') or '')) + if config is None: + continue + for item in raw.get('observations') or []: + if not isinstance(item, dict): + continue + value = _normalize(item.get('value'), config) + if value is not None: + signatures.append((str(config['field_code']), str(_json_value(value)))) + matched = [ + row for row in rows + if any( + row.get(code) not in (None, '') + and str(_json_value(_normalize(row.get(code), configs[next( + field_id for field_id, item in configs.items() if item['field_code'] == code + )]))) == value + for code, value in signatures + if any(item['field_code'] == code for item in configs.values()) + ) + ] + return matched + + +def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """从已关联后端表格行读取当前字段候选,用于一致或冲突裁决。""" + if not rows: + return [] + code = str(config['field_code']) + result: list[dict[str, Any]] = [] + for row in rows: + if row.get(code) in (None, ''): + continue + value = _normalize(row.get(code), config) + if value is None or not _validate(value, config): + continue + result.append({ + 'value': value, 'document': row['_document'], 'quote': None, 'confidence': 0.9, + 'source_type': 'backend_table', 'extractor': 'backend_table', + }) + return result + + +def persist_dynamic_order(*, raw_order: dict[str, Any], intake_id: int, snapshot_hash: str, + documents: list[ShippingNoticeDocument], actor_id: int | None) -> dict[str, Any]: + """裁决并保存一个动态订单,返回 field_code 下游投影与阻断字段。""" + version = published_version() + supplied_version = raw_order.get('schema_version_id') + supplied_checksum = str(raw_order.get('schema_checksum') or '') + if supplied_version != int(version.id) or supplied_checksum != str(version.checksum or ''): + raise ConflictError('Order schema changed', code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED') + configs = { + str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or [] + if item.get('enabled', True) + } + extraction = ShippingOrderExtraction( + intake_id=intake_id, schema_version_id=version.id, input_snapshot_hash=snapshot_hash, + input_snapshot_json=_input_snapshot( + intake_id=intake_id, snapshot_hash=snapshot_hash, documents=documents, + ), + status='extracting', raw_llm_output_json=raw_order, created_by_id=actor_id, + ) + db.session.add(extraction) + db.session.flush() + document_map = {int(item.id): item for item in documents} + header: dict[str, Any] = {} + line_projections: list[dict[str, Any]] = [] + blocked: list[str] = [] + observations: list[dict[str, Any]] = [] + decisions: list[dict[str, Any]] = [] + backend_rows = _backend_rows(documents) + groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [ + (None, None, 'header', raw_order.get('header_fields') or [], header) + ] + for position, raw_line in enumerate(raw_order.get('lines') or []): + if not isinstance(raw_line, dict): + raise ValidationError('Dynamic order line must be an object', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT') + line = ShippingOrderLine(extraction_id=extraction.id, position=position) + db.session.add(line) + db.session.flush() + projection: dict[str, Any] = {} + line_projections.append(projection) + groups.append((line.id, position, 'line', raw_line.get('fields') or [], projection)) + + # [STEP 1] 只接受发布契约内且 scope 正确的稳定字段 ID。 + seen: set[tuple[int | None, str]] = set() + for line_id, position, scope, raw_fields, projection in groups: + if not isinstance(raw_fields, list): + raise ValidationError('Dynamic fields must be arrays', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT') + associated_rows = _associated_backend_rows(raw_fields, configs, backend_rows) if position is not None else [] + for raw in raw_fields: + field_id = str(raw.get('field_id') or '') if isinstance(raw, dict) else '' + config = configs.get(field_id) + if config is None or config.get('scope') != scope or (line_id, field_id) in seen: + raise ValidationError('Dynamic field identity or scope is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT') + seen.add((line_id, field_id)) + value, status, field_observations, decision = _persist_field( + extraction=extraction, line_id=line_id, raw=raw, config=config, documents=document_map, + backend_candidates=_backend_candidates(config, rows=associated_rows), + ) + observations.extend(field_observations) + decision['line_position'] = position + decisions.append(decision) + if value is not None: + projection[str(config['field_code'])] = _json_value(value) + if status not in {'accepted', 'corroborated'}: + blocked.append(str(config['field_code'])) + + # [STEP 2] 未提交字段也必须形成 missing Decision,保证每个 Schema 字段都有可审计结果。 + for config in configs.values(): + field_id = str(config['field_id']) + if config.get('scope') != scope or (line_id, field_id) in seen: + continue + _value, status, field_observations, decision = _persist_field( + extraction=extraction, line_id=line_id, raw={}, config=config, documents=document_map, + backend_candidates=_backend_candidates(config, rows=associated_rows), + ) + decision['line_position'] = position + observations.extend(field_observations) + decisions.append(decision) + if config.get('required') and status not in {'accepted', 'corroborated'}: + blocked.append(str(config['field_code'])) + + # [STEP 3] Required 按 Header/每一 Line 检查,缺值和冲突都阻断自动建单。 + for config in configs.values(): + if not config.get('required'): + continue + code = str(config['field_code']) + if config['scope'] == 'header' and code not in header: + blocked.append(code) + if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)): + blocked.append(code) + extraction.normalized_result_json = {'header': header, 'lines': line_projections} + extraction.validation_result_json = {'blocked_fields': sorted(set(blocked))} + extraction.status = 'needs_review' if blocked else 'accepted' + extraction.updated_at = datetime.utcnow() + db.session.flush() + customer_matches = refresh_order_customer_matches(extraction, header) + return { + 'extraction': extraction, + 'header': header, + 'lines': line_projections, + 'blocked_fields': sorted(set(blocked)), + 'observations': observations, + 'decisions': decisions, + 'customer_matches': customer_matches, + } diff --git a/backend/app/services/shipping_notice/order_schema/service.py b/backend/app/services/shipping_notice/order_schema/service.py new file mode 100644 index 00000000..16d98aa2 --- /dev/null +++ b/backend/app/services/shipping_notice/order_schema/service.py @@ -0,0 +1,876 @@ +""" +backend/app/services/shipping_notice/order_schema/service.py + +用途:管理唯一订单 Schema、稳定字段目录、不可变版本和追加式配置审计。 +依赖:db、订单 Schema 模型、registry、统一 AppError。 +逻辑:草稿与发布版本统一读写 definition_json;乐观锁阻止覆盖;发布冻结快照并追加审计事件。 +""" + +from __future__ import annotations + +import hashlib +import json +import re +from datetime import datetime +from typing import Any + +from sqlalchemy import func + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + ShippingOrderField, + ShippingOrderFieldDecision, + ShippingOrderFieldObservation, + ShippingOrderFieldValue, + ShippingOrderSchema, + ShippingOrderSchemaAuditEvent, + ShippingOrderSchemaVersion, + ShippingOrderExtraction, + ShippingOrderFieldObservation, + ShippingOrderFieldDecision, + ShippingOrderFieldValue, + ShippingOrderLine, + User, +) +from app.services.shipping_notice.order_schema.registry import ( + COMPARATORS, + CONFLICT_POLICIES, + FIELD_SCOPES, + FIELD_TYPES, + NORMALIZERS, + RELATION_ROLES, + SOURCE_TYPES, + TYPE_COMPARATORS, + TYPE_NORMALIZERS, + TYPE_VALIDATORS, + VALIDATORS, + catalog, +) +from app.services.shipping_notice.order_schema.diff import compare_definitions + +SCHEMA_CODE = 'SHIPPING_ORDER' +FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$') +EVIDENCE_KEYS = {'required', 'source_precedence', 'conflict_policy', 'allow_single_source'} + + +def _iso(value: datetime | None) -> str | None: + """将可空时间转换为 API 使用的 ISO 字符串。""" + return value.isoformat() if value else None + + +def _schema() -> ShippingOrderSchema | None: + """读取唯一逻辑订单 Schema;不存在时返回 None。""" + return ShippingOrderSchema.query.filter_by(schema_code=SCHEMA_CODE).first() + + +def _require_schema() -> ShippingOrderSchema: + """读取唯一订单 Schema,不存在时抛出领域 404。""" + row = _schema() + if row is None: + raise NotFoundError('Shipping order schema not found', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND') + return row + + +def _field_payload(field: ShippingOrderField) -> dict[str, Any]: + """序列化稳定字段身份,不混入具体版本的显示和抽取规则。""" + return { + 'id': field.id, + 'field_code': field.field_code, + 'scope': field.scope, + 'value_type': field.value_type, + 'status': field.status, + 'published_once': bool(field.published_once), + 'created_at': _iso(field.created_at), + 'updated_at': _iso(field.updated_at), + } + + +def _copy_json(value: Any) -> Any: + """复制 JSON 兼容数据,避免 ORM 可变对象被后续修改污染审计快照。""" + return json.loads(json.dumps(value, ensure_ascii=True)) + + +def _definition(version: ShippingOrderSchemaVersion) -> dict[str, Any]: + """返回版本完整定义副本;草稿和发布版本均以此字段作为唯一配置真相。""" + return _copy_json(version.definition_json or {'schema_code': SCHEMA_CODE, 'version': version.version, 'fields': []}) + + +def _enabled_fields(definition: dict[str, Any]) -> list[dict[str, Any]]: + """筛选当前版本实际生效字段,供发布门禁和 Dify 运行契约复用。""" + return [dict(item) for item in definition.get('fields') or [] if item.get('enabled', True)] + + +def _audit_summary(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]: + """生成阶段一审计摘要;阶段三在此基础上提供完整字段级语义差异。""" + before_fields = {str(item.get('field_id')): item for item in (before or {}).get('fields', [])} + after_fields = {str(item.get('field_id')): item for item in (after or {}).get('fields', [])} + return { + 'before_field_count': len(before_fields), + 'after_field_count': len(after_fields), + 'added_field_ids': sorted(set(after_fields) - set(before_fields)), + 'removed_field_ids': sorted(set(before_fields) - set(after_fields)), + 'changed_field_ids': sorted( + field_id for field_id in set(before_fields) & set(after_fields) + if before_fields[field_id] != after_fields[field_id] + ), + } + + +def _write_audit( + *, schema_id: int, version_id: int | None, event_type: str, actor_id: int | None, + request_id: str | None, before: dict[str, Any] | None, after: dict[str, Any] | None, +) -> None: + """追加配置审计事件;调用方与业务变更共用同一数据库事务。""" + db.session.add(ShippingOrderSchemaAuditEvent( + schema_id=schema_id, + version_id=version_id, + event_type=event_type, + actor_id=actor_id, + before_snapshot_json=_copy_json(before) if before is not None else None, + after_snapshot_json=_copy_json(after) if after is not None else None, + change_summary_json=_audit_summary(before, after), + request_id=request_id, + )) + + +def _version_payload( + version: ShippingOrderSchemaVersion, *, include_definition: bool = True, + actors: dict[int, User] | None = None, +) -> dict[str, Any]: + """序列化 Schema 版本;列表可省略完整快照,详情始终读取不可分叉的 definition_json。""" + definition = _definition(version) + + def actor_payload(user_id: int | None) -> dict[str, Any] | None: + """返回版本操作者的安全展示信息,避免历史页面暴露用户敏感字段。""" + user = actors.get(user_id) if actors and user_id else (db.session.get(User, user_id) if user_id else None) + if user is None: + return None + return {'id': user.id, 'display_name': user.real_name or user.username} + + payload = { + 'id': version.id, + 'version': version.version, + 'status': version.status, + 'checksum': version.checksum, + 'lock_version': version.lock_version, + 'change_note': version.change_note, + 'source_version_id': version.source_version_id, + 'published_at': _iso(version.published_at), + 'retired_at': _iso(version.retired_at), + 'created_at': _iso(version.created_at), + 'updated_at': _iso(version.updated_at), + 'created_by': actor_payload(version.created_by_id), + 'published_by': actor_payload(version.published_by_id), + 'field_count': sum(1 for item in definition.get('fields') or [] if item.get('enabled', True)), + } + if include_definition: + payload['definition'] = definition + return payload + + +def get_state() -> dict[str, Any]: + """返回编辑工作区所需当前草稿/发布版本,历史版本由分页接口按需读取。""" + schema = _schema() + if schema is None: + return {'schema': None, 'fields': [], 'versions': [], 'catalog': catalog()} + return { + 'schema': { + 'id': schema.id, + 'schema_code': schema.schema_code, + 'display_name': schema.display_name, + 'description': schema.description, + 'status': schema.status, + }, + # Retired fields remain available to historical records, not the current configuration workspace. + 'fields': [_field_payload(item) for item in ShippingOrderField.query.filter_by( + schema_id=schema.id, status='active', + ).order_by(ShippingOrderField.field_code).all()], + 'versions': [ + _version_payload(item) + for item in reversed(schema.versions) + if item.status in {'draft', 'published'} + ], + 'catalog': catalog(), + } + + +def list_versions( + *, page: int = 1, page_size: int = 20, version_number: int | None = None, +) -> dict[str, Any]: + """分页返回 Schema 版本概要;可按业务版本号精确定位历史链接。""" + schema = _require_schema() + safe_page = max(page, 1) + safe_page_size = min(max(page_size, 1), 100) + query = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id) + if version_number is not None: + query = query.filter(ShippingOrderSchemaVersion.version == version_number) + total = query.count() + rows = query.order_by(ShippingOrderSchemaVersion.version.desc()).offset( + (safe_page - 1) * safe_page_size + ).limit(safe_page_size).all() + actor_ids = { + actor_id for row in rows for actor_id in (row.created_by_id, row.published_by_id) if actor_id is not None + } + actors = {user.id: user for user in User.query.filter(User.id.in_(actor_ids)).all()} if actor_ids else {} + return { + 'items': [_version_payload(item, include_definition=False, actors=actors) for item in rows], + 'page': safe_page, + 'page_size': safe_page_size, + 'total': total, + } + + +def get_version_detail(version_id: int) -> dict[str, Any]: + """返回指定版本的完整不可变快照;不存在或跨 Schema 时拒绝访问。""" + schema = _require_schema() + version = db.session.get(ShippingOrderSchemaVersion, version_id) + if version is None or version.schema_id != schema.id: + raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND') + return _version_payload(version) + + +def _require_version(version_id: int, *, schema: ShippingOrderSchema | None = None) -> ShippingOrderSchemaVersion: + """读取属于唯一订单 Schema 的版本,防止 ID 被用于访问其他未来 Schema。""" + owner = schema or _require_schema() + version = db.session.get(ShippingOrderSchemaVersion, version_id) + if version is None or version.schema_id != owner.id: + raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND') + return version + + +def get_version_diff(version_id: int, *, against_version_id: int) -> dict[str, Any]: + """比较任意两个订单 Schema 版本;字段重命名依靠 field_id 保持为一次修改。""" + schema = _require_schema() + version = _require_version(version_id, schema=schema) + against = _require_version(against_version_id, schema=schema) + return { + 'base_version': _version_payload(version), + 'compare_version': _version_payload(against), + **compare_definitions(_definition(version), _definition(against)), + } + + +def _audit_event_payload( + event: ShippingOrderSchemaAuditEvent, *, actors: dict[int, User], versions: dict[int, ShippingOrderSchemaVersion], +) -> dict[str, Any]: + """序列化审计时间线的最小安全字段,不暴露完整配置快照或用户敏感信息。""" + actor = actors.get(event.actor_id) if event.actor_id else None + version = versions.get(event.version_id) if event.version_id else None + return { + 'id': event.id, + 'event_type': event.event_type, + 'version': {'id': version.id, 'version': version.version} if version else None, + 'actor': {'id': actor.id, 'display_name': actor.real_name or actor.username} if actor else None, + 'change_summary': _copy_json(event.change_summary_json or {}), + 'request_id': event.request_id, + 'created_at': _iso(event.created_at), + } + + +def list_audit_events(*, page: int = 1, page_size: int = 20, version_id: int | None = None) -> dict[str, Any]: + """分页读取只追加的 Schema 审计时间线,可按版本过滤且批量加载操作者。""" + schema = _require_schema() + safe_page = max(page, 1) + safe_page_size = min(max(page_size, 1), 100) + query = ShippingOrderSchemaAuditEvent.query.filter_by(schema_id=schema.id) + if version_id is not None: + _require_version(version_id, schema=schema) + query = query.filter(ShippingOrderSchemaAuditEvent.version_id == version_id) + total = query.count() + rows = query.order_by( + ShippingOrderSchemaAuditEvent.created_at.desc(), ShippingOrderSchemaAuditEvent.id.desc(), + ).offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all() + actor_ids = {item.actor_id for item in rows if item.actor_id is not None} + version_ids = {item.version_id for item in rows if item.version_id is not None} + actors = {item.id: item for item in User.query.filter(User.id.in_(actor_ids)).all()} if actor_ids else {} + versions = { + item.id: item for item in ShippingOrderSchemaVersion.query.filter( + ShippingOrderSchemaVersion.id.in_(version_ids) + ).all() + } if version_ids else {} + return { + 'items': [_audit_event_payload(item, actors=actors, versions=versions) for item in rows], + 'page': safe_page, + 'page_size': safe_page_size, + 'total': total, + } + + +def _extraction_summary(extraction: ShippingOrderExtraction) -> dict[str, Any]: + """序列化版本使用记录概要,不返回原始 LLM 和证据正文以控制历史列表体积。""" + return { + 'id': extraction.id, + 'task_id': extraction.task_id, + 'intake_id': extraction.intake_id, + 'status': extraction.status, + 'input_snapshot_hash': extraction.input_snapshot_hash, + 'created_at': _iso(extraction.created_at), + 'updated_at': _iso(extraction.updated_at), + } + + +def get_version_usage(version_id: int, *, page: int = 1, page_size: int = 20) -> dict[str, Any]: + """统计并分页读取实际使用指定 Schema 版本的解析记录,供发布影响评估和审计追溯。""" + schema = _require_schema() + version = _require_version(version_id, schema=schema) + safe_page = max(page, 1) + safe_page_size = min(max(page_size, 1), 100) + query = ShippingOrderExtraction.query.filter_by(schema_version_id=version.id) + total = query.count() + status_counts = { + status: count for status, count in db.session.query( + ShippingOrderExtraction.status, func.count(ShippingOrderExtraction.id), + ).filter_by(schema_version_id=version.id).group_by(ShippingOrderExtraction.status).all() + } + first_used_at, last_used_at = db.session.query( + func.min(ShippingOrderExtraction.created_at), func.max(ShippingOrderExtraction.created_at), + ).filter_by(schema_version_id=version.id).one() + rows = query.order_by( + ShippingOrderExtraction.created_at.desc(), ShippingOrderExtraction.id.desc(), + ).offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all() + return { + 'version': _version_payload(version, include_definition=False), + 'summary': { + 'total': total, + 'status_counts': status_counts, + 'first_used_at': _iso(first_used_at), + 'last_used_at': _iso(last_used_at), + }, + 'items': [_extraction_summary(row) for row in rows], + 'page': safe_page, + 'page_size': safe_page_size, + 'total': total, + } + + +def _field_identity_map(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]: + """从提取时锁定的 Schema 快照读取字段身份,避免后续目录重命名污染运行审计。""" + return { + str(item['field_id']): item for item in _definition(version).get('fields') or [] + if isinstance(item, dict) and item.get('field_id') + } + + +def _extraction_value(value: ShippingOrderFieldValue) -> Any: + """返回运行时已保存的统一 JSON 值,避免读取已失效的类型字段组合。""" + return _copy_json(value.value_json) + + +def get_extraction_audit(extraction_id: int) -> dict[str, Any]: + """返回单次订单解析的完整只读审计链:冻结输入、LLM 候选、裁决和证据。""" + extraction = db.session.get(ShippingOrderExtraction, extraction_id) + if extraction is None: + raise NotFoundError('Shipping order extraction not found', code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND') + schema = _require_schema() + version = _require_version(extraction.schema_version_id, schema=schema) + identities = _field_identity_map(version) + lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all() + observations = ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).order_by( + ShippingOrderFieldObservation.id, + ).all() + decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).order_by( + ShippingOrderFieldDecision.id, + ).all() + values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).order_by( + ShippingOrderFieldValue.id, + ).all() + + def identity(field_id: str) -> dict[str, Any]: + field = identities.get(field_id, {}) + return { + 'field_id': field_id, + 'field_code': field.get('field_code'), + 'display_name': field.get('display_name'), + 'scope': field.get('scope'), + 'value_type': field.get('value_type'), + } + + return { + 'extraction': _extraction_summary(extraction), + 'schema_version': _version_payload(version), + 'input_snapshot': ( + _copy_json(extraction.input_snapshot_json) | {'snapshot_available': True} + if extraction.input_snapshot_json else { + 'snapshot_hash': extraction.input_snapshot_hash, + 'documents': [], + 'snapshot_available': False, + } + ), + 'raw_llm_output': _copy_json(extraction.raw_llm_output_json), + 'normalized_result': _copy_json(extraction.normalized_result_json), + 'validation_result': _copy_json(extraction.validation_result_json), + 'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines], + 'observations': [ + identity(row.field_id) | { + 'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id, + 'source_type': row.source_type, 'extractor': row.extractor, + 'raw_value': _copy_json(row.raw_value_json), 'normalized_value': _copy_json(row.normalized_value_json), + 'evidence_quote': row.evidence_quote, 'confidence': str(row.confidence) if row.confidence is not None else None, + 'evidence_verified': bool(row.evidence_verified), 'created_at': _iso(row.created_at), + } + for row in observations + ], + 'decisions': [ + identity(row.field_id) | { + 'id': row.id, 'line_id': row.line_id, 'decision_status': row.decision_status, + 'selected_observation_id': row.selected_observation_id, + 'supporting_observation_ids': list(row.supporting_observation_ids_json or []), + 'resolved_value': _copy_json(row.resolved_value_json), 'reason_code': row.reason_code, + 'decided_at': _iso(row.decided_at), + } + for row in decisions + ], + 'field_values': [ + identity(row.field_id) | { + 'id': row.id, 'line_id': row.line_id, 'decision_id': row.decision_id, + 'value': _extraction_value(row), 'created_at': _iso(row.created_at), + } + for row in values + ], + } + + +def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """初始化全局唯一订单 Schema;重复初始化明确拒绝。""" + if ShippingOrderSchema.query.count(): + raise ConflictError('Only one shipping order schema is allowed', code='SHIPPING.ORDER_SCHEMA_EXISTS') + display_name = str(data.get('display_name') or '').strip() + if not display_name: + raise ValidationError('display_name is required', details={'field': 'display_name'}) + schema = ShippingOrderSchema( + schema_code=SCHEMA_CODE, + display_name=display_name, + description=str(data.get('description') or '').strip() or None, + created_by_id=actor_id, + updated_by_id=actor_id, + ) + db.session.add(schema) + db.session.commit() + return get_state() + + +def save_field( + data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None, + request_id: str | None = None, +) -> dict[str, Any]: + """创建或更新稳定字段;系统标识可重命名,首次发布后仍锁定 scope 和 type。""" + schema = _require_schema() + field = db.session.get(ShippingOrderField, field_id) if field_id else None + if field_id and (field is None or field.schema_id != schema.id): + raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND') + code = str(data.get('field_code') or '').strip().lower() + scope = str(data.get('scope') or '').strip().lower() + value_type = str(data.get('value_type') or '').strip().lower() + if not FIELD_CODE_RE.fullmatch(code): + raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID') + if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES: + raise ValidationError('scope or value_type is invalid', code='SHIPPING.ORDER_FIELD_INVALID') + if field and field.published_once and (field.scope, field.value_type) != (scope, value_type): + raise ConflictError('Published field scope and type are immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE') + previous_code = field.field_code if field else None + field = field or ShippingOrderField( + schema_id=schema.id, + field_code=code, + scope=scope, + value_type=value_type, + created_by_id=actor_id, + ) + field.field_code = code + field.scope = scope + field.value_type = value_type + if not field_id: + db.session.add(field) + try: + db.session.flush() + draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='draft').first() + before = _definition(draft) if draft else None + if draft and previous_code != code: + definition = _definition(draft) + for item in definition.get('fields') or []: + if str(item.get('field_id')) == field.id: + item['field_code'] = code + draft.definition_json = definition + draft.lock_version += 1 + _write_audit( + schema_id=schema.id, version_id=draft.id if draft else None, event_type='field_saved', + actor_id=actor_id, request_id=request_id, before=before, + after=_definition(draft) if draft else None, + ) + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('field_code already exists', code='SHIPPING.ORDER_FIELD_CONFLICT') from exc + return _field_payload(field) + + +def retire_field( + field_id: str, *, actor_id: int | None = None, request_id: str | None = None, +) -> dict[str, Any]: + """退役无运行配置引用的稳定字段;历史 Extraction/Schema 版本可继续审计。""" + field = db.session.get(ShippingOrderField, field_id) + if field is None or field.schema_id != _require_schema().id: + raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND') + draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=field.schema_id, status='draft').first() + if draft and any(str(item.get('field_id')) == field.id for item in _definition(draft).get('fields') or []): + raise ConflictError('Field is referenced by a draft schema version', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED') + if _field_runtime_references(field.id): + raise ConflictError('Field is referenced by downstream runtime configuration', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED') + field.status = 'retired' + _write_audit( + schema_id=field.schema_id, version_id=None, event_type='field_retired', actor_id=actor_id, + request_id=request_id, before={'field': _field_payload(field) | {'status': 'active'}}, + after={'field': _field_payload(field)}, + ) + db.session.commit() + return _field_payload(field) + + +def delete_field( + field_id: str, *, actor_id: int | None = None, request_id: str | None = None, +) -> dict[str, Any]: + """ + 删除当前配置不再需要的字段。 + + 未发布且没有业务/下游引用时物理删除;已进入历史 Schema 或解析记录时仅归档。 + 草稿中的字段配置和字段目录在同一事务内变更,避免删除失败却提前改坏草稿。 + """ + field = db.session.get(ShippingOrderField, field_id) + if field is None or field.schema_id != _require_schema().id: + raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND') + if _field_runtime_references(field.id): + raise ConflictError('Field is referenced by downstream runtime configuration', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED') + + historical_schema_reference = any( + any(str(item.get('field_id')) == field.id for item in _definition(version).get('fields') or []) + for version in ShippingOrderSchemaVersion.query.filter( + ShippingOrderSchemaVersion.schema_id == field.schema_id, + ShippingOrderSchemaVersion.status.in_(['published', 'retired']), + ).all() + ) + extraction_reference = any(( + db.session.query(ShippingOrderFieldObservation.id).filter_by(field_id=field.id).first(), + db.session.query(ShippingOrderFieldDecision.id).filter_by(field_id=field.id).first(), + db.session.query(ShippingOrderFieldValue.id).filter_by(field_id=field.id).first(), + )) + + draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=field.schema_id, status='draft').first() + before = _definition(draft) if draft else None + if draft: + definition = _definition(draft) + definition['fields'] = [ + item for item in definition.get('fields') or [] if str(item.get('field_id')) != field.id + ] + draft.definition_json = definition + draft.lock_version += 1 + + if field.published_once or historical_schema_reference or extraction_reference: + field.status = 'retired' + action = 'archived' + else: + db.session.delete(field) + action = 'deleted' + _write_audit( + schema_id=field.schema_id, version_id=draft.id if draft else None, event_type='field_deleted', + actor_id=actor_id, request_id=request_id, before=before, + after=_definition(draft) if draft else None, + ) + db.session.commit() + return {'field_id': field_id, 'action': action} + + +def _field_runtime_references(field_id: str) -> list[str]: + """返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。""" + from app.models import ( + ShippingExcelTemplate, ShippingInventoryParsingProfile, + ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, + ) + references: list[str] = [] + if db.session.query(ShippingInventoryRoutingRuleCondition).join(ShippingInventoryRoutingRule).filter( + ShippingInventoryRoutingRuleCondition.order_field_id == field_id, + ShippingInventoryRoutingRule.status.in_(['draft', 'published']), + ).count(): + references.append('inventory_routing_rule') + parsing_reference = any( + any(str(item.get('order_field_id') or '') == field_id for item in (profile.definition_json or {}).get('match_keys', [])) + for profile in ShippingInventoryParsingProfile.query.filter( + ShippingInventoryParsingProfile.status.in_(['draft', 'published']) + ).all() + ) + if parsing_reference: + references.append('inventory_parsing_profile') + template_reference = any( + any( + item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id + for item in (template.definition_json or {}).get('mappings', []) + ) + for template in ShippingExcelTemplate.query.filter( + ShippingExcelTemplate.status.in_(['draft', 'published']) + ).all() + ) + if template_reference: + references.append('excel_template') + return references + + +def create_draft( + data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None, +) -> dict[str, Any]: + """创建下一版本草稿;从指定版本复制完整定义并记录来源和审计事件。""" + schema = _require_schema() + source_id = data.get('copy_from_version_id') + if source_id is not None and (not str(source_id).isdigit() or int(source_id) < 1): + raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + source = db.session.get(ShippingOrderSchemaVersion, int(source_id)) if source_id is not None else None + if source_id is not None and source is None: + raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if source is not None and source.schema_id != schema.id: + raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if source is not None and source.status not in {'published', 'retired'}: + raise ValidationError('copy_from_version_id must be immutable', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='draft').count(): + raise ConflictError('A draft schema version already exists', code='SHIPPING.ORDER_SCHEMA_DRAFT_EXISTS') + next_version = int(db.session.query(func.max(ShippingOrderSchemaVersion.version)).filter_by(schema_id=schema.id).scalar() or 0) + 1 + definition = _definition(source) if source else { + 'schema_code': schema.schema_code, 'version': next_version, 'fields': [], + } + definition['version'] = next_version + version = ShippingOrderSchemaVersion( + schema_id=schema.id, + version=next_version, + status='draft', + definition_json=definition, + source_version_id=source.id if source else None, + change_note=str(data.get('change_note') or '').strip() or None, + created_by_id=actor_id, + ) + db.session.add(version) + db.session.flush() + _write_audit( + schema_id=schema.id, version_id=version.id, + event_type='cloned' if source else 'draft_created', actor_id=actor_id, + request_id=request_id, before=_definition(source) if source else None, after=definition, + ) + db.session.commit() + return _version_payload(version) + + +def _string_list(value: Any, *, field: str) -> list[str]: + """规范化去重字符串列表,非法结构抛出字段级校验错误。""" + if not isinstance(value, list) or any(not isinstance(item, str) for item in value): + raise ValidationError(f'{field} must be a string list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + result: list[str] = [] + for item in value: + normalized = item.strip() + if normalized and normalized not in result: + result.append(normalized) + return result + + +def _evidence_policy(value: Any) -> dict[str, Any]: + """校验证据策略,仅允许受控来源、冲突策略和布尔开关。""" + if not isinstance(value, dict) or set(value) - EVIDENCE_KEYS: + raise ValidationError('evidence_policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + sources = _string_list(value.get('source_precedence', []), field='source_precedence') + if set(sources) - SOURCE_TYPES: + raise ValidationError('source_precedence contains unsupported source', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + conflict_policy = str(value.get('conflict_policy') or 'block').strip() + if conflict_policy not in CONFLICT_POLICIES: + raise ValidationError('conflict_policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + required = value.get('required', True) + allow_single = value.get('allow_single_source', True) + if not isinstance(required, bool) or not isinstance(allow_single, bool): + raise ValidationError('evidence policy flags must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + return { + 'required': required, + 'source_precedence': sources, + 'conflict_policy': conflict_policy, + 'allow_single_source': allow_single, + } + + +def save_draft( + version_id: int, data: dict[str, Any], *, actor_id: int | None = None, + request_id: str | None = None, +) -> dict[str, Any]: + """校验并整体替换草稿定义;expected_lock_version 不匹配时拒绝覆盖。""" + version = db.session.get(ShippingOrderSchemaVersion, version_id) + if version is None or version.schema_id != _require_schema().id: + raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND') + if version.status != 'draft': + raise ConflictError('Published schema version is immutable', code='SHIPPING.ORDER_SCHEMA_VERSION_IMMUTABLE') + expected_lock_version = data.get('expected_lock_version') + if not isinstance(expected_lock_version, int): + raise ValidationError( + 'expected_lock_version is required', code='SHIPPING.ORDER_SCHEMA_LOCK_VERSION_REQUIRED', + details={'field': 'expected_lock_version'}, + ) + if expected_lock_version != version.lock_version: + raise ConflictError( + 'Schema draft was changed by another user', code='SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT', + details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version}, + ) + configs = data.get('fields') + if not isinstance(configs, list): + raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + before = _definition(version) + active_fields = { + item.id: item for item in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all() + } + seen: set[str] = set() + normalized_fields: list[dict[str, Any]] = [] + for sequence, raw in enumerate(configs, start=1): + if not isinstance(raw, dict) or str(raw.get('field_id') or '') not in active_fields: + raise ValidationError('field_id is invalid or retired', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + field_id = str(raw['field_id']) + if field_id in seen: + raise ValidationError('field_id must be unique in a version', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + seen.add(field_id) + field = active_fields[field_id] + enabled = raw.get('enabled', True) + display_name = str(raw.get('display_name') or '').strip() + normalizer = str(raw.get('normalizer_key') or 'trim').strip() + comparator = str(raw.get('comparator_key') or 'normalized_text').strip() + validators = _string_list(raw.get('validator_keys', []), field='validator_keys') + aliases = _string_list(raw.get('aliases', []), field='aliases') + enum_options = _string_list(raw.get('enum_options', []), field='enum_options') + relation_role = str(raw.get('relation_role') or '').strip() or None + required = raw.get('required', False) + if not isinstance(enabled, bool) or not isinstance(required, bool): + raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS: + raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if set(validators) - VALIDATORS or relation_role not in RELATION_ROLES: + raise ValidationError('field validator or relation role is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if normalizer not in TYPE_NORMALIZERS[field.value_type]: + raise ValidationError('normalizer is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if comparator not in TYPE_COMPARATORS[field.value_type]: + raise ValidationError('comparator is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if set(validators) - TYPE_VALIDATORS[field.value_type]: + raise ValidationError('validator is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if field.value_type == 'enum' and not enum_options: + raise ValidationError('enum field requires enum_options', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + if field.value_type != 'enum' and enum_options: + raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + normalized_fields.append({ + 'field_id': field_id, + 'field_code': field.field_code, + 'scope': field.scope, + 'value_type': field.value_type, + 'enabled': enabled, + 'display_name': display_name, + 'description': str(raw.get('description') or '').strip() or None, + 'required': required, + 'aliases': aliases, + 'normalizer_key': normalizer, + 'validator_keys': validators, + 'enum_options': enum_options, + 'evidence_policy': _evidence_policy(raw.get('evidence_policy', {})), + 'relation_role': relation_role, + 'comparator_key': comparator, + 'extraction_instruction': str(raw.get('extraction_instruction') or '').strip() or None, + 'sequence': sequence, + }) + after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields} + version.definition_json = after + version.lock_version += 1 + version.change_note = str(data.get('change_note') or version.change_note or '').strip() or None + _write_audit( + schema_id=version.schema_id, version_id=version.id, event_type='draft_saved', actor_id=actor_id, + request_id=request_id, before=before, after=after, + ) + db.session.commit() + return _version_payload(version) + + +def publish( + version_id: int, *, actor_id: int | None, expected_lock_version: int | None = None, + request_id: str | None = None, +) -> dict[str, Any]: + """发布指定锁版本的草稿,生成不可变 checksum 并退役上一发布版本。""" + version = db.session.get(ShippingOrderSchemaVersion, version_id) + if version is None or version.schema_id != _require_schema().id: + raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND') + if version.status != 'draft': + raise ConflictError('Only draft schema version can be published', code='SHIPPING.ORDER_SCHEMA_PUBLISH_INVALID') + if not isinstance(expected_lock_version, int): + raise ValidationError( + 'expected_lock_version is required', code='SHIPPING.ORDER_SCHEMA_LOCK_VERSION_REQUIRED', + details={'field': 'expected_lock_version'}, + ) + if expected_lock_version != version.lock_version: + raise ConflictError( + 'Schema draft was changed by another user', code='SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT', + details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version}, + ) + definition = _definition(version) + enabled_configs = _enabled_fields(definition) + if not enabled_configs: + raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') + included_field_ids = {str(config.get('field_id')) for config in enabled_configs} + referenced_omissions: dict[str, list[str]] = {} + for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all(): + if field.id in included_field_ids: + continue + references = _field_runtime_references(field.id) + if references: + referenced_omissions[field.id] = references + if referenced_omissions: + raise ConflictError( + 'Schema version omits fields referenced by downstream runtime configuration', + code='SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED', + details={'fields': referenced_omissions}, + ) + encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8') + now = datetime.utcnow() + previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first() + if previous is not None: + previous.status = 'retired' + previous.retired_at = now + db.session.flush() + for config in enabled_configs: + field = db.session.get(ShippingOrderField, str(config.get('field_id'))) + if field is not None: + field.published_once = True + version.checksum = hashlib.sha256(encoded).hexdigest() + version.status = 'published' + version.published_by_id = actor_id + version.published_at = now + _write_audit( + schema_id=version.schema_id, version_id=version.id, event_type='published', actor_id=actor_id, + request_id=request_id, before=definition, after=definition, + ) + db.session.commit() + return _version_payload(version) + + +def delete_draft( + version_id: int, *, actor_id: int | None = None, request_id: str | None = None, +) -> None: + """删除错误草稿并保留删除前快照审计;发布和退役版本不可删除。""" + version = db.session.get(ShippingOrderSchemaVersion, version_id) + if version is None or version.schema_id != _require_schema().id: + raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND') + if version.status != 'draft': + raise ConflictError('Only draft schema version can be deleted', code='SHIPPING.ORDER_SCHEMA_VERSION_DELETE_BLOCKED') + _write_audit( + schema_id=version.schema_id, version_id=None, event_type='draft_deleted', actor_id=actor_id, + request_id=request_id, before=_definition(version), after=None, + ) + db.session.delete(version) + db.session.commit() + + +def get_published_contract() -> dict[str, Any]: + """返回当前发布订单字段契约,供阶段 2 的 Dify 输入编译器使用。""" + schema = _require_schema() + version = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='published').first() + if version is None: + raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED') + return { + 'schema_version_id': version.id, + 'schema_code': schema.schema_code, + 'version': version.version, + 'checksum': version.checksum, + 'fields': _enabled_fields(_definition(version)), + } diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index 802ed489..02078c23 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -1,8 +1,8 @@ """ services/shipping_notice/progress_workflow.py -用途:承接发货通知任务的自动推进流程,包括解析确认检查、库存准备、字段映射确认与履约侧串联。 -依赖:customer_identity_gate、tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。 +用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。 +依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、tool_response。 逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。 """ @@ -16,7 +16,6 @@ from app.services.shipping_notice import fulfillment_workflow from app import db from app.services.shipping_notice.constants import ( CP_INVENTORY_SOURCE_REVIEW, - CP_UPLOAD_REQ, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, PH_RSV_REQ, @@ -27,25 +26,20 @@ from app.services.shipping_notice.inventory_source_gate import ( is_inventory_source_stable, ensure_inventory_source_review_state, ) -from app.services.shipping_notice.inventory_mapping_workflow import ( - awaiting_inventory_mapping_confirm, - inventory_mapping_checkpoint_response, - maybe_auto_confirm_inventory_mapping, -) from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool -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.state_machine import resolve_task_ui_state +from app.services.shipping_notice.tool_common import auto_progress_enabled 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]: """ - 按任务当前状态自动串联解析确认、库存准备、字段映射与履约动作。 + 按任务当前状态自动串联解析确认、正式库存准备与履约动作。 【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。 - 核心逻辑:先检查解析是否需要人工确认,再保证库存已就绪、字段映射已确认,最后委托 fulfillment workflow 继续推进。 + 核心逻辑:先检查解析是否需要人工确认,再保证正式库存已按 published Profile 就绪,最后委托 fulfillment workflow 继续推进。 Args: payload: 必须能定位任务;可额外携带 lang/locale/language 以及 auto-chain 控制参数。 @@ -135,30 +129,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 2] 保证库存已经就绪。 - # 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。 + # 正常任务仅复用排程或手动刷新已导出的文件;这里不得隐式触发 RPA。 if not task.inventory_lines_json: - if not auto_rpa_inventory_enabled(): - apply_task_transition(task, TaskTransition.INV_UNAVAIL) - set_task_step_progress( - task, - step_key="step3_inventory_prepare", - step_title="获取库存", - status="needs_human", - message="未开启自动 RPA 获取库存", - progress_percent=100, - current=0, - total=1, - detail="请手动上传货代库存 Excel,或开启自动 RPA 后重试。", - ) - db.session.commit() - return tool_response( - status="needs_human", - task=task, - message="未开启自动 RPA 获取库存。请手动上传货代库存 Excel。", - data=serialize_task_for_tool(task), - checkpoint=CP_UPLOAD_REQ, - stop_agent_turn=True, - ) lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"} if lang: @@ -168,24 +140,11 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: steps.append("触发 RPA 库存导出") return inv if inv.get("status") != "ok": - if maybe_auto_confirm_inventory_mapping(task): - steps.append("自动确认字段对齐") - else: - return inv + return inv else: steps.append("载入库存") - # [STEP 3] 尝试自动完成字段映射确认。 - # 当系统已经拿到足够可靠的列映射时,直接确认可减少一次人工往返。 - if maybe_auto_confirm_inventory_mapping(task): - steps.append("自动确认字段对齐") - - # [STEP 4] 如果映射仍需人工确认,则停在检查点,把确认动作交还给用户或 Agent。 - if awaiting_inventory_mapping_confirm(task): - lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() - return inventory_mapping_checkpoint_response(task, lang=lang or None) - - # [STEP 5] 库存与映射都就绪后,再进入履约侧自动推进。 + # [STEP 3] 库存就绪后进入履约侧自动推进。 # 匹配、生成 Excel、上传货代等步骤统一交给 fulfillment workflow 处理,避免本文件继续膨胀。 fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps) if fulfillment_result is not None: diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 9e408695..97e05038 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -188,21 +188,29 @@ def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None: def resolve_task_export_download(task: ShippingTask | None) -> tuple[Path, str] | None: - """解析任务导出文件路径;文件不存在或路径无效时返回 None。""" + """解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。""" if not task or not task.export_file_path: return None - path = Path(task.export_file_path) + from app.models import ShippingExportArtifact + artifact = ShippingExportArtifact.query.filter_by( + task_id=task.id, status='ready', file_path=task.export_file_path, + ).order_by( + ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(), + ).first() + if artifact is None: + return None + path = Path(artifact.file_path) if not path.is_file(): return None - return path, task.export_file_name or path.name + return path, artifact.file_name or path.name def task_export_error_message(task: ShippingTask | None) -> str: """导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。""" - if not task or not task.export_file_path: + if not task or task.id is None or not task.export_file_path: return "export file not found" - path = Path(task.export_file_path) - if not path.is_file(): + resolved = resolve_task_export_download(task) + if resolved is None: return "export file missing on disk" return "" @@ -536,7 +544,6 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, "warehouse_hint": task.warehouse_hint, "inventory_source_code": task.inventory_source_code, "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, "inventory_source_method": task.inventory_source_method, @@ -727,7 +734,7 @@ def list_tasks_for_user( process_status: str | None = None, limit: int = 100, ) -> list[dict[str, Any]]: - """列出用户可见任务摘要,可按 batch_no / process_status 过滤。""" + """列出用户可见任务摘要,可按批次或工作台用户态状态过滤。""" q = ShippingTask.query.filter( (ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None)) ) @@ -737,7 +744,13 @@ def list_tasks_for_user( return [] q = q.filter(ShippingTask.batch_id == batch.id) if process_status: - q = q.filter(ShippingTask.process_status == process_status) + if process_status == "shortage_review": + q = q.filter( + (ShippingTask.review_status == "shortage_review") + | (ShippingTask.pending_human_reason.in_(("shortage", "shortage_review"))) + ) + else: + q = q.filter(ShippingTask.process_status == process_status) rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all() return [serialize_task_summary(c) for c in rows] diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index 48d6b06a..da2ff5a0 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -36,7 +36,6 @@ _ACTION_EVENT_MAP: dict[str, _ActionEventMeta] = { "decision_rejected": _ActionEventMeta("reject", "用户已驳回 {task_no}", 40), "focus_switched": _ActionEventMeta("switch_focus", "用户已切换 focus 到 {task_no}", 35), "focus_auto_switched": _ActionEventMeta("auto_focus", "系统自动聚焦到 {task_no}", 10), - "inventory_mapping_confirmed": _ActionEventMeta("confirm_inventory_mapping", "用户已确认 {task_no} 库存映射", 30), "inventory_source_confirmed": _ActionEventMeta("confirm_inventory_source", "用户已确认 {task_no} 库存源", 30), } diff --git a/backend/app/services/shipping_notice/routing_facts.py b/backend/app/services/shipping_notice/routing_facts.py new file mode 100644 index 00000000..f3e9c899 --- /dev/null +++ b/backend/app/services/shipping_notice/routing_facts.py @@ -0,0 +1,64 @@ +""" +services/shipping_notice/routing_facts.py + +用途:构造库存源路由规则可读取的受控业务事实。 +依赖:无 ORM 写入依赖;调用方传入已完成解析和标准化的任务/订单行数据。 +逻辑:规则引擎只能通过本模块的白名单读取事实,避免管理端规则访问任意模型字段。 +""" + +from __future__ import annotations + +from typing import Any + + +ALLOWED_SYSTEM_FACT_KEYS = frozenset({ + 'task.customer_code', 'task.destination_country', 'task.destination_city', 'task.destination_port', + 'task.warehouse_hint', 'task.order_type', 'task.sender_email', 'task.sender_domain', + 'line.reservation_id', 'line.part_number', 'line.customer_part_number', 'line.aws_part_number', + 'line.inventory_source_hint', +}) + + +def build_routing_facts(*, task: Any, line: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]: + """ + 将任务和订单行投影为路由规则可读取的稳定事实。 + + Args: + task: ShippingTask 或提供同名属性的对象。 + line: 单条规范订单行;任务级规则传 None。 + + Returns: + dict: 使用 task/line 两层命名空间的只读事实字典。 + """ + line_data = dict(line or {}) + sender_email = str(getattr(task, 'sender_email', '') or '').strip().lower() + sender_domain = sender_email.rsplit('@', 1)[-1] if '@' in sender_email else '' + return { + 'task': { + 'customer_code': str(getattr(task, 'customer_code', '') or '').strip().upper(), + 'destination_country': str(getattr(task, 'destination_country', '') or '').strip().upper(), + 'destination_city': str(getattr(task, 'destination_city', '') or '').strip().upper(), + 'destination_port': str(getattr(task, 'destination_code', '') or '').strip().upper(), + 'warehouse_hint': str(getattr(task, 'warehouse_hint', '') or '').strip().upper(), + 'order_type': str(getattr(task, 'order_type', '') or '').strip().upper(), + 'sender_email': sender_email, + 'sender_domain': sender_domain, + }, + 'line': { + key: str(line_data.get(key) or '').strip().upper() + for key in ('reservation_id', 'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint') + }, + } + + +def read_system_fact(facts: dict[str, dict[str, Any]], fact_path: str) -> Any: + """ + 读取白名单路由事实。 + + Raises: + KeyError: 规则引用未注册字段时抛出,调用方应拒绝发布或执行该规则。 + """ + if fact_path not in ALLOWED_SYSTEM_FACT_KEYS: + raise KeyError(f'Unsupported routing fact: {fact_path}') + namespace, field = fact_path.split('.', 1) + return facts.get(namespace, {}).get(field) diff --git a/backend/app/services/shipping_notice/routing_operators.py b/backend/app/services/shipping_notice/routing_operators.py new file mode 100644 index 00000000..374ca01d --- /dev/null +++ b/backend/app/services/shipping_notice/routing_operators.py @@ -0,0 +1,62 @@ +""" +services/shipping_notice/routing_operators.py + +用途:执行库存源路由规则允许的比较操作。 +依赖:无业务服务依赖;由 inventory_routing_engine 调用。 +逻辑:操作符白名单限制规则表达能力,避免管理员配置任意代码、SQL 或正则执行。 +""" + +from __future__ import annotations + +from typing import Any + + +ALLOWED_OPERATORS = frozenset({ + 'equals', 'not_equals', 'in', 'not_in', 'prefix', 'suffix', 'contains', + 'numeric_length', 'string_length', 'is_empty', 'is_not_empty', +}) + + +def matches_operator(actual: Any, operator: str, expected: Any = None) -> bool: + """ + 按受控操作符匹配一个标准化事实值。 + + Args: + actual: 路由事实值。 + operator: 白名单操作符。 + expected: 规则期望值;空值判断操作符不使用该参数。 + + Returns: + bool: 当前条件是否命中。 + + Raises: + ValueError: 操作符未注册或期望值格式不合法。 + """ + if operator not in ALLOWED_OPERATORS: + raise ValueError(f'Unsupported routing operator: {operator}') + value = str(actual or '').strip() + if operator == 'is_empty': + return not value + if operator == 'is_not_empty': + return bool(value) + if operator in {'in', 'not_in'}: + if not isinstance(expected, list): + raise ValueError(f'{operator} expects a list') + result = value in {str(item or '').strip().upper() for item in expected} + return not result if operator == 'not_in' else result + expected_text = str(expected or '').strip().upper() + if operator == 'equals': + return value.upper() == expected_text + if operator == 'not_equals': + return value.upper() != expected_text + if operator == 'prefix': + return value.upper().startswith(expected_text) + if operator == 'suffix': + return value.upper().endswith(expected_text) + if operator == 'contains': + return expected_text in value.upper() + if operator == 'numeric_length': + return value.isdigit() and len(value) == int(expected) + if operator == 'string_length': + return len(value) == int(expected) + raise ValueError(f'Unsupported routing operator: {operator}') diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index b6a7c482..e8ad59b2 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -9,7 +9,6 @@ services/shipping_notice/rpa.py from __future__ import annotations import json -import os import shutil from datetime import datetime from pathlib import Path @@ -35,7 +34,7 @@ def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | b mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower() if mode in {"browser", "mock"}: return _runtime_summary(mode) - raw = str(os.getenv("FREIGHT_RPA_MOCK", current_app.config.get("FREIGHT_RPA_MOCK", "false")) or "false").strip().lower() + raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") or "false").strip().lower() return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser") @@ -47,8 +46,8 @@ def _path(key: str) -> Path | None: def inventory_drop_dir() -> Path | None: - """RPA 库存 Excel 落盘目录(FREIGHT_INVENTORY_DROP_DIR)。""" - return _path("FREIGHT_INVENTORY_DROP_DIR") + """RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。""" + return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") def inventory_processed_dir() -> Path | None: @@ -61,17 +60,17 @@ def inventory_processed_dir() -> Path | None: def inventory_trigger_dir() -> Path | None: """RPA 库存导出触发 JSON 目录。""" - return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") + return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") def upload_queue_dir() -> Path | None: """货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" - return _path("FREIGHT_UPLOAD_QUEUE_DIR") + return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR") def upload_trigger_dir() -> Path | None: """RPA 货代上传触发 JSON 目录。""" - return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR") + return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR") def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None: @@ -129,15 +128,27 @@ def write_inventory_export_batch_trigger( for source in sources: if not isinstance(source, dict) or not source.get("source_code"): continue + # 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。 + from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source + configuration_test = str((payload or {}).get('trigger_type') or '') == 'configuration_test' + trigger_source = get_rpa_trigger_inventory_source( + str(source["source_code"]), enabled_only=not configuration_test, + ) or source + source = {**source, **trigger_source} + business_connector = str(source.get("connector_type") or "").strip().lower() + worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector) inventory_sources.append({ "source_code": source.get("source_code"), - "connector_type": source.get("connector_type"), - "site_id": source.get("site_id"), - "warehouse_id": source.get("warehouse_id"), - "entry_url": source.get("entry_url"), + "connector_type": business_connector, + "worker_connector_type": worker_connector, + "rpa_profile_code": source.get("rpa_profile_code"), + "warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"), + "login_url": source.get("login_url"), + "entry_url": source.get("login_url"), "navigation": source.get("navigation") or {}, "parameters": source.get("parameters") or [], "query": source.get("query") or {}, + "credential_envelope": source.get("credential_envelope") or {}, }) if not inventory_sources: return None @@ -176,6 +187,16 @@ def write_inventory_export_trigger_for_task( 核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。 """ + from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source + + source_code = str(rpa_source.get('source_code') or '').strip() + rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source + # Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。 + rpa_source = dict(rpa_source) + business_connector = str(rpa_source.get('connector_type') or '').strip().lower() + rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector)) + rpa_source.setdefault('entry_url', rpa_source.get('login_url')) + rpa_source.setdefault('credential_envelope', {}) body = dict(payload or {}) if inventory_rpa_batch_enabled(): run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}" diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index 366624a4..dfcd64e3 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -77,6 +77,8 @@ def _build_refs( run_purpose: str | None, intake_nos: list[str] | None = None, capability: str | None = None, + temporary_inventory_asset_no: str | None = None, + temporary_inventory_session_no: str | None = None, ) -> dict[str, str]: """ 构建新版 agent_runtime_context.refs。 @@ -111,6 +113,12 @@ def _build_refs( refs["intake_nos"] = json.dumps(normalized_intakes, ensure_ascii=False, separators=(",", ":")) if _clean_text(capability): refs["capability"] = _clean_text(capability) + asset_no = _clean_text(temporary_inventory_asset_no).upper() + if asset_no: + refs["temporary_inventory_asset_no"] = asset_no + session_no = _clean_text(temporary_inventory_session_no).upper() + if session_no: + refs["temporary_inventory_session_no"] = session_no return refs @@ -208,6 +216,8 @@ def build_shipping_runtime_context( run_purpose: str | None = None, intake_nos: list[str] | None = None, capability: str | None = None, + temporary_inventory_asset_no: str | None = None, + temporary_inventory_session_no: str | None = None, ) -> dict[str, Any]: """ 构建货代发货通知 Agent 的 agent_runtime_context。 @@ -226,6 +236,8 @@ def build_shipping_runtime_context( run_purpose: 本次 Dify run 的目的,如 parse_notice。 intake_nos: 尚未建 Task 时的 Intake 编号集合。 capability: 当前固定画布能力。 + temporary_inventory_asset_no: 本轮对话临时库存文件资产编号;仅供 Dify 调用受控 Tool。 + temporary_inventory_session_no: 已创建的临时库存会话编号。 Returns: agent_runtime_context 字典;session_id 为空时返回空 dict。 @@ -253,6 +265,8 @@ def build_shipping_runtime_context( run_purpose=run_purpose, intake_nos=intake_nos, capability=capability, + temporary_inventory_asset_no=temporary_inventory_asset_no, + temporary_inventory_session_no=temporary_inventory_session_no, ), domain=domain, reference_context=reference_context, diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index fc31a77c..9977f109 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -21,13 +21,11 @@ from typing import Any from app.models import ShippingTask from app.services.shipping_notice.task_line_store import read_task_order_lines from app.services.shipping_notice.constants import ( - CP_ALIGN_REVIEW, CP_EXPORT_READY, CP_EXPORT_GENERATED, CP_INVENTORY_PENDING, CP_INVENTORY_SOURCE_REVIEW, CP_CUSTOMER_REVIEW, - CP_MAP_INFER, CP_PARSE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_READY_EXPORT, @@ -39,11 +37,9 @@ from app.services.shipping_notice.constants import ( CP_UPLOAD_FAILED, CP_UPLOAD_REQ, CP_WAITING_UPLOAD, - PH_ALIGN_REVIEW, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF, - PH_MAP_INFER, PH_NOTICE_TEXT_EXTRACTION_FAILED, PH_RPA_EXHAUSTED, PH_RPA_PENDING, @@ -51,7 +47,6 @@ from app.services.shipping_notice.constants import ( PH_SHORTAGE, PH_UPLOAD_RPA_FAILED, PH_UPLOAD_RPA_PENDING, - RS_ALIGN_REVIEW, RS_CONFIRMED, RS_PARSE_REVIEW, RS_REJECTED, @@ -72,20 +67,12 @@ ACTION_SPECS: dict[str, dict[str, str]] = { "reject": {"label": "驳回", "message": "驳回", "variant": "danger"}, "reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"}, "replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"}, - "confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"}, - "correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"}, - "reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"}, "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": { - "label": "选择库存文件", - "message": "我要上传库存 Excel", - "variant": "secondary", - }, "retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"}, "download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"}, "generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"}, @@ -94,16 +81,6 @@ ACTION_SPECS: dict[str, dict[str, str]] = { "message": "已在货代系统手工上传完成", "variant": "primary", }, - "paste_inventory_json": { - "label": "粘贴库存", - "message": "我粘贴库存小表", - "variant": "secondary", - }, - "edit_inventory_mapping": { - "label": "修改映射", - "message": "修改库存列映射", - "variant": "primary", - }, "match_inventory": { "label": "匹配库存", "message": "匹配库存", @@ -115,28 +92,14 @@ ACTION_SPECS: dict[str, dict[str, str]] = { 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", - "reparse_inventory", - "retry_rpa", - "reject", - ), - CP_MAP_INFER: ( - "edit_inventory_mapping", - "upload_inventory_file", - "paste_inventory_json", - "retry_rpa", - ), - CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"), - CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"), + CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa"), + CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa"), CP_INVENTORY_SOURCE_REVIEW: ( "confirm_inventory_source", "retry_resolve_inventory_source", - "upload_inventory_file", ), CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"), - RS_SHORTAGE_REVIEW: ("reparse_inventory", "rematch", "reject"), + RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"), CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"), CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"), CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"), @@ -154,7 +117,7 @@ ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys()) # Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ] OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",) -OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("retry_rpa", "upload_inventory_file") +OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("upload_inventory_file", "retry_rpa") @dataclass(frozen=True) @@ -211,7 +174,7 @@ def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]: "variant": "primary", "source_code": source_code, }, - *build_action_buttons(["retry_resolve_inventory_source", "upload_inventory_file"]), + *build_action_buttons(["retry_resolve_inventory_source"]), ] return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW])) @@ -347,16 +310,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: ) # [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, - human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]), - ) - if reason == PH_MAP_INFER: - return TaskUiState( - checkpoint=CP_MAP_INFER, - human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]), - ) if reason == PH_INV_UNAVAIL: return TaskUiState( checkpoint=CP_UPLOAD_REQ, @@ -454,8 +407,6 @@ class TaskTransition(StrEnum): PARSED = "parsed" PARSE_NEEDS_REVIEW = "parse_needs_review" INVENTORY_READY = "inventory_ready" - INVENTORY_ALIGN_REVIEW = "inventory_align_review" - MAP_INFER = "map_infer" RPA_EXHAUSTED = "rpa_exhausted" RPA_PENDING = "rpa_pending" INV_UNAVAIL = "inv_unavail" @@ -467,11 +418,6 @@ class TaskTransition(StrEnum): CLOSED = "closed" CONFIRM_PARSE = "confirm_parse" CONFIRM_MATCHED = "confirm_matched" - ALIGN_REVIEW_HOLD = "align_review_hold" - MAPPING_CONFIRMED = "mapping_confirmed" - CORRECT_MAPPING = "correct_mapping" - REPARSE_INVENTORY = "reparse_inventory" - REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote" NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed" REMATCH_REQUESTED = "rematch_requested" WAITING_UPLOAD = "waiting_upload" @@ -497,17 +443,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = { pending_human_reason=None, clear_error_message=True, ), - TaskTransition.INVENTORY_ALIGN_REVIEW: _TransitionSpec( - process_status="inventory_ready", - review_status=RS_ALIGN_REVIEW, - pending_human_reason=PH_ALIGN_REVIEW, - clear_error_message=True, - ), - TaskTransition.MAP_INFER: _TransitionSpec( - process_status="waiting_inventory", - review_status=None, - pending_human_reason=PH_MAP_INFER, - ), TaskTransition.RPA_EXHAUSTED: _TransitionSpec( process_status="waiting_inventory", review_status=None, @@ -563,28 +498,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = { review_status=RS_CONFIRMED, pending_human_reason=None, ), - TaskTransition.ALIGN_REVIEW_HOLD: _TransitionSpec( - review_status=RS_ALIGN_REVIEW, - pending_human_reason=PH_ALIGN_REVIEW, - ), - TaskTransition.MAPPING_CONFIRMED: _TransitionSpec( - review_status=None, - pending_human_reason=None, - ), - TaskTransition.CORRECT_MAPPING: _TransitionSpec( - process_status="waiting_inventory", - review_status=None, - pending_human_reason=PH_MAP_INFER, - ), - TaskTransition.REPARSE_INVENTORY: _TransitionSpec( - review_status=None, - pending_human_reason=None, - ), - TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec( - process_status="parsed", - review_status=None, - pending_human_reason=None, - ), TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec( process_status="pending_review", review_status=None, diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index 7be1a7af..b9b2afb9 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -44,6 +44,26 @@ def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int: return parsed +def cfg_float( + key: str, + default: float = 0.0, + *, + min_value: float | None = None, + max_value: float | None = None, +) -> float: + """读取 Flask config 浮点值,并在异常配置时回退到安全默认值。""" + val = current_app.config.get(key) + try: + parsed = float(default if val is None else val) + except (TypeError, ValueError): + parsed = default + if min_value is not None: + parsed = max(parsed, min_value) + if max_value is not None: + parsed = min(parsed, max_value) + return parsed + + def auto_progress_enabled() -> bool: """是否启用 auto_progress 自动推进(SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED)。""" return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False) diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 60ea2eaf..63a5211e 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -65,15 +65,40 @@ confirm_customer = customer_identity_gate.confirm_customer # 库存阶段 ensure_inventory = inventory_workflow.ensure_inventory -parse_inventory = inventory_workflow.parse_inventory -get_inventory_schema_preview = inventory_workflow.get_inventory_schema_preview -apply_inventory_mapping = inventory_workflow.apply_inventory_mapping upload_inventory_file = inventory_workflow.upload_inventory_file rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source + +def create_temporary_inventory_session(payload: dict): + """创建对话上传库存候选会话;仅供 Dify 临时库存固定分支调用。""" + from app.services.shipping_notice.inventory_temporary_session import create_temporary_inventory_session as _create + + return _create(payload) + + +def get_temporary_inventory_session(payload: dict): + """读取临时库存候选会话的脱敏结构预览;仅供 Dify 固定分支调用。""" + from app.services.shipping_notice.inventory_temporary_session import get_temporary_inventory_session as _get + + return _get(payload) + + +def submit_temporary_inventory_mapping_suggestion(payload: dict): + """保存 Dify 临时库存映射候选;后端校验后仍须由用户确认。""" + from app.services.shipping_notice.inventory_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit + + return _submit(payload) + + +def confirm_temporary_inventory_use(payload: dict): + """确认当前会话临时库存使用并执行后端确定性质量校验。""" + from app.services.shipping_notice.inventory_temporary_session import confirm_temporary_inventory_use as _confirm + + return _confirm(payload) + # 履约阶段 match_inventory = fulfillment_workflow.match_inventory generate_excel = fulfillment_workflow.generate_excel diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index c4a3a632..7fd57f14 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -13,12 +13,10 @@ from typing import Any from app.models import ShippingBatch, ShippingTask from app.services.shipping_notice.constants import ( - CP_ALIGN_REVIEW, CP_COMPLETED, CP_EXPORT_READY, CP_INVENTORY_PENDING, CP_INVENTORY_SOURCE_REVIEW, - CP_MAP_INFER, CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_PARSE_REVIEW, CP_READY_EXPORT, @@ -31,13 +29,11 @@ from app.services.shipping_notice.constants import ( CP_WAITING_UPLOAD, PH_INV_UNAVAIL, PH_INVENTORY_SOURCE_UNRESOLVED, - PH_MAP_INFER, PH_RPA_EXHAUSTED, PH_RPA_PENDING, PH_RSV_REQ, PH_SHORTAGE, PH_UPLOAD_RPA_PENDING, - RS_ALIGN_REVIEW, RS_PARSE_REVIEW, RS_SHORTAGE_REVIEW, ) @@ -59,7 +55,7 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( {"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"}, {"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"}, {"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"}, - {"id": "shipping-step-4", "code": "align_confirm", "label": "确认字段对齐"}, + {"id": "shipping-step-4", "code": "align_confirm", "label": "校验库存"}, {"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"}, {"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"}, {"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"}, @@ -86,7 +82,6 @@ _BLOCKED_CHECKPOINTS = { CP_PARSE_REVIEW, CP_RSV_REQ, CP_INVENTORY_SOURCE_REVIEW, - CP_ALIGN_REVIEW, RS_SHORTAGE_REVIEW, CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_UPLOAD_REQ, @@ -119,12 +114,9 @@ def _derive_current_step_index(task: ShippingTask) -> int: return 4 if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE: return 4 - if review_status == RS_ALIGN_REVIEW or pending_reason == CP_ALIGN_REVIEW: - return 3 if process_status == "inventory_ready" or match_status: return 4 if process_status == "waiting_inventory" or pending_reason in { - PH_MAP_INFER, PH_RPA_PENDING, PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, @@ -232,7 +224,6 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l 核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发; 以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。 - 新顺序为先解析复核再库存源;存量 pending_parse_review_after_source 仍提示延后复核。 """ checkpoint_value = str(checkpoint or "").strip() if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS: @@ -277,12 +268,6 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l if isinstance(item, dict): _append_unique_issue(issues, _parse_validation_issue_text(item)) - # 存量兼容:旧顺序「先库存源后解析」延后的低置信度提示。 - if payload.get("pending_parse_review_after_source") or ( - checkpoint_value == CP_INVENTORY_SOURCE_REVIEW and task.review_status == RS_PARSE_REVIEW - ): - _append_unique_issue(issues, "解析置信度不足,确认库存源后仍需复核解析结果。") - return issues @@ -295,8 +280,6 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。", CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。", CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。", - CP_MAP_INFER: "库存列映射需要确认或重新选择。", - CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。", RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。", CP_READY_MATCH: "库存已就绪,可以继续执行匹配。", CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。", diff --git a/backend/app/services/shipping_notice/user_facing_status.py b/backend/app/services/shipping_notice/user_facing_status.py index 5c8e587f..66038107 100644 --- a/backend/app/services/shipping_notice/user_facing_status.py +++ b/backend/app/services/shipping_notice/user_facing_status.py @@ -10,10 +10,8 @@ from __future__ import annotations from app.models import ShippingTask from app.services.shipping_notice.constants import ( - CP_ALIGN_REVIEW, CP_EXPORT_READY, CP_INVENTORY_PENDING, - CP_MAP_INFER, CP_PARSE_REVIEW, CP_READY_EXPORT, CP_READY_MATCH, @@ -46,8 +44,6 @@ TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset( _CHECKPOINT_LABELS: dict[str, str] = { CP_PARSE_REVIEW: "待确认发货通知解析", - CP_ALIGN_REVIEW: "待确认库存字段对齐", - CP_MAP_INFER: "待确认库存列映射", CP_UPLOAD_REQ: "待上传或获取库存", CP_INVENTORY_PENDING: "待上传库存", CP_RSV_REQ: "待补充 Reservation ID", diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml index 81af62d1..72969833 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/shipping_inventory_sources.yaml @@ -1,6 +1,7 @@ # backend/config/shipping_inventory_sources.yaml -# 货代库存 RPA 源配置(新增 Warehouse 只改本文件,改后需重启后端)。 -# 环境变量 SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG 可覆盖路径。 +# 历史库存源配置:仅用于期初数据导入和人工核对,不能恢复为运行时真相源。 +# 新增或修改库存源、报表路径、查询参数和别名必须维护在数据库后台。 +# 本文件保留 site_id、selector 等旧字段,导入时需显式映射或丢弃;新运行时不得读取。 version: 2 sources: @@ -18,7 +19,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSATL01 @@ -40,7 +41,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSAVP01 @@ -61,7 +62,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSAZA01 @@ -82,7 +83,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSCMH01 @@ -104,7 +105,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSCMN01 @@ -126,7 +127,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSEZE01 @@ -148,7 +149,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSFRA01 @@ -169,7 +170,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSGRU01 @@ -190,7 +191,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSIAD01 @@ -211,7 +212,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSJAN01 @@ -232,7 +233,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSLTN01 @@ -253,7 +254,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSMEL01 @@ -274,7 +275,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSNRT01 @@ -295,7 +296,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPHX01 @@ -316,7 +317,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPNE01 @@ -337,7 +338,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPRD01 @@ -358,7 +359,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPSC01 @@ -379,7 +380,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSQRO01 @@ -400,7 +401,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSRIC01 @@ -421,7 +422,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSRNO01 @@ -442,7 +443,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSRUH01 @@ -463,7 +464,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSSBN01 @@ -484,7 +485,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSSCL01 @@ -505,7 +506,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSYYZ01 @@ -526,7 +527,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSZAZ01 @@ -579,7 +580,7 @@ sources: report_name: On Hand Inventory by Location parameters: - name: Warehouse - selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: multi_select select_all: true selectors: @@ -645,4 +646,3 @@ sources: - TZR - TZR2 - TZR3 - diff --git a/backend/init_local_db.py b/backend/init_local_db.py index a1e5b4ae..618d99f1 100644 --- a/backend/init_local_db.py +++ b/backend/init_local_db.py @@ -1,46 +1,112 @@ +""" +backend/init_local_db.py + +用途:通过 Alembic 初始化当前版本的本地 SQLite,并写入最小管理账号和演示 Agent。 +依赖:Flask-Migrate、应用工厂、User/Agent 模型。 +逻辑:空库按当前模型建表并 stamp 到迁移 head,已有版本库执行 upgrade;随后写种子数据。未受 Alembic 管理的旧库明确阻断。 +""" + +from __future__ import annotations + import os +import sqlite3 import sys +from pathlib import Path -# Add backend directory to path -sys.path.append(os.path.dirname(os.path.abspath(__file__))) -# Force SQLite for local testing BEFORE importing app -db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'local_test.db') -os.environ['DATABASE_URL'] = f'sqlite:///{db_path}' -print(f"Setting DATABASE_URL to: {os.environ['DATABASE_URL']}") +BACKEND_DIR = Path(__file__).resolve().parent +sys.path.append(str(BACKEND_DIR)) -from app import create_app, db -from app.models import User, Agent -app = create_app('development') +def _database_path() -> Path: + """返回本地 SQLite 路径;验收或多工作区可通过环境变量使用隔离数据库。""" + configured = str(os.getenv('HXOPS_LOCAL_DATABASE_PATH') or '').strip() + return Path(configured).expanduser().resolve() if configured else BACKEND_DIR / 'local_test.db' -with app.app_context(): - print(f"Creating database tables at {db_path}...") - db.create_all() - print("Tables created successfully.") - - # Check if we need to seed data - user = User.query.filter_by(username='admin').first() - if user is None: - print("Seeding initial user 'admin'...") - user = User(username='admin', email='admin@example.com', role='admin') - user.set_password('Hxit@54321') - db.session.add(user) - else: - # Update password if user exists - print("Updating admin password to 'Hxit@54321'...") - user.set_password('Hxit@54321') - - if Agent.query.first() is None: - print("Seeding initial agent 'Demo Agent'...") - agent = Agent( - name='Demo Agent', - description='A test agent for local verification', - type='api', - dify_api_key='test-key', - is_active=True + +def _legacy_unversioned_database(path: Path) -> bool: + """识别已有业务表但缺少 Alembic 版本表的旧库,避免不安全地在未知基线上升级。""" + if not path.is_file() or path.stat().st_size == 0: + return False + with sqlite3.connect(path) as connection: + tables = { + str(row[0]) + for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'") + if str(row[0]) and not str(row[0]).startswith('sqlite_') + } + return bool(tables) and 'alembic_version' not in tables + + +def _is_blank_database(path: Path) -> bool: + """判断目标是否为可安全按当前模型初始化的全新空白 SQLite。""" + if not path.is_file() or path.stat().st_size == 0: + return True + with sqlite3.connect(path) as connection: + count = connection.execute( + "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'", + ).fetchone()[0] + return int(count or 0) == 0 + + +def main() -> int: + """迁移并初始化本地数据库;只对空库或已有 Alembic 版本库执行原地升级。""" + db_path = _database_path() + db_path.parent.mkdir(parents=True, exist_ok=True) + blank_database = _is_blank_database(db_path) + if _legacy_unversioned_database(db_path): + print( + f"Refusing to modify legacy unversioned database: {db_path}\n" + "Set HXOPS_LOCAL_DATABASE_PATH to a new file for a clean local environment, " + "or migrate the legacy database manually after backing it up.", + file=sys.stderr, ) - db.session.add(agent) - - db.session.commit() - print("Database seeded successfully.") + return 2 + + os.environ['DATABASE_URL'] = f"sqlite:///{db_path.as_posix()}" + os.environ.setdefault('FIXED_ASSETS_SYNC_ENABLED', 'false') + print(f"Setting DATABASE_URL to: {os.environ['DATABASE_URL']}") + + from flask_migrate import stamp, upgrade + + from app import create_app, db + from app.models import Agent, User + + app = create_app('development') + with app.app_context(): + migration_directory = str(BACKEND_DIR / 'migrations') + if blank_database: + print(f"Creating current local schema at {db_path}...") + db.create_all() + stamp(directory=migration_directory, revision='head') + print("Current schema created and stamped at migration head.") + else: + print(f"Applying database migrations at {db_path}...") + upgrade(directory=migration_directory) + print("Database migrations completed.") + + user = User.query.filter_by(username='admin').first() + if user is None: + print("Seeding initial user 'admin'...") + user = User(username='admin', email='admin@example.com', role='admin') + db.session.add(user) + else: + print("Updating local admin password...") + user.set_password('Hxit@54321') + + if Agent.query.first() is None: + print("Seeding initial agent 'Demo Agent'...") + db.session.add(Agent( + name='Demo Agent', + description='A test agent for local verification', + type='api', + dify_api_key='test-key', + is_active=True, + )) + + db.session.commit() + print("Database seeded successfully.") + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/backend/local_test.db b/backend/local_test.db index 75abebe36b00449174224b97598ca423031f764e..7785b1d560ba85309795f70d6a254b8162f26dd7 100644 GIT binary patch literal 1912832 zcmeF)4|p7Be%SY2P{a}-DM)um&*^lsMyI2Rv8WRP68v*KS+@d*6pr9RTr6~?<@0#3 zI{-%5-C54el7Q^9Go*BP{*y~$$88!rX_C6Oo78FT)UDk(ar3YBpEPY8JI&MQ$@BC{ z+b7ABwrQTkah@km+jnMXW@lz+7vT9I0qB=LL&UuQe(&e~Gw%xs(DLm?(>3HZ%Wmne ze7^8hp;#<@UX}}mq9y+S?-k-d#kTnC6Y-}aG4b~ye-(9n<}1okk@~_^S$r)1*3`e9 z`qxwcV(R~x`o~lMXzCwM{ZCVWcj`B%{?^p5PW|%KUz+;4sh^qpvr|7Y_2W~2WacP~#sm&>4N}IYnwLEoe>PAq_kk&>%zWL0!q+KZ%%yz@ra_%)nuQk2vTEXX9 z*D-8OUpLyW)-mjs={Tmx*hs zY;wYEh}vuF4Yev)mTGckWpVMWJUJ27C%;v$&c9KvPS2fFQW=bvZZ_l8nRA)shSAY& zw62SMnBiwoZ{Eq)Z6P_F%EIUOr~~s z!)O^=$2Qgs+i2H^XMAAPtyVB3!Y3k_nY|n|6DGFBAm^mohThctp@_=~IzKw2)oEJW zhM^@2g-M+at8HlQZfn)B<6?rwFV-;D^lsA)=U0EY0!qU%T+OvMjdonjABs$xW^8p# zdt1IHrc`a=mg*tXWMizwy7sckGzDQMJgrH-PH4BUxS3} zOI3B@M#Yb0I@?)AuBzA7s#=*>m*rrEIYG3Oit;Vv(yP*_73pYm!Nix8Q#)t95M=!p z^cq8 zb+k1*oS(VLPlszg-Zye{^(*l=lH4rvbli~Qoti31OCq$H(V?}RbNc!g_fH|o*w#w^ILb!^|pB3*!`_K+TvZaWr$Z%s}pal=Vyb>s%<4- z8y7DG55=p*-tM@Xtv`@!>YZ9|+YX+I`L@++#!vlL{k4&;wl{duizci#UV3rvD7@ZT zBk>*yqYKS5^%%Bo*_!B(lYBSMhA++jT#erksTY0rMKP&(pPnd5r%x9j9uG!L?{qZr z8gk9{x|96-WNLhpDgLm0YSY;MRH|dCR`2W0t`W0!JB@JZ?jpvZW@S>jG&wHaJU#3U zk&H*1Nq%l%?Yqzbg7X6 z-SObrh#sd-Lpeu9r*4}aR~)C}0XKz$*0uWw%xJbY%(ZRJAFagXk4`*cnyHDY)t_16 zaVWLwvZqeHV`{6qW8^kzY`M0siGbG3b@>a+OBH{4|G@?$yQcgaqr+FChhh+3Dve98 zJu`F?2l8V22LC+fZ5$~{FTPlOBn2bZKZ84ozdn%~yF|h_Jb-np(cjR*6RkKtcl7q) zFf@$8!5*a%+-Z_Leq+LA?&!F*@ZvC+M6a~j#3$o(PwckXOrqFPuU72sc$)$2yG<>+ zYB|KT5F zdWZl52q1s}0tg_000IagfB^S@<^Tc+Ab0R#|0009ILKmY**5IBSa-2V^ZpwcA-5I_I{1Q0*~ z0R#|0009It0{-v+FHU{3ApXZ61Q0*~0R#|0009ILKmY**{(mXp>BWy0q*n^kGY@Y| z&qM@zqh+>(51%)-^j4>7e5P)-dQa=FdEapA_IAhp?D^SC7cYPI@@Hp0eZG6|t<9wi z=PtPS&Mn`&a_iIQuB@(|ySR4o!kV#qseb;_rJ2T+b2H~IUbs@%FV-*C&(F?WxOi#q z+~xX}^Q#vx)GuFYTsT+PXIJ$#qds@(((IKhYsQs}hG8_;8f#Z(E}c7nu`#+p|6iQ? zX9e*;{vdz=0tg_000IagfB*srAb`NZ7x>tbS0)C&Zqd8{|9)ZW_YZyt=>Y-=Ab!jaB}M36r|$C!ju1G>Q_(xktcut$#;+c z!;`C%e}Cd%PyVT6*Gj)odU5>yqyOj8>exGDuZ?}I_)m*}wfJKq`#%-`_s#or^OrdYpT3bS-8ET$_tfi>K%C?tGrZ^gY5FO{|~>k zqI}D^^r|$Vk%-jM=7K_!a%$(S7lN$cqI_)UtmlKQr<9NGoOL$H`Z47rJ7*0LosYh6 zJYA9`srbW+tFJbDNI@kZ38iY~*B8}DV{*c52(+4dL#@h{rJ7t>SzJ6TPfqwnd?xv= za&`WVa&>y{oRZ35v~;r>r_P+qBsYwXZo4fp(y2Ut)wb2_S38?2=eWAtb>cGF) z_HxinnAjF`Hz(CL^rn`j^P@9bou;*I7+Ru`Q1z2K8&=!U+TGTwVaLshzWZqnV@>Zi z-Ei6Ths#g14aaab*V;7NaWQ`=GHIHz)iLdD`I=ZMwS`-%pZsQZ;a0hNSH7v*)rA`sKa%NeXBD}sURSGXWnNvDgN?%p zqMcN{k3UtCZeJ>TbJ6b5i?OaZo2z<#Q|xRF({;2pI~>T|t|BD6DLd3f{5<)=;)05VpGWt?8)5)7E~}IrXXGMrcRWkn<5-# zbU41Q*~pFO)i5HUUIyjSE5}RHrAx*4zZ~rBxlQIiJQ2px+xc^|$kRjL1b*v| zx!xB0vYps4!@bZoTZY)PTb+3SIX@e$>b8~KUoTz=9*RBJ-tM@Xtv`@!>YZ9|e+!<8 z`L@++#!vlL{k4&;wl{dujvQ7SFTFT-v{m=c8i@@zj4m|K)MMDTWox2CPVyx(8@^ro zb2Z*bQ*XrVjw<%3PfwJj)2E9Mj|U^BcRHHbuU)gf?j-*{nHryDia#u$+BCL5mFifk z)%$w0Ys75bP9t2pyNEHUS(#KWO^!=9PY*i@CF9X%lAj%a_{6c2bmmO)(T!gJ+HI>V zM%{nwJ9_eyiF6N>Nh4;SYr3hELgr;&x7x0MzVIhfio|p@z3!U#4f*w@rA4(|Nu};I zjE_YqUYwK4qp|Ul^vpBG_q85_f4=o+koZ_icRYADqQ|LYL(ZAXsoQ4973Yq4z)hi` zb?yF1ESjwib8TDmM=LS;qoYBXW@=(;^=DRiZb+@V?D@yYny6T2-olPGr7s}*}Y-ev&%Zc~fSoWxKX7<$TW+wU^iI{mYdCRuO{Ja*M>lh*PUX@1HS|wD zsT}fjKa28c{P~h}{(SNM^TE98fAK)GjeA{j0&#L4eJVA}ax#pVZ2tY%-#YW|#_^#d zFHxMGop66ny>@oE*zWXJvW@$uxG4CC^7zf}ulBsjo4ink{Yc%Tf-eWem%e1~sAs9{ zy*)F$cD;A(TT9aO&lkVid)L)BbXRLy>rVWa7gFf)Cem)@QmcFqY}%V>mO zcFsI~-n;*a;F|rYcWDbsZdfhx^~`l6JlysscJ|?OgZ|kpI}Jcn-?qALuot9W9*=b= ziDa{e(evb&)cj}BSJb|#U%G$z@sF3JD_4q-ZuaMJ@9olm5BC@co<1|^IFM&2$XumW@G1^}Jspmh+p342_z1aQKZERk#hJ{P{QIX zIh)P?S4G3@fljbF#T7+?_s1tb;HQ>oYS((~7wV+)@Ljniz4TJ?{g;A4zt=UzH%WrK zlm9)~%%?A=hCY+{c%wgZD^7ojZ{RClQFwz#`2%*Oh}@pr~96@N`+yf!&AIn#@L{Ilc1U+!NiNv|nI z?`gB$Ft*Gs&8cq~jc(J>T;17pG^4GrHjPI5>8tZqwOmu>g~~Pcjy$xGyi}3X1?B0m zKE*qBxg^~b4J$($ZkTJ^n!awdUCqoi|G6ESPZiAzBFfMU;s-93BvnN6+>l7>wxPR5 zL(|=KXRhuLM!#HM4E55m&F;1bdVFPvW)lVTT2CY^Ug?#RwD5exU_Og;nZHR?on;qA*+Hy_3Q}aut!wu{76XG$KUtd~U zRLhlgRq3&jlWhjoCeu?<&Cbm!evW8KuWpOU5_QH;=yt@65Ie{~LR3O`9ETR9UW7%c9?M_nsEZCl^Q%{Yquw_KG^NFoN0R z*K>WTsxI89_;pW5aRwbwsrC*iRfqIj=bW1OcAe+^F{AcG`AlZb*rVdE!Q6+z1uKdM{{kxZisQnNqae* zgrPwE7R$*RSL09noOF3QYDe)tI$e^ML|8MU!ipqyH>b9<*)^DxN9)%xG^TzQvCp0n zo4trC-t6=0bX?u-IyosX?IxmL>7mi|k`-_A+r*A9A~`+E$DdF6qxS8)2_-B(G?p-3 z@t!(el5UA$ULF;U)iK(^i$6zZdN<+36$}k1&Y^gxE|jF(;0JGDaNEkGigULuah9DOeU`Nzw8g9r=U!Yg zh~{FJCY`LMisl89${@~mGo#OTiIGjWG`B+_iGq1yB$Ab{80Sioq7?t|(cl!2ZYTZO zg|OA$c_5u8PY*p5#2LllMDOW~7t%+A)GK=6;1Ji~PuaMR^RwwXQn=9@J@tmJ+g4jM zwmNoPM>dWJy6I|;ctf=tPHq*^Z6vtqL^=F7aHpxeYnI*8^p2@@bax|eWA5C!;9c(@ zG&RTS+Tv9=vLoTUF`9zfJB~OoePMa2;>mN{ z|NCbwhy(!y5I_I{1Q0*~0R#|00D-*{;Qqf?veb(J0tg_000IagfB*srAb`OB5#av6 zf5w7H5I_I{1Q0*~0R#|0009IL*ee0<|9d4%y$B$H00IagfB*srAb06zcD#m`pwdhmYx~^@$pX`{l&3D@fV9n`;ixax&QY= z@i*_~H%gLrsp#D{+YMvO+|r!-hSBIY4b9b^O|5RV*UWV%^VDqQ=DIasRm(M1UZ`AC z@5sBZOJ1tTx%J7@>BnY6S-3GSed$uM5Jc0Q?fKF>rM#Xgg+C49X2)!FMM z>C&a**N?dRYSYNgl>6{z*v(q`^+k19Skp3v^B%6Z)n0wuBmrw zeh9rM4>kpF(r)?2x09o=yrhz`Z&5=}L1^S)unDTx}5cHQ3Y z^y8Sh7`5fvUB}hxMk2^CQSX>q*KWquMfm>nmf>z#{TM`v)Wq|{|}0Z>$cVHh*g>_x-hc2sKj7{ zQHtUf=Sz|*+B`j?&B1QIv5R(lrG~eCRt~%U;PsMJ79pI<4Z#%4$7mX2P9!^iV`KpR zGK0*D2`+3@_8)0dK8Us_sJ z%av4P(Mn$37LziH)-M+=;emvx#5Z&8&o5P$Yt^!N^U2+NTGCkSN%qL1Eh5rAD+kYm z?IXEEMCnR$XArdp&wHCfc2kLZ6?8XM&fnVe%cO{gl$lh#CtoW`w_YiFFGnk5-Dn%O z-W2axqv5|29j(5hyPE%QHX8$p*RqRbAV;#ezf=Y?$kT}i6z}+Vl%$&?AZ0{A@diIo z+59fziAxU)C(fXFW3P(6OGNYB@M!!Y$fJ3E=TO3;L*fWil}EMDm84f*DSqXP!B#NP z=Ya?1)TS_yJYr{v0?Iq(B}OT=6tjnmxpV0qBbrD98$fEQ$GKXTe^if83E9m=9PV84 zVhr}4R0ZKK)6v&ch5e-zEuUeVLf#8MxniS%NG@3aS^mOHIHi_d^gMd+&s-gs)aQr2 z8X^xzn~DGW+QUzLwj@3OeDS^B`94mF|MDHFk&hpb81X2o#0HyYty{Jcjdv=gZngX) zO8gf1MwFvHGZDqWewj>5jzIK0^1OegB)z5-y{Dt4n!1)an$h;}MCogu^J;dH<`?o; zXgWon4(n6AW0%E_B^r)*taMJTVXkd!Vp_Icft*hJ+z!pBisl88%AoM?{~wC4V9*H! z5I_I{1Q0*~0R#|0009I>3h?j$kK`c{0R#|0009ILKmY**5I_KdLm|NZ|4!4@Ab!4@Ab0NqydzJY_>B|Z@qamXzxYpzHw!;|yXEJ@3v&sTQpb5Fr+XAQkWUTP0~h1b2F5aL$H4 zJ9jZJuJ77aT)pzcL+Yg~p0v`N9&;n3F&(YmwQVtF@*;YBR}uB=7#>wWk7C^}NmtJl zy@@C=r@mn{x=ll~yJEujhC21^i`g(zsbLAf?bLI5I+`^n-z-T>qQ#jZEk^CTy0fX7 zjZ`gf?a+3nY+e+ZEXwyTm85wQ&NKPp)NMm|jfSSXsX$gn2huN<6GA^x%+g9px;X+P z*ekTKL@I*X=m>h+QOTSrdKu2jiDOW4* z$<*^k*VbL}9@kn5loX z5y|;U4~)9i6068H*G!`!zrM7zsFo}8HT8OVWw9o&=}pH-&8&0*v5%#OH<7xn1)Ye4 z?{AWEiB!dJRu^uSt9Rv_>Rox-Yy^Q{U#hALH!A+K>FktNurD7rIf^)BFx`w8AT`TxJ6J;2cHj}O;e7xu#ukGq6 zIP_fpo!Rc@oz4;mpSEE^hWPpmwwIdw0nt#A_lH^oQU@~Kf1haZGNe;T&tGF z@XFnL!*99aOpwD|GWO01{o1R009IL zKmY**5I_I{1Q0l|0^I)(?9dT70tg_000IagfB*srAb{@{P|E{UXhyVfzAb009ILKmY**5I_I{1Q6J@z)3&nQ@hSiMg$N*009ILKmY** z5I_I{1Q0lY0(}4f01g@5I_I{1Q0*~0R#|0;4uYG9=TgMIrdCp>{rH~Ir$wYe*MJ4 z@qc#w$Bun#>32#u#((bUzd7=^MTTpmEA_6fm!$QpMNc=|4P(pP()4ws?P?9vHtMcr zZ)+{1wQAT-;z=)u*%*?uJzrJJHC0}yTvPAJk5!|*RFQ|&Do^)AiULq>t&L0i)nXxt z-MQB^T|?8mt`&Sfv?nt|nrOXu)F??;uNJ@hf~&7KjUm~FJZ^^Fu9aV3REPIsa>8r~ znwok;t;&_9np{~~Ts$jJP7HQ0H(PHw!oCfu%9HPuq}y{v??yDJo2y#Gs&`xd(B2oL zXwzTPz(h7;2#A8uv?NhZc6`qR5tl|0?cW;T@f zlzK@zeY*IyQ;Dh9%ayF^ot#M))ircxMUCXnr!})_Xl=b^$ZwUa^KX=^)3bAPN@`{X zS={YTKg-;?oE#n9-H0ohJC~QmG2bGq~vQ}5LLB93Ld znq@Z(JE|xZYj1kxCe>|2ca4U&x*a9^^+iv0SH328t=hsZHC17^(+ElpOMkPvaI0Ls zE8kS_%F|*X{W`BNRn>(X75`a(gypJwU9GB>d3CwBJ2<)dqj*-gm1K#oBUWutU{djB zS4&b|tev~j{Pfp`xwfr2+wHn0Hg4e)Ebr8U*LrIxo6pQn-Q89et)*;*i3J~SHKJw3 zll0!6G&eeE-PIk#9TMxt?qZGW7!hKeNAZq-Pf1!3oTo=d*54_!9bVs6RN>4FcgbuW z@^rW{-q6OSx95hv(sIXUChzImSM2XDNpo|>KU@lSl)OB7&y3U#lb1uD9=g-4+g7(D z#xA+Q61#uy=;Uc3|zORK|L zibf;C^rv-i&+}`{oimE_oh9it(f%{p?)8?M7QPe1ruAV>r*o%T?IoR+qqnQ>D(}B` zwrZLwm=u+VU5cmnyw2*6B9g z^s`7hST9k7yV=6TP}%-5Ewl5jnQhbA7<|6d`76>(Em<+3`+BcQ;iV!^o&)*!|3`mq zgH!|%KmY**5I_I{1Q0*~0R#?%0QdjHFpBg60R#|0009ILKmY**5I_Kd(E{B6NBfY9 z00IagfB*srAbq}?AbWnm6N?q`OMdYei4$8@j8xmethkZrjlu!*NWj zt+~3hsnu;mRNhEu`M&w8TCS<`LgkuzM;3LalXGj3mnw2Pn>-!0WH!#qPJP2@bel%6 zS^r7cw5Gd?H|CV28zSZxhQu7y+_cs;GZX6f?htCCU|xiYWTo3FNw1wLdQYcf2>ak@ z`nu6}qxPexTe;0gsd1UO=_o~>j;d3<(^g5+M7y{1+cmaa!*1(Mt!}mN8@8jn{@{fU zQGE|a$1$vqoVbQ%RlHKWB;6EoD*16Xb;s58x@+DS^Vkhwqv-CBjxJp?C#G};#cq|P zS4AKv^8@KRhMo24j*cKKlGAjUqIlolEJ<&RMzs-*_Qo_3ZA!u2MGONq3=iq798ICK za-zxJa@s6O^CH+Y`N4+cl0|aD09Pstw^y>OKN`z;@tcjD*!ndq-}_E4hG+6)=&$}1 zl06!!Un-~ZexmZoHA~W&GsUl-arM=vk!m9K$-S_>TKV-wwYPyqJ(Z^?CqyR~DmC?n zT9qqHHMz2~xOi5coalE`eyd!af1_NTo;i0;N#%*=R9^XL%_O}A;p_0G=CrR#NE z-R(O4^h~qE)^A+E57h5NUrW9wHv8JbEj1l~$A9fK#C*z6PtUphJa1MPZk4Nd<(ukV zdD?6Q?OtE1stY$N{{8$^XjtfKXY<(M`}tkd+@NAe^T*gH%gLzwdk!x zlde~$VcJIBwd`%JWwcgB{oz034SGm6D?1y9_7sanp)-b-g65i=g$L zg6?;tSGhPC1TUrj^RRpE-NxN78Pzy4^ug@Pt+jDqe8@3oNPODNkc5^v)O}XEdbRk~ z7lMU5B%8iIcw)F}k4sC+ut0)E-#-J*q(6W6UPHW6PA6U|y@uDjW<#93dY?qvy@#9m z#F-L(&0a#{z5m`(qqLiz`lpV*dpN+&)V4K5X~YKBuQ2Lc?pBnUs=0X_%XT%(ZWwlM z@=n`K-WD;xR9UW7%VOu0yZ1uR?Y-Ju=xy@8Md+bqj*hS zRK<~azPvnNzNY#cXmTUVwl!pj8mwqi`AYF#Nm7*J55L-fRmBrEJx#Y$qn=J1G1x(E zZN1fhsa(8}ey2oe(Fpq8%e=pK``UB6wtqT}UpLvNf~b2Z`DAO^>p^asxW4#Rhi}w4 z$dRcy1GV|DF%ALRV(H|3p}H<^>uByt`$(fsI>`FDOlMhhTh zADH9`?o^}E^ZYk$b~I8&Q;9p2?~Pb~asM(Jyyqtse*fPA|6&H=BY*$`2q1s}0tg_0 z00IagunPhH{r_Dckp%$+5I_I{1Q0*~0R#|00D%K8!2SP#42@PKmY**5I_I{1Q0*~0R#@X0Qdg`K7fRe00IagfB*srAbC(KmY**5I_I{1Q0*~0R#{j zDZu@IBoB!QAbu z|BvJ$5dj1cKmY**5I_I{1Q0*~fkPp{{r^x5Bb`710R#|0009ILKmY**5I|t00Qdiq zJR~B300IagfB*srAb|@ z3yBCIfB*srAb{o?X;!)obf`>g+&=5BY4v+`=!G24dY_)RGC z7vE5;YMd&+DxZntX8|3+1<97gJM3IR$Fs* zXETZXOpL+mdu8Tw7y|9x=o|ktp6kt^Y?pCl%yL2WWD*EhxUiF z5&D!`ZvH-7v^;u)kP6_YcVt{rPK_CG}E4`-PP^w4iZCbYJZs)e0S}suyGqaZ!Kd_Fz-L&+E_Kst<+;|{4p-x3pkM24nS-xS;H>UNA2 z^&w2rUHO{WaBB;sdq-*Oy8cV_|2~{c6|Dw&{pv zku2vwf3v!9t6aS+-&F6)(`F-3zrIve7j9JiXVa-T6}hTj7yEi;UR{>Ej$w;QCCW@H zp8VyKv@$d1snMif)9+~;maEnEcEj`|7Mnq^U24Ww#}q>~n4$2M?8G0;lc~gC4uhG* zZV)teRu0<=_NvM6D@h9?#M2`}6tkr5iUAp{v+({df{Tg|3oA-ju6^&g^u?L6LJ*2` zuW7o5rgvQ{_*@%oU7HzvR(SN)&%IlcW@g5|{z9=IG*xohm6 z*0$_cJo#tm=F)qBm99gZ0qg1AzxoyDvOtX z_~Q4MnWMKl;)Ue*-87uUR_2P&?~4${iU>N|PiyLqtBL*%uG!3XJ9{ooE%w5e+)QPAIs(uv8VlHwJ%Mu*TJ_jE0VKeR&# z{epQR^i!4X2PLU2j*zE@AVlMtZvO{%Xg(^H*Lakscu(FJ7bns7%#gO@gQPgjish3I z;rn+8AyYUnl1vumezzpOCgOQ|NIb!2mW|`fJH!zd%4(FV$jvYzmtDq1@);JpH!fN6JmF zkaN!N?VUlLKbTu*xVgr`_dZu{|3J>=Ejri+)qO3ux+qIO!sv;@_y1F0(BKmU5I_I{ z1Q0*~0R#|0009IJr2zN;LpiK;3IPNVKmY**5I_I{1Q0*~fs_Eh|1ZVCCkP;b00Iag zfB*srAbrBetXfB*srAbJ9wP_^kP5ia+6JZ}~<<}S0bRQ-s%!cTDO}(L3<;qe`uBF3sw$(J^Lg#1G z4LerX796_k>h+D5U(u$q9p@Hd`t?}0xo)=gX5ik|Tm9;0=jJl?xt6W38(PPvkF=)8DKv+$vY^ z$~V=!^0e6qIz7KsS*}&fVwTC>d#QyOPx6(@!tE7Ro{k;_<*qMP)rA`szpl($m#gY^ zwW?O;)n(b=Q=GW1WSPt~SCXX?%QGlDsXYGbPwxwbKbhUhhHoDJR+f`0PuoUEH|=oP z6;JY}O44nyAE|JF%?a5t)Ci-L9uIA5~ywLu{ zZbD1cF*LM99_9Uay^|&B{Q0pTekRzIa~jThRQUH(n{-YNd3xw(9m=G)(gat$fG?j* zZ&hKQ^agqETrmAxmRO^j(=qCC@!2rRY>SPd+0>d=U3Zh)jK8`1t2^Nltoqa%7K#2O z6Ge@6%kFR8A~?V7n%-@SAv2u1ZFYj%Yw8{GVoJQ6detYk>Y3SIS-s=$;yDRno7w#= z!x854r%Moa*cCt8Zrki{`H@2}|M2GOmeVhEp%-G<#)f!{IWcTHE!%fLjPR`|P5|Nv zlXxvhJ&!id)xKwx6z!QgNl~f9=A43#iVjQ9Znu-lL)|-3lCE4Cd++Um*{^pSrYk1R zdhhfS?qB_7}CAQ?oc*X4P1;Y{TD0blIPa z{&?tXt{8~aBdcTBx;P_fspS-nf^FRE8cyms6i)b^24N7{oA8d8qy zQm%Uw&p!;a)Rk!UkH4+}r~l@s2v-j@FAz@!dM^2+_Oq0>2r+-Xa%i%mG*C3d@e zrzZS}ZM-2iV%znP&~X#dY|UE68KNCNoB=y*s4czST@$OTYbQ3zX!jKD+S|dqIo@o= z?%n7Hi!uFNG!wqY}T1gF_JN4W0dJHmav*)_z?=ayPs zn4g}xa8~Y}mPHe0qbn{E!!qdg;M}W;D`s4Iyp^|fdo$iHqBWkg2SXa|3Bmbpm_ukKmY**5I_I{1Q0*~0R%n(0q*}F05VM=fB*srAb-rR2q1s}0tg_000IagfWQYJ!2SONK&A-<5I_I{1Q0*~0R#|0009I( zWPy`Mzq9aE;TH;%vlG8??AMPyU;4`U|23{3{hyE4$G+#NRQ&DYjlwTXtv~s{Kl#&7 z{`7|&YS_H@wD){Ty7lsyciwC_j4g9Zb2iLQ$84`_tGZj?FdVIJweK6Yqr0Zn&L$TA z{Crg{*Hn3-a!tJ>?^Ik~s>simW!hlvP z3%6HB#TC_%A5)a7c*nfwO45P|=Je2D>b9Y~MnluxfpC6yXP>xmekA?MmG{qk&z7W@ zUmp7*$<SzJ6TPfkSLm)|N^ z=iew-r!QVmQW?6AVT-Yf3j1X;!x$HxId@J8(z~{8v|Vk@s&^gD)tyZ-esM0*fS+m2 zY#L(5b=z)Kb*kAOhG^Jmbu8Ct*SEDzV>_;7X7+MWOUJhAhT~{Xx7E_^ZS5V$YRg|( zUaACf^ue!*saspPrKZ~Gb{gSm%DL%pRu^uSt9Rv_>RowSOjp0o`K8Koty&h8a`)cg z5(=~iW0%88Ivr}Bl?U_q{R^77zEo8gZdCkcqx_0oRj;d6wKA_R%YGeBUO;P`g8|j^ z#-g9i9~?(cwwPNW)qXtrdWEOM0ahlJ&wHO7mzG~1D+CM3xz{vZL({vi6@1=rHJEf_ z!f3d(oQu(-nRT5Yj?xY~y9Y$OBwv!enVEIJTb zmMhVW;(eQUswAz5z_dKDXs}&ZuWz*c;Kb5T#`b4M#g&2^rm^=NMtJf=`h;Vi+Hyc?HqWraYg>( z8)6%j8%ERUy@%z6<=|Z=mn+xgOs9ji@Ll(1@1wo-^jzMEqy{tDw?8#%BvPdYI+99N zE_xps_qUZHTVtY4Z6@(a;U^1)C*CbdFTObT^_Ac#kVs7YweS;RpuGb?B1N7a`tI-T zV(C|N>IIqVLhfr?ObcDiUvWN2oFDx6)aP2ZzHVsZxNu(_DeSnafri73tKIsh;l|ng<3>ux3G*e- zBy%&FUL+&1f5IhIr?Rtz-CMt-mM72Pr?2#43%>SN`Mv+cwUf3hfVmEK5v(EuQ4j z5iEKzaMnuA_SA_ded0=F=7^G&w%?dZ#?OcWJ#kI)rdaWos(@h26yw79SZ* zbYu@sM122$e|%MgC=fsZ0R#|0009ILKmY**5ZFrr?*DtKOWg<{fB*srAbTN|9%<`VnF}_1Q0*~0R#|0009ILKwxhKxc~2sE43nk00IagfB*srAboXQY!)oAbr$Xm+=)wXJmC!q3lF z)pAXh7b@4(JMv@JB`;Ovbba#l$i@}#Bi^S=(rpp^+>qcMt83Q{(Fa%G6#ro5H0 zJH(qUo)=;^kMcS1#c^p#87l-aIro~TYiN4cwSv#Hyfc}Q{^C#0d!H&viZb>~uetha z(@3YMKP&uP*nwL4^+k0+Z*szHh_R@tH`J3M<7jJQAsKeZ7Bev0aw19dsRUG6t0m@XdM1U_F;1;pjs84~jH9B7ARSkCyG}eB(SYUTY#Hu`)n5SFoI<7Tn(p?f zsgj7Uy=L0}{=2%J>~Ky7-IcG2y|}h;OAVHS*wr=HiaErvx@Nn#JoEaTN*Ce9J)N1o z9L&vB2CLh4?S7un?SXC^8|?$K(>vF~RR1KKv~;!ULGO^|-ReyfRX zCyc0{D{L}<7zeWDkKsTz5n}G}jL4W7ru>}i@sf?U(Qp>^v)h(fJmRH2Vyj4G9((^tgkg_oQBdUK=fQ-R{lb!9kRxE$vLl5Ib~x{Y+|Wt9NbN-w1ov z8C$Nc*P|Cz7(fuXZPoovJg5HT+cc`pag9#Q5l%SUxNjN{a%%AFZw0T?!P>_ zDh@MbUoA)x0rXW zjwN0P^=)m_=1+&57B4ulHRWxkVfkK$mY7gtSmS*-Otg)< zVRqc~X!{dN499lhl3r51S*>k!TY5WssYZK4IQ8<|tBW^qrjIGAZpUBMDT7q{o7II| zU^ z_9UvvRrR`BRV(xAa{s*RA5)z;oMidvw3=ToNF7o#JkzEM`p@#)3127CF)~#uSXDvF z$g=SzB~>^EXj`rsUuF6gCG6KW2kd(X=+r4SsS~|-6Q|gbjmH)B+fP+DFx2_A1sBWQ z;p(3U!_b18ikN1(!#=#8ob%A?cB+!$L)qUbBc8-teMB82MyO0{~4UTpKBfciy{UaSG+Uc<&vZc?%PAS`wfPj@BLI}ChWhp>#$R`La4U2nD| zl|_uFhQt{CXlEv@U)>?Bs90VkQJUhN_hw4cx@cV=()x%W)XN0)S9b_#L```yj>xV& z@XnQ_*F@A$4~aV5;xiHcl^r4sOXWoqCi%5IPgjU)~{}e!;wW`l-tIdoTA!#+Usr=*AdE~T(=UJPN9zj2=}Neg07UK$dC_@xZ~PwWT3Mj^xS%R4b7isl88tXlkD z82^_wy|lwGYl?pHRQOwmG6DV44gtm4qhDH-b4_?L0s(J^p z|7wTmhErI!WFN%=L zLqZCV6Yus9 zw#><|cr)I&m87}=9ro%8im&GUhN(=*zp$H-^XeHHb6x@ecEGQZ6Tf;S|JUAy6Epq= z4|%@XJb%z%Bggmu58{_Fh#3I{5I_I{1Q0*~0R#|00D;F7;Qs%3UgSmq0R#|0009IL zKmY**5J2D{3UL2Fh@(c#2q1s}0tg_000IagfB*srJe~me|HtzpHv$MCfB*srAbfKmY**5I_I{1Q0*~0R#|uJOS?ikLN{h1Q0*~0R#|0009ILKmY** z4x#|}|ARPc#Ebv}2q1s}0tg_000IagfWYGkaQ}ZiFLEP*00IagfB*srAb#q z2XWMh836aQ{Du zqejdKAb+!?009ILKmY**5I_I{1Q0*~f!zx5{r}xckq-d`5I_I{1Q0*~0R#|00D*%m!2SQ= zjvbLBfB*srAbXwn(hv(?04p?YPqJ$3zci?9eG4h{i@`piaew` zdAgrX@xI-=UXtDxaW3o>XGgakLwmZ!f)xw=!d##YC) z4QGf!;qUD>(6FA7F@|}>2rAyPcdaDdyE^vp=uQy^GpIKdLeyw=EZ1n)w}(aiTf2>T zNWCL_5YFba@?bpLrm^kA&zGcSF-@-Q)Ggg{40ps7`MbOAM^w?sz@tq5M1K9TCbHw| zZg=SX_#by0Wp94=DjOMTGNa^AQFYDe}U(R>urS$VbVm~FAnlEEon)%%W;op5LoM8#hIR07 z@3w=(DjwOzY@ujD_`9=G@m?L5^s8fqpij=drYWM{KJ-m7JFF|eQSmhRacG}@1mM|L#@h{rJ7t> zSzJ6Ti^svcQM@VTx60M|H_FxNix-qsj%c~&77sU}+_bvY_E&-K`s+Y6A2l#@?wsN` z-RasL%Q52T=V#LmCs*IlOqSgcFLh(fwe@blf%+t z!;r6uLtAa(mg)!C&mhLiYIgnkl?-559x=4KKdRAO=+`6W-nw|xy1KKOS#mjb-4~N& zb=zM#;ldq~Clj?;c22hy98OcciJ!0f7@2D0#2~bEllkY17-DAjaxk3z6IHs|_^2E| zPA$D|rx6~d^V8p~F5D_t@5(pTyYjTz2%4H-sw~&4Wx*nM?+x9=`&-*eW#RUUDvC#& z-DA|!+y276N()w(Ek_kbd*fL-%pm^aFX4EZ1`ST`MLYkEtt0PG}>kHcq&BmBvmec4+W`4egtt9;cUvU z!B6a!pH##hZ{?eQ_wrV}&zGd`t`GKk`&!)J^j)&>cXoTG3C1q3=8=b*aKwk5)vkN5 zm84B^w7<90SuObz-RYe6-|x0hd6karPO?Die8%_xM}KvLR0I$}009ILKmY**5I_I{ z1P+4$_y5B%iu3^i1Q0*~0R#|0009ILKmdW!0^I*c`;dwN0tg_000IagfB*srAb`MO z5a9lQ7)FskAbZ z{}00`(gy?(KmY**5I_I{1Q0*~0R%=1aQ`3eLn;CYAbC)Y!-&QI-(LVBXW50Xi>nE-r z|B1qnO#am5?@s=1RLi)xG9LW>J;PfrNms6neXZ{5t4+h%FgqQyy{=hy!>~1{zG1X< zC;w^TAI(?Qa!r+M<<}QgIm)yLRi>knrza=OhP+UzsW;TBTv@8gm6gTCv-0FbFJ7%~ zH4OQ!a&`WVa&`LR1tpcIVLF|rzOA+ORzK6s?Bz@@!>QY5$2G0CTvPAVg4$i(?K*MA zGZz*4ntHvwvRISP=ylh;Z=6ZBRJRS?H5%ILw$_i=uc+H;Rox-Y$$$X^GlWGTD2^=Y1SGmCC~Z$KKrsN0Q$6VV{}1!z^%%y`w2kRPW3>Xjp56%>Qu(H@Xm;@g`U3l-ld#6~cRtxX1@X2m;z{WZM_o-rm~lX+p^W3P{xwpwOFRQz1^sLYkps&9W|W#@hvWwbY#nx*cw!&L^km%$70VU z2{}h&muVz3=sXE?Omy8_2FoNtBPhwaZO> zz6vQ1cJGl`1osPWtyps2D)c`(sXJbFW+{i|QPYzB{si+Pt3&_Yv>nQ9d2E;bTAI2{ zxS0G4Q8EzRA9imQOZV7tU7M%0 z@3TWCqtO_;p8H2ZNBI{EX{gwk_kfV}X}k$|3DA2B2;VotBmWAwn+`OiU7CA0P)&K? z=3foikJWPi7a&Li9t69v*5OCCS= zPD66Qn@V1f*LM10C9XGg%9-%0lsu&j%{zZmN#V2z&nMiJTPDHnF|R{Y zz6-@2*gMUrvLN91|KZe@Ap{@* z0SG_<0uX=z1Rwwb2tWYu|Cj?1fB*y_009U<00Izz00bZaf!PV_a{vMmfB*y_009U<00Izz00bZ~`vUm=|Ll)3dI$jsKmY;| zfB*y_009U<00I!e`#FM#*|*&k!{5CRZ@00bZa0SG_< z0uX=z1R&u3^ZyI^H*&B1yDwi{`1cp~=KgT*Z@uuz!he+iqx>6%-+@n-fP2GzR4i?5 z7u-WlSLum%B5C@u)RRq%NWvnu?`&=^ zlZE+k!YPJI$^A;RdaKebU%x7Fg;dSzb>ve?m%DMHmDM-+QpeP^G((RbvnH-rb~amN zg=@>QW!tf$N3C2JNLX-5HRXMKi7W1}hJC~A%6594la6)5S5YaOt(wh3k>0gfJh!*m ztWWk?X;bCUa=KB2tiPT`Jl!WYF=l-Xx0*Q*hYKdwm=s!uBXVWck5DnGY*SU*I}Mfn zF?9Ain$;e;9+qZwYb-&uYFi@b(2MFNN_Y+4ZPvCb&0TUw+$CjA^&eer)VEvB3Y$a3 zIU19WByT1~@$b}Y_jW{5PENCB67-U`y;FfS#dWbM)~n(+aV$2o zqCk=r;vQsHSrBf!yK|*SuTNa=W>1ciYGQ#WFX#U0`)&7OvGn@ugK#n5%Cu+2oWPkZr#W^;_29v$OA(A=QM@fQhNt6pSXeC@R zVUi1z3ZH%03{%-Ys>vP6>8bu&8k+m@984~;urR;y!m^1bxX{8{S@$Qev(%Xs&QgD= zk+dZ?ykeEZcvnl#H`W3-6{@$y>K#%Zx>~D~@{+n|EiIEJ#guirBz*5nH?$eEaGUOf zxe|SQ;=+y3M*AA=sFt)Eu?^qK{m)JJ{*yJDw&f3=m;0Z-^$B;USbF>I!k=mISz-A3 z*@69!>DghpfiW4v4`whY!foTpHgc6(imCOy9W+|a$8yJ^e7@keZg1)H+puHF2SYWy z3=^))r30!{Q||DUG>dh>q$8_-U+!4^vLAPjU}tCTnDQ-KhG|PI9Z@q}*KsH-moM{$ z!-dT+_jt;NO?Y`OESt5+!&+JQ&yWO$Cj*}V;_)9|{%pg}oOlv^5Sr7$z(DT zQ7|k)A_@NFCy-!JSPn6%t+6~DWRb+dVr9E7;*x!=XV|DW}SkLwVC00bZa0SG_<0uX=z1Rwx` z*%81$|35opiJm|J0uX=z1Rwwb2tWV=5P$##vIOw^|123?hX4d1009U<00Izz00bZa z0SL^F0Dk{JJ7bBSKmY;|fB*y_009U<00Izz00goG@cy4AgX<8000bZa0SG_<0uX=z z1Rwx`*%83||LlwALu>9Tzv%oDUP_GC-OB14d=X1A5?_z^ zz6R~hnflJ=rvLeOQ!`BV_1kdSMPFOK%oQ7aK(}kCi3hQkqOU~DouMy84`l=HBh;!X z?+<;2+Dj0I&VRUi_^a4KnVx*wF=RF4d-T(NU!LyoQ~%@B(!ObQ$y%i)wrX3V2NK`1 z4emxf$3rWxcsz@fSHrSdc_plsb$>$MN&iqZKk>a(Erl9kHi#zFG6`-?_tj{=>A{Q& zza8yQufd0%W$V!UwsJ>{zCAzjtI>SRiD?!zpSUvkJT;qW>=CklI_*cI`6mSPG7R39 zZO39GN6JfsS;^Y&IeQ(=YO^n2vp?`3!Cr4P#o9)l+!1%n;TZ3oo;l%VR9Fz)JMLbw zbnijIJq^z_ENifHlIbY6V^T@h<<6S%jfhowb{ z>(1Nmmj>Norxul-XeaD{Q%7fCV~M*hTkYwF=YOBFJ5jS|=#F29eI#5tw4AQszTryj zWY0!qXF?Z(={;Qs{$R=u1dW~{{BV`Yw($O{`^94E!GprLD_Q$=JPij6g<8|a|IdT? zTa}xeB0FAby`Fc37(eqD=Ht^Uw^>?-V=7cSWWv$5%pHddih*Hnc*3R|Jq_TQC z)T1bQy=xgdxxL+}^F4MB4ya|bSAniPU{5c1EO#_j_Kyi{CbJiV(~Kj)W7*Wb(MxY; zOumY`&Un1NJu?#w7aVL-CbgW7o$=Uk9`8jbE&mD3%j@}B&H-oIgBAq*^Z)68$APO5 zfB*y_009U<00Izz00bZafmss3`~NJBCi(&a2tWV=5P$##AOHafKmY;|NEg8Sf4U2< zLI45~fB*y_009U<00Izz00d@90Pp{^G@9rO1Rwwb2tWV=5P$##AOHafKpAaITnniku}FFF zkY&RDS65|I^&cmEKQtU8@eSS2zZ68>>N}g8%Vc5RAAdFrAS-0+EJ0z zMl9{iG&Kgxa7=|t)~RLFZe|+;+35C_Re`LD>y@3&7Fjx$JDTdv-z6?~+py)1WEzjH z=($mq%Y0G4h3SeumQCGTN>jB~@$ywsJ9~KJduzzvA(G+VNbuW-IPb840xGpxu zdR5#ejzvwjT!ToHm4@^(YAp!vmTMME@{K~jn3;4WmT3=IcC}^pKX#a8M_2ctSpLO{ zIVios)MOMCCFStpQRY`AOP70A+pw2OJnn*9c8`js-5cYwX!!iNT4rZnn7T7@W8*s# zmlN)~y}6QdWBj&|-0p&bSjh~x@bx9vD3)&AD13_zS89$Pw2|3DenL(jR43)kTpY~s zc#Dn)D#~BU+#QtnHneC&qx`sf`7)oS!}ZhlwtdA=Q|esjYmAvVsqqBmr;H~k&8FeB z@yLqJaw(td*s;YjbkY(ZvOO)auc_3QwT|?zck}i(J9Q*)#uMr3C9`0Hh04JKixSzG zu^mZUVL!7|&s|q9mb&)}ZZ|vibhLe{oGNVhrpHvb#~<;A3+Ho_SMPA0Fui$uMCvhb zxB_?3bNAeCv1HvV^j|(hpZuW{FrI`8r9R{gvIsxy{3CuEZw_Tcz-b?wGI!|6g~Xc6VmN) zlVcKZJXlfs^p2NY%1GHg!zAdRpThgu*^etWKJ9r$!z_?|N+R2NMV@++OP+(m=Vxc3 zkGby_OWW+N>&?u$?7uU`FG3^3YUTc)i4%3Gjnr8=c=L)MB)G4;TCsG%f|JJt=O=Ad z(sbKMycw%0VgB(HVP>?J6>vsz0l)tr`?njo2>}Q|00Izz00bZa0SG_<0uY!90et^& zCWaB6fB*y_009U<00Izz00bZa0SJs0!0-RZ^57-}AOHafKmY;|fB*y_009U{eLEg5uJbl1Rwwb2tWV=5P$##AOHafj1|E9|5zT}ga8B}009U<00Izz00bZa z0SL^50RH{|nHWZN0s;_#00bZa0SG_<0uX=z1RyY00Kfkq%Y&N`fB*y_009U<00Izz z00bZafte7%`~OS~BRT;A2tWV=5P$##AOHafKmY;|7%PDH|FJx{2>}Q|00Izz00bZa z0SG_<0uY!90lfdu#4w^05P$##AOHafKmY;|fB*y_0D-Xrix++~_t9K6_sXxm@>7@e z;y-`sS6;gG;&)&Cffv5>LcZ|z{2%4NnES7C)y2TyS6R=ZmE~EEXX%7TWD~j8jS_O&xA4|9umKNz_h{CQ(3eOZ{B2w9UeK zGcz2;VDV5}Gjz$;x^yI@k4_9}sD<>fh6)Mp1^26yMopzX*|fV@SBTsjLHNDm~qDSWNzo)k;3y;k_^Ie2`la&uEmNs=E)OooYdR_(-ijs{ zS!3DWYhkc7!zNZQ3tU)=W11}SNJkE}{N(5lNNNu(w#U%aJHe3OY&15-N}X$;?L@41 zwxk%2Zl_k3b?Y%3YL(iu*0IR#?M6Ka+Z=3VeotDpEs<+@DA7iRyt?sD6MBW)*DT+wo&)4mBZOXn&P_H6zf%Sn|RkOzx0COK6D=!OGjG; z_bcK2w%S^+=WW%BW7$U6o7>%OwMGw^UV>amw^Hkc`I@HR#p8p|k zwPh6}<;+#bKS1-NukMk~#S-DnQHmTG#RGN&0YyL4S z(KeW)CmZGdrm|_I*{8wePTY2Xus>HU z-MdzBuZ>JoTec1*>dnAty|EK>G`kYF^B>DxW{FaXV>h>~5=Hpa^AGl4nkF_sM9Dtw z(bU*}aH`niMzUjz%Lwi({TJEEp1DOQ`?QBke%~}T?Owh#RbW92*--@rg#J(TUnrKY zT`Roz6+Vk3d{g82f%NQ=s5T~ZgyE&`*WTRm2PT?v!|7zOo$<>l&Z1AY?Svr7ZHMc4 zwEx_4kEhMi;raj&DYdtOb%$oLekka-F%7wN=RZ%h)>VXf~B($7bhq z_7W^j3RYU3R3cyel52lYk64-bh&lZC|Kq>Wz)ui>00bZa0SG_<0uX=z1Rwx`Srx!P z|39lEi+(`>0uX=z1Rwwb2tWV=5P$##VgbDW#}@br0uX=z1Rwwb2tWV=5P$##ATX-} zc>kZ(kww2C009U<00Izz00bZa0SG_<0dM1OW&@00Izz00bZa0SG_<0uY#0 z0lfdu>d2yB5P$##AOHafKmY;|fB*y_0D)Kl@Bgs{eu4l5AOHafKmY;|fB*y_009Wh zssP^qXLV%JF9<*Y0uX=z1Rwwb2tWV=5P(1|fcO8{0zW|j0uX=z1Rwwb2tWV=5P$## zW>o<1|Fb%>=obVa009U<00Izz00bZa0SG`K7Qp*|Y=NI3009U<00Izz00bZa0SG_< z0<$Wx=ymMXS?wMA1px>^00Izz00bZa0SG_<0uX?JCxGAoV;(>N0uX=z1Rwwb2tWV= z5P$##W?umB|Fb{F=ph6k009U<00Izz00bZa0SG_<@Bf$s5P$##AOHafKmY;|fB*y_ z0D;*Tz`y@L`(unALI45~fB*y_009U<00Izz00i*+f6M_0KmY;|fB*y_009U<00Izz z!0ZbwF20akEPOq8;SY;{eeR#m&As%w7vFnDy!7jff3PUL@Q+_uDSZ9Xg~j_%;^6*x z|4$T4@7yT3HBDFPiFP7cZLQbS^aDxLkEw1O=Bc!=b*Lp-hGQyJQVf-5mC1j)+7v4- zk<{vI;zKfJYot*pSuK)s;<1AJ@%~4OrEM1On-jxzENV)cn$>XrQ&Wc;v@|}z&Dl!a(a3^C~1W7(u_gEf#D>yJ$x>u{6fgHG5klPCcOkB>39@Bc#3Ow7ie!YLOSW?*N?@k{oo=SjMe8T`kC;CJe^dppx4ypg6S^n%O2 zEE2($`V0OL^o5B-5G-sh2Xy4 zpPzP?4K}+k1?}rzQ>F8{Nv9XDF_@V89Jh&w`#o@stH^`D7{t~Iw*GSwHscn;bqebdF zo16ZvM9U-hlKW2b<~Qg2#bW8kjly?7Y0G=;1d?$u$-18Zp}?+Hxw*+=&!|qy3-g-F zPAn~PLu^K2FB5iocny;Km1gx;rCGjyRp3hQ$+psFV;VN&)eiG((6V;Ysmo52$w;^&+{{SOd;N^>c?Z&{2{teZXumH9(lIqHjTwba z1U-(H;9#E`zMY)2VNJey`?ME7IcRh!Ee$uC$aZ9nos?U(Ezt{@UDr$|DBIlS#F82g zfz1KcVe`may!^xq0zYynJG*m35+9MGr*Pm-PYup(>G$t8Yg?7(F1aJ_k}^9bdXcX; znqqCE?p-T~%RnGaah)ZMdR5$x7oLBYTB$X|<8!j2cWqF5L0~U8pDvc}T`RcPMm9fN zwhkrgy{yda;X8XTNld7$4441p)LUSpwej0VqM+dZX#Y~Nw8IWqH%7)L&Jcr_$Z&>a z#`>dE#~L;@KG3j~ceYrZ`fR~3uFPORF?FzB%1$oV@vppmVFADYf0Do3KphA`00Izz z00bZa0SG_<0uX?}^Cf`y|L1GG5G@2C009U<00Izz00bZa0SG|gNd)lz|0HUt0|5v? z00Izz00bZa0SG_<0uXq<1n~ay z0Pp`#qJ}yUfB*y_009U<00Izz00bZaf#*vA@Bh!&cp+K{KmY;|fB*y_009U<00Izz zz>^5z{r^eSPzM4KfB*y_009U<00Izz00bcLd%c(JfH_ixYb=6^Z&d#?zWzPk8dE`D_JqZfbk z;%`1l>*uD9yWIbgV(Fc?3vNx*ReGYGNLE|x^)&rJ(hXZvsH7T-)1|s?Ns38jo2rs* zXO_vYR-0m_C6ZcwO?*hEY>qVQB(q6Uj-M;ILjO+|OS>#yadNzxZp(*M($vhh^DEPb z8?`ne+NhlH&5!gyRxG{!cHz4}Y0G;Zni)psjr>mp@wF;9H^p&A3-g-F&|Bh$*d+Bv zi_~{EHT)-3XZ6}O!F!5g=(bn6EnDqmZU0_}#ii|Qifn6!9^D-dp(mRbl`LDf z9V@dCJ+Vz$@uscKek3jNVat2OpzdSY)Y(+Gq<1a$oZH)tx_8eoRccB>MHWEXBi6+A z%FbqsEU{JM-8b12mN=l%Rt(2fVhGlo)Q6eWays^eh^T2Arlc5Z+#ZupZEsMtOD#)2 zpi%$hHAU9gdTrIVL@s)#rv__1{r=r%ZL8AUC3nPKQr1-e(bYzMyVb0)SxB6tF?l4I zl0!3Sr(V0aBeKTA3A;@A5@&mcDh(PUQM>9giQ4wtT5mMP+D6^$L;O^MG{tqXDb}mv z_Q--8)VHD@CtC=Y64!t?{U!g-pwfcS?EmmwiN0OP`T5H_>S#7A;n;@%=P_!l*;(Rp zv;RX+*62!hqd)obkLTw7jmmwa|AWPnbfe%h)1gg5(~sFIHq2AW>#8N~$+prCcZ#U- zp;GzRGSlu*NxnTU^A43H<-wyhHq7zl7Tj{b#5N2T`{;%-)B;=aJ&motd$ z;BjN)qmIi7?zR386ibg-tnW;8b}W{nf_`Q)e`e}vlg*8f*DpDY{1g4}9|XQNF>sc0 zY1?3}B=_ZEW?|~Ulg*6}JXuoc-|Bx~vEWd%__z*iTO#Y@)UC(IyHC?#KHdDVDZbxNlBeSi!;^33a{y$+^<*m5CdU zEnA0DN7GpXjCY0jV*U+xwf_mW4Y0HKy^&x>-W8H(vnZtDQu*tde8WYhWP=>wa7j{5 z78O|3Wa_Ashtlk*uT39yvcU;aCyNU1r~4l-mL4$c%4F;C?pPRpgMqts4h0V z1A=fM009U<00Izz00bZa0SG_<0?$BT(QEV7XV5U3ga8B}009U<00Izz00bZa0SG|g z+z8UoZUPE4IAXNe?2m zvHa(P$Xb<~n_|`j7v?pU+^;mNw<^u@mFohjH(I2=v$?rU7UrX9SnpcmhS=op`T&w* zs5ENe`qkkEm|JvrWvKaMx#LjDJ{?oUvSr(`xE9vL^~%m>i!8~CtsT=PE~cKd*U_vt zRV71LD7o2aY>JgS3G3|39gA`m6qCv}E53IsF^Hg>Uf;tTvQ5_5__k_WB3IGrseZ+* z`*)kQtx9v3+!1$4SyKhC&1$2*-D+0YQ;2gke#ZH%JN4SV9g&+AG5T)|ETnkD6}N zgTVtmI`7h+VRWdhdp}a$>7F5mU}A*58cY-a*}=46O`6o!OsWR0t~Z)uZKLiDNW9Dh z(iGRlrdY3v+rvv_F#D}&^pXvPv%{Y@TqBOfvXEbAL0J4}x%twg*9*DZ{m;z#KTMU* zg50y3zN~-xc3(JqW5X#i$X;)|rT$W}bni;Ry*82wZP_}Myt!dXJ=wG+HbQ%>b7Ag{ zZ|84hCc(H+vJEZ+#zjau@f^V={ZF$b%|fe;3(cfV{8+YG=4VSdExON66CK}7W`KM# z!F{>^sbZh(CeSl1&6{}P#=+l=*G#;Dt-itUkVp0@+ithSX02LYd1ILjZIO=A zjp|-m^)oa-1EaeutYvSH(ez`g+lF~6S%zaORBE%lJ5tJ9)sk*R*V)GHRW|97!eu;i*U>dw>X{nb)Ojv1 zY`JSVtdpZR6vs5FuAIirT@U)%mCZxa5+Am_`t-y$W$9gu4dm_ZM%}wK*k=cX7JrK# zYbtA$@>lsYX!JnuL=>Jrmcps|nm4Cj^Tyz{<5m6u;}1-5kd0g2-+8-{Jzn-}l4HxyYQq&-~Ck>bMPZ?2B!Cmc>siRg5c8Jw&sV!UW z?5M9zA9b?92~j7D3eV3QEPnqV|Fs5wf&c^{009U<00Izz00bZa0SL^h0N(#+b!5>m z2tWV=5P$##AOHafKmY;|fIuvO_y5=eKS2Nj5P$##AOHafKmY;|fB*z$RRHh*vpTZq z7X%;x0SG_<0uX=z1Rwwb2tXhf!1w=R3;YBD2tWV=5P$##AOHafKmY;|m{kG%{(n|S z7X5+%1Rwwb2tWV=5P$##AOHaf!~%H#k1g;M1Rwwb2tWV=5P$##AOHafKwwq{@cuum zBa41P00Izz00bZa0SG_<0uX=z1Y!aF`~R^8eu4l5AOHafKmY;|fB*y_009WhssMif zKdU2)en9{N5P$##AOHafKmY;|fB*zyfyMbB%oX#$lw0`Q3-{(v3cK^4c;%P0PE} zGmU+%LnTekE}XwzZHkqaNNV*p@gX^D!=zCs*^QI(Xefd!_E(FgL)I5mT+S$%^q zr5L(S6*iY7`?MFAyRym`GkbDkZl%UFI__aHFX9o)cq&>s5*}|~f(z}+SliS;D;;xD7m7UENS^Al;EOA;#4rR-U z^?_;G)U?v-yz_{!)0J(dEy*2Cw%8I(dB|`DOP70A+ps0u?noA8_No;+M4`QL{p#h* zTx?YL=9)@wHX55^CGLc6I+QEO8r;_oq+=F86C7!Ig)eMUw!Bnn?=&pvu{k|8<*E{t zm2I-dGDoYnC30!YiXG*DWA7)xsh`ZwVHYGL0B?h6bH=1H?qwdY0GM|bB(iGRlrdY3v+i@;Ul(C`-muzG- ztn`Lr$e|kP&5m>>y;Z(gdQ;(&+dJjjU`f(UuMn=m%nA#_rN5J#FCA10xmN%3od1Kr z9a~2ojcv5DV;laT$E}~0F&o>4yVL)PVrjQl=zr92D7mf;Q>CV4DQ()7B}1oD&)Mr} zR-48r6|P8-#H_p+Y?r~(9~@eyYnj{NQ(I@5WDpTcO60*UHj#*B%eG??wj!elm%h+{ zZLVb03b_ehsn3vNv()?f>NhX+my4xZt?=D>{#cP(J{p14yZM{x$BWd$q?~=k2wlS6 zA<92q@*dt|xWmZ+Fx-zO7$QcyYdH4HB)Bzh`^#v0FbjgMAy`y{jn$t6 zY-^1qy?r(y3U=CLu1>7bv|OKje0pXa8D}n|j$clxyGJ-~{siC}%TCWxX9v?Jqt=4J z-b%lA)W23Nxi37Lm~Z0k$u!uhnY{p-4tx6x2F*%jo(U!Mo5}Z0_p|+#Vu`Z%wMTx! z8~=)!*lfqYciuX~%NpM(m&oI;3Wh8i5h;Jq){hafvk2(*)K0?s^D(*-!7KkVR2iN;&v=*N{UHko2pYiCjVgC z@RLoSp%;ENOI^fZ%Ntc~e9cYkc>rg+R5IvU3&xVQRO ziluI);C4p_EHQ%&$5dEnda}vJ^+4*G#=h2}Y{a9^jTFw`&g{`h*_4L4?u=9*<q+yEU$w6g-3L*0>6!9Mtf-_1P!tmMvR{$sro| zxP0r$x)nU*4BZN92<~D3tzzjb4+{Ook(oCxQb{pb?lUdfW;t!@?rlF=_lBNzhHehk z6kOW>sbcAnb@!vG-A!a)uIiaGWOHmUCp_ZGJI7~CssCoNAGVvc?XAt=g8zRgMon>Gz$U z7lg_VHR<>7Hfvjz<}SG-?vgS)4tlXy8};p0v%-{#b2R1JU{h$PUc0v=l5#w&{MObR zO|iC7_nr`KkfbTDi%qd!6}O2u!>s7p$ zEED*ZXnKp`OiXXiznf7r+&Gi*M{#&J2M=5jT&aJZomn3xUns&eYaFj>IJS3|GaYu2 z^EOoP6=CqF)MH(0`FuSy2T%DVE(K4hL&|=zY+@btuN6z~3y&tI;0Y~CaTcCXGQat? z%l)gx(xXR(Z>;c%ctXu+j3$)J-$_r$6RMGNW=0OQ!lcJ7^4Emm7ZjJ z&R$2e+AI_7orW!VYdyaH6f(qwesdEyN*6(wmr2mSk)#pMpwv~A{>b!&9QSqalv~Vk z3R)2G`~UO(_cMqN0uX=z1Rwwb2tWV=5P$##An-H<@bCXW4Mns80SG_<0uX=z1Rwwb z2tWV=5IElg`2GL+9v?&p0SG_<0uX=z1Rwwb2tWV=5O^8_c>jMIif97@5P$##AOHaf zKmY;|fB*y_aJ~ib{(rv52hl+Q0uX=z1Rwwb2tWV=5P$##o`wM4|DT2;+JFEAAOHaf zKmY;|fB*y_009V`ZvnjjpYQQObP#|51Rwwb2tWV=5P$##AOL}3Kk9E4 zOK-hZ`1yt{?{#Q&BdTe!rmc+2`Tc5Bth7YZs@&WZNk%DBUYOTZQmePb4Y5h;jTWiz zY;G=-h56_y8TY-1OS;^p zTg?g^0OA~_Ob&mD%!8%?pcQTHB|EGCeqxGpxudR5#W zof1|Q6<0m!#5Lep)J(4vO8B-JbruA7qrX`!X?F@P_1A`Wk^;c5jzpJ7XEawdPlNei ztFMU<$=TW_jru4Lzfd`T;i)b9sDpfG)c3yHzg;Zdxl?$bP5abjz*U%pqfAH+Tw~u$ zk}w=op^|lK*|Zxi)!{7Ap$D>Z8qe}W8ZUM)32>|I!&rqJhhz;p=QM~9kyxnof-f^jFH9@SNL%;b+igESRI!5x{pvhK(o zzWnf!$O*kgq@2?e0#)E=;G?H}KuG%w9*<@!}{g`EbgZ*T&1GQ%8mLyviwb|h|T2$jo z=O1OJp>frshj0mLTn$nV;}YEa{pu6-Y|mdP)AsBOPu8>WA!q1WSVeH}_HPzT5*sro zbB_6Y%^0F@LLpTM&Q%1Rwwb2tWV=5P$##AOL|G5y1QZj0_~Y z0Rad=00Izz00bZa0SG_<0uUG@;QjOexmU*&z%2+s00Izz00bZa0SG_<0uX=z1fF{V z{Qm#BA3}5h0uX=z1Rwwb2tWV=5P$##ATUt?@Bb5tPyhlDfB*y_009U<00Izz00bcL z+za6S|G6JRbN~VnfB*y_009U<00Izz00bZ~Q2_7%6Nyj&0uX=z1Rwwb2tWV=5P$## zAn@D^;J^R(+z%l-009U<00Izz00bZa0SG_<0uY!efZzX5BtiiQKmY;|fB*y_009U< z00Izzz;iEv_y6a92+;uuKmY;|fB*y_009U<00Izzz(fK3^ZyfxPyhlDfB*y_009U< z00Izz00bcL+za6M|Ihspq5}|s00bZa0SG_<0uX=z1Rwx`i2`{4pGbrP5P$##AOHaf zKmY;|fB*y_0Dp_s#uQ;kOHK=Kn_i6N`I`^A~Tu{GFG-_42nSHufPFxZi(guB259 zIZapTiFMS`Y%0l)ZTNqdthUzcY5IY*=UAFfElaZKkwbNbTGGmxn|a60^>>RUQ7E`S z;y0z8#EmJk#p)|2m2Ij@vK=+#-^g3lrdVl-q*h-OAChquNuy5q%A_1OE4Z)r9~Mhn zEQV_tF<7>2J5eZnQ+abj9DL=pSOz7QNiwF7^&b>V_gGBTjF=S1vW+e^L!hCkjwVDk zTsyIBeP*)o;|KsZ;2aXlhhk6Qs3F!TqXcSm=+d(`xntLb#8bWBZ4GxR8eAkMhdV0tF+lQnU@va{JDOFgQq ztfeImWn2Y=)!<8;wAYcnOyOJej^T>fJC)LJ$hP0%R&7hhL<(c@850KwkpkC za!1@HWli-RtBv}0t65>wfH+6PX=o(MoqFxwj!4SGH~gl;o5A$)udO$lVr`@DJ+how zSpsQ_>ta)^SHtqSZtQ~bryur z_IKt=4PoMD;HPQn%FseIKHG1dq5A4jb^Wvb?K4!5cOO5Re0Tm2a`XO1>Mr%~6-&Es z6L_v>>d`K`$_nTsfKq=`mpKzoqO<$tYMdh4yi&o_p)B(8<5q1n&aq`1nYoV{Cx z1>nbUK$aOUbCEjp9|ZuGxUEKwHvqiI5qn)5cnXtG6Dqdw-3&k}r8 z-#=$0&(zVKsAW=)u6d<}XZ8Z|^&jegzF4YO3*UN^Uvbg%qnO4)*y$^8w2?8ZFDh)G z_TuHk&G9G%-LN%fXtGDiBxChP?fd@TIgeYpies8oxB2s4yu2>+D=W@|=?A26MLppG zN;!-VP*L2`NU(K~jJ0}8tlse^eDdN=vGqU{>*O-2)Yr(HZ~FNo1aA!D<>rfx zoS?ii?8PQdn#&|=$)B}e%HqyPaZ&Dc6b)`9}qMi0|5v?00Izz00bZa0SG_<0ucBR1@Qa-4-p@ah5!U0009U< z00Izz00bZa0SJ6R0(k%bfS~ah2tWV=5P$##AOHafKmY;|fWU_+fcO6o5g(6+00bZa z0SG_<0uX=z1Rwwb2z)>Sc>n)^pz#<8KmY;|fB*y_009U<00Izzz=tS+_x}$OACHCr z1Rwwb2tWV=5P$##AOHafd_V$t|NnrX@fZj|00Izz00bZa0SG_<0uX?}hbVye{|^x# zkA?sQAOHafKmY;|fB*y_009VmKmv>2b6)*`9)`z200Izz00bZa0SG_<0uX=z1R(IC z2;les9|}7j3IPZ}00Izz00bZa0SG_<0ucB>1@Qj=fpX(v5P$##AOHafKmY;|fB*y_ z0D%uh0Pp`F3OgPO0SG_<0uX=z1Rwwb2tWV=5cog^@bCYBpxk&E1Rwwb2tWV=5P$## zAOHafK;T0W!0-P*6m~om0uX=z1Rwwb2tWV=5P$##An<_-EMEHY+(O|yx%oes|8p1q z{)HD`{OuP%_QG1>JFiqP8TtS0mE}u+?~-%LNrvRE_uIu1-6*(+ny%6l?L@NLTCb<+ z2a+vYhmxirQ{6VqQ>mlrht}Yttk~Ky9a}K}UbQJ!S|X{{*Tje9EbWp;os4apln0@y z%S5xJK`?@Qw|_9`$yd+N6U%T+WkOH-PtcP=yJzW1SGJWlRcB~GuJmcK^oUKZtuqXW zrj8x@{GWb;!O+y{2SRY~_0?kOh=uJ;7k0ct_O%X`CUxMeXY0U7>r-@Pq>kXe*;k4s znRRMsx=wkEovM;-j~|VnJ6mU>R;TDhR91NZGyT0{X=9`C?R&Po*BQTB$H)7XAl_Ex z=B79)$t=vXiBqe$#0{}Y>Wvnu?`&=^lZE*p`=s6*u}>}Kbxtyk4kh<1&FZa6vwUS$ z;GQ8XEG=15*HE*|M9GibY&15-N}a5U>y@3&7O_o-a?K4MNM*~=qeou9DtNsK5|8v) zHfh^%EN=>Dl^LWpNl8W(G^43(pU~`6iDfb6P_k^GdHP zy2MS{j-JNp+-=sjD$QMTN8BZ4P4z=vZ#2c)M%}v>ZZ`sHitA!itXIWte)3qU)kfw* zdINm1^rl97$2H~kcu;S_%U^P_bikJS=su`8mTh!Boo>%CZ8ifRThgAl@dV=)t)8@! z`Jc^P?P;#@jLV6_d(-7c!Eu(_?F&-x@gTv}9dv)VEvB3d{J! zIhwGjI)>us7P3>X-P;l4wYto5dN@Ou$zUpuYz5&A=kjmn((+5w^prk28spncZ)J3R zrfFqCU@w7d>_k{iI}z?VmZp2B4~rf-RA&c~k{b9K0uX=z1Rwwb2tWV=5P$##ATXN( z`2GKEjw^Zv0SG_<0uX=z1Rwwb2tWV=5J(E({XeOJpCJGN2tWV=5P$##AOHafKmY=> zDS-F?*&J8&3IY&-00bZa0SG_<0uX=z1R#(U!25qv13yCm0uX=z1Rwwb2tWV=5P$## zW>Wy~|Fb!+=oJJY009U<00Izz00bZa0SG`KDS-F?qy~P500bZa0SG_<0uX=z1Rwwb z2+XDc-v4KFT+u5CKmY;|fB*y_009U<00IzzKvH1Q`@^frEBF}#5P$##AOHafKmY;| zfB*y_0D)N(!0-QOZA8%@2tWV=5P$##AOHafKmY;|fWW8#-v38Ua0LPofB*y_009U< z00Izz00bZ~YXXale-~1IL^lfVA=eRas@Sr1C~5jJ)osH(l{%V!XbmpPime^f zh(E1h{=Li*NGqOfmm7w(!lXR7sxA}Fk_N#%hjZvozgsLBYz`fb(5I|YQ|roX6jVcT zx@<(oPycUa;!o8wHv%Iy*vcIZMridrbEShyA?J6-I_hXPm1M^@{6CLNK&#P28hKRy z8?FA~6E?dtrrGzuWA@)ImMWFPuXb&DuM^MZkr2kT^7TNuRk^t-j!kt7^P0+%XG`1= zo21@ok^0W&<}z8BkMb}}%;bKhS-n+hmaktGxI$6hNo^u!FjC9Kk2<8M(X&=o-{2o+ z8IH*|2*XsV$yPtxKEl?#cIx<6 zn~h4#E3&WAjw;1>q<1YtC%3m7b?AK?L0h&RD{7Q=kgSR8m7UENS?W=?f9eNI+&Fpdbu`5u zirS(bs@PN|Hye#ju~Ls(VbM{pfjx(Homv*_ynaAUHnO@MJ)g~rfnIb=I%b?{ zj6tHd#0aQuOMS>@#6v=v`>hxI0*>QqBFB{F#l{Qrlsmim(mAkUd zN(}MEx7ipP9mgA+DAb_GX=T`u%ihFli4Xm07niYR^MKleEr(xr9&lVPh*pwqvc^t7 zt=g8z7w`i*X0vPWl;z{(I*A*J$_%x_bS;+2)nJ?DYAY;sHer$v=H`jh^Nw!W_wP1q zTb1T6xg+k9vZng;rrM})x0)4}gotxAE*-~tg4yiUYxj0UQchkxTXRA3@^VhtSd`C} zN!%_gFx>F|;kY>CozOoIlJ!PYtZmf2PN!{9?5q%;8wJu7*Ttq-uZr6vX*+Dz^5l}0 zyrEA%W4h)BrToVH?j>7DnI!&1;^K2Gw#cJVOjaMBL0q+H+wzV|gZc}Cd$+F*PJ3S+ zIdY^Ov{-iNuuXi5)85xI4;+))<<1&ug<0RDGpHYrKP=I?kG=7fQckd0Cv4B>|JBSdDyG!oTjxHgm{NN11X2!adEe|zek1Z>|7Y1ZBJUOY`Dr>9eCIg) zz~vM@`wM63*--P-b}g(n+_!4~%YzS+(viOT-#3lFe?9nEw108vyQ66Z^S_+gskGvQ z4+{t1V{X*r58b8}CT0Js*OfsHp}*KaEta|)h5q34^vRC~r?ns%?3>t9hkd`Aea@48 z;5!Yby@9?icd0-g++tq=4mwP3 zkR`7ROQcd?BSCRe+m1fG-2eXmi4XGLV9rhl5{ES&R%iD10Rzj3zt9ydFMLtI$sm-@%WlEY^DAj?iSu%W^< zv;EIK`QY-8nWAI`T1q51H_d{k~N!ZEO^Nv1ZGA9Xd9gu{ZPI z4PtFoZf>#+*VcMH@5|R|V@Apg^YO>)qjcwe?mX-Q`)ItlAvU>t;iv@nyyEc;8kG00 z#c77zuQaQ-D$Vlss{+>&J<%-Ni|$zNIFz)+hb^zBrYi>fg7om^sI+A`rb3gga<$TL zN44p(rczy@(z}+SliS;kI#)aWcCeX-9l5e9kTr3=va{I=_l|m_<>y4NF_T(G=a{NP z{faL8-+Ctrzvzx^leJ1qY}K~Js3FHoxspj`FW%57TzFD&771I6!dl^^6VK=F-)+{mD$QMTN8F9RNMCK#w_D8$>jqH{rLi+j3jC_K#OfV(G_+;gu~^8Y zJlJ`c$x=wL#C}#atE*WSRhI<8V_0uA#o9*QdwO_Une@qfZ}F{(n_^2O)yj6YvgUgx z8wyhfX^QLYFi@|G+e6F6D`ENFO|-Tx#^ao9E{tFD2bT-a`y~0GodtoN@xM?ky~Doi zUK`mmN5AXdGbG*V?y>6OIvy#L|HZlf&&~O-4)3q`f2LTvcdzhmhtDFJr}U`V%o6!u zNzW&l6~-i$=#3zntjR?aAF9LK-q8DR6Ow(}i`Toi_>vW6#WqYSPGnxSJ-Tn0RI+rr zXSEHRU+eO|%|1P!eotx3`T?uxbi1;78rS2VXwoBxTDJGhFe9+k<~?`PIy=KU$`T%6 z1S=`QJMh6z%f&c^{009U<00Izz00bZa0SF`n@cy5`z>g4s z00bZa0SG_<0uX=z1Rwx`85O|$|BMbSx&;9UKmY;|fB*y_009U<00Iz52;lucfq@?( z009U<00Izz00bZa0SG_<0y8SG==JN>8SNap1px>^00Izz00bZa0SG_<0uX?JFM!|w zVBm&J4f9ko4afGbm`;aE zilM8Ttr@x{txR7w|JT3q3|vaqWWv%dSz#`MOL_$EWc@bmPh@-#k6(QN^aJbS!rqD!pqNI=Q{wsQZo6BZuk=je3z(xZA94Rhqlxj<`$8 zn(9BT+Nf{0niYmdoTIbM8!LR$PQ7+-MJ6AKaeHWTVnMNDVLMb zH^@@Lbcs~zYb0^OL#}N{L*U;YR`%|*$smwMlMJ_=D4W?ftDD(wFwq3R!|RQvSlg(3 z$RUY9n&P_H6zf%Sd(wQiqLE29#CJBmy+oNoBMUTHY1Gr~GM>&9qs$it zFF5bLaMrY$(SB;$%qW}xEAQ{VSMby3w|^!pZD!OxgZE#alr}RSF*a@Ll5Rwa==xPY z5v35P=AB>w2G5s{scEr!mR{19ZO4ip=w-ez4KK-$WwvE`J6KO%iWa+{^lbTnrdJB< zJT}ZjYVy@&UGAJ(8k^_Qrs3}u)N(p@oL0F1iqbHUDfC~Sq8padrd>H)OH*{`FP)(~>5Wh7)=;hC?%n8rm8C#7O3D=7vt{dWicbC7 z89J40a#C0PvO^vC#wYqeS1eU3h40+qbNI*zkC{||F+E3*G%+S82eBm+O*EmB7e|I8 zyvgMtP479jWa)CxY8$rHmaTS_NJrB>SC&6_j!E3XB?EHj!z$=FMe?AWWRgR@H7?Ql))oem}T@J1rrau!aHwaRB>?*4?d%#OF&BQIG4 zpx|^H{Haza<)x5knJk5gN>0SG_<0uX=z1Rwwb2tWV=5Xch1`+t@Uu0sF<5P$##AOHafKmY;|fB*z$ zM*#2tvon_H2?QVj0SG_<0uX=z1Rwwb2tXi90RR2JEE!yf00bZa0SG_<0uX=z1Rwwb z2+WQEe*Zr^V~L(X00Izz00bZa0SG_<0uX=z1hNG1{+}g->kxnd1Rwwb2tWV=5P$## zAOL~c5x_tHKRaWIolMIX{f^f4*=+$2byI4Sy~Z~DG(TI65o?DHsQ-P{@0cNx$<=Jtt-!5c_ynRzRwXDZ`nUm z=8kqtV@XkEdaj&{#<4OQDe95fw+vGoQe89@lZuK=RZ}@ssBQ#b241312Ni{0;N1(_x z^736?;K`v*m7`-*d?4xcShEagxsc`_Y4=(!Qg3e%e~{#}XBftvTt*{Q>m{;XWX1gMyRc%Wp8Sp=)>BtY z?n>%(Q&-a$H|@)1uGcI5%FuN7(L5_+o;t~sK6g}5~Csz1eUpsr++4R&62n>&0WR?sS| z{GQOz`k&dLQX3!HeKj{#|nnH!g-Qo$XmaXN6;ykwc0`#J4^$cQOkPe~>jb&FqRm$7?g zPLfJr`AAl>%4nPZl<__LsWLZYx3}Tclx5%Eg2f}5VbsjZ#XriNrOY;B^nkvf`P`cN7u zud>W^CJij7f+?AnQIqYfE8K(K+(nt`7+Z{)b&7xR+OzhPWo~!3^d&yI2s7Kv!TPoI z(=s#UjI+|eUk5omk%lL1GmpIld02~`W8s;yww4I2OAox+2rJ*Zb}e~2P0m|(O>aKK za_3AAPN+5Z5}<2mRGxS|9ZLEM>GJox&KVVLhj;HZYINFrU7^lyCnWyDkU2v>hySJ# zy!EV;i7Cik-cv_m@ctA(xYAdcca&9X`0xL7-r`XV0SG_<0uX=z1Rwwb2tWV=5O@p( z@bCXW29t;(KmY;|fB*y_009U<00Izz00eRb@cy3zgklIl00Izz00bZa0SG_<0uX?} zV<3R{|HohwF$4%e00Izz00bZa0SG_<0uX>ejsX7q{~RC`LjVF0fB*y_009U<00Izz z00bTb0sQ{|7)&CD009U<00Izz00bZa0SG_<0uaa%!25p=5Q-rH0SG_<0uX=z1Rwwb z2tWV=kAVQ*{~v=%#1J3=0SG_<0uX=z1Rwwb2tWV=IRbe9&jCU)1Rwwb2tWV=5P$## zAOHafK;SVDz~BG(7)&CD009U<00Izz00bZa0SG_<0uaa%!0-P#Kq!U)1Rwwb2tWV= z5P$##AOHafJO%>J@Bf#JuNSTqDqpKSvAT8n^_Blz`L*Kf#ZMG=o#9<>f9>>pDj`a;(RG^cX$8x4W4cX`rm zZ}9iYqR~mGO>&+Xeh<#0tJ@dx%UQ<&tEhB96+>IL9;5X~NR+p?x_@rANp6Sexwn9Kj85 zh56zAPwoSv^~D}xsmiHE#c+b1$4bKk<;c=3!}-t;X2qCiAQNZSk+{HTx&a+^t)s*R-^x>eiab zq+ZLvoRvP^Dx~@ja^^^5Of07cNhh%do$%rbeHd={>wbdk=j`2u_oh1#G3-pnP7KQ3 z4HI7w(F$bQCo!E9rcuSLrCOGAFYBi~0RGCF3N&`+q)v_u~O` zdhb@9?EJ^<_m#OG>-=Zu?7Sjpv;WzG{bna^{8Baz?svH+*gv+y(HC+v!(@b5dYCLK z{^^%~$^OwY_reRMH{X-Y5tCK32mB}L*Z z?q(OL(SRN1v8zEMo_7~F*adtjiDxYT&bZ`xb)$Wp6;n~qsA_8ZLvbXrfb7OU(zQcn zklBf-L2##vg?2`vs3VJAq>gF-#IO=K!o*TIE?`6DxgI$f#m^xM+P(Z;14`nJw}j z5Zgd`k)7S*g{#!?`~QOfd;`@X009U<00Izz00bZa0SG_<0!t`>_x~lFG;|pP5P$## zAOHafKmY;|fB*y_u%H0m{}%*9bqGKJ0uX=z1Rwwb2tWV=5P-lE3gGYmU&2X4mmvTF z2tWV=5P$##AOHafKmY;@3gGwu1;J1q0uX=z1Rwwb2tWV=5P$##Ah3i2`2BwgCk1;J1q0uX=z1Rwwb2tWV=5P$##Ah3i2S1+)AG{rBZ-m)>9cOmR?nv+xu*UvZD15>G#0qEZlnRO}({tl= zpqNyYEK_qoi^j1s8Y$|L*tZN*8&aKpBgxtWaVVMnV`_-k^J)~oJ^sA?(K6TXl^#9i z235|p!w#eaI-s)H*QsPuIWxFU4Q*hVil!RHe`*MPy~~qkdxO7E7KlzdZ8FajNOdTw zmNbYE6nUNaT@)p=Hg4IZ%qhLnnC6Z!)^pJ?CDStI=|b@z=N{zr1Lhy6*P+_@zWtFh zcgn_NEi|5pWUev&!-d8aJ!JlIMQv*1d-hM2Iccu3c^nHZ#=oC?Ov&K$kHu@3Sbx9# z^Y(|zT(4L9RmqeN26P_%dFmAZ)*nr`ey7FHxmPNyip=(6m*3(A((ZIgyVq*1lgese zQe{PE+gi-1ps1#Fl35z9Yw?Wg2HX1NrMl3#TNkR&-KZs=Ge!)6we63n4O_IMMhuKDcNjw>Rson=@b%g5ahjshcO(dSx_LEWP>HS zZgYosExr86l27<`Vhq;EftEAN?+MMFy0A~S`F&DVg*ux$(m%;g(LQeD zF5lQDRsU17O{!~_s+?L>4Ci@movca21LerlEW`O=sh+6pd^nU8mg(1O?z4OC=5CKC z)vzsNa0@m&0^i(fI~`3H5`o|31-{+j_o9WVYNo>GHH>1ogLC%Q2H)b@8PTZkHR>BK zVLWoU@@lifdbQ?_Ik7y_BL~N-7u1=Bc(4gzpK1hSaoky;~o2hWp21#8V{$=8BLejZ6ojr?;G^o)TO?2@Us;X z=CJh2#lOi+#_0{jMD#>TPH#Y}i59i-uKfXTK+^|jdW2|%x)w{^>6MG$Sad+4pA&tq z0fjA`JC4(;Rwxud%AIcKu8j0P$8Lz}6^dUk6yDP-bKBdcH;c*RE4@MLtdIBYkC(ZV zPU+F5jHRRdLW)j19oJE2fWiaRnv#kKzWrNpDCr` z<>A!QOiH@^efN0pYwDqQt6=w?9bRZQs<+n3P4^57o3ML}!bUEWJDpC8uREvGX1&+y zl0#`=(1clZV@*Hc(+=?X(UF*yMADyF8&So14>o@~X9abt%o{FP3bW$5b<)pBe<{Qk zN_rswY7o>5j=gcu{^>HOvDbmqsk{-ULjRpNc8H1LjUnWmQM>rhnaN{DtLPbt#66=0 zJIaGAbPa$1-xB^q8*~{05P$##AOHafKmY;|fB*y_u%H0`{r?5QP#ppgfB*y_009U< z00Izz00bbggaUZ~U&2X4mmvTF2tWV=5P$##AOHafKmY;@3gG>JK`>N@00bZa0SG_< z0uX=z1Rwwb2rQuh-v5_y($HlHKmY;|fB*y_009U<00Izzz=8sJ|6dRc)gb@@2tWV= z5P$##AOHafKmYC7d*L83GW100bZa0SG_<0uX=z1R$`W0RI2~EeM9{5P$## zAOHafKmY;|fB*y_0D&bG!0-P{IBDoI1Rwwb2tWV=5P$##AOHafKwv=u{Qkcn7^*`6 z0uX=z1Rwwb2tWV=5P$##mQVn{|1aUBq010}00bZa0SG_<0uX=z1Rwx`1qH5Feppy3 zNrk6AcKK5Iw^rU-DX|Y2eDsABPZ4S}zBdD3e)cY8c(wm10u zWWLCx(^!2V>J z`y3l?EqA!bRC2~Y&w#(X=z!y~FEHd;BW0s}{lj*x%r%>(uRLc;2Ln1AbarX+Eq`p? z`kfY^J2#b8MP?J;<+petR9`2R)x@Nw*6`;sD03PG<0LQDg~r{wP<`%pEfFf-BPM2lYN;1g?+a%rQ4xb2nPiXGcg?+Nk?~^K9 z%ubs|r@hw|>dck&PqH_tkI=ZwH?~Q2(x%xa)itT#ry~ZjwocainyzaHnlAaDRZ3+; z)ajW*A2{U)1Fe7JRUImZ!DQBIZg)020^i(fJ6%j}#u^d$O}6#g4SsKOsYDCFaL45= z`whOuvpmtL?=|Whyfe~xXn#S>3hGpuH(aooX2tV1d*~kTO~w++jTT>WURNu%F>hDP z9Nj66`)(Ri&Z9}~TZX9(S>iE{C0TnQ4kfdHObs#kKHRRs7ZVkW|LSj8FYPW8I+2Mo z!jo!Pz!v9t*Ip}g8XL&z+yimaHkOHNSEu0B(_I8ik{F@??j9z;#%O`~B1)`8S?A5;jEU7_&A%`$h=DLuM0l_R_> zX6#Tl#OR!ux_Yt8>a%4|Y-C?ny&Ufz$hr4buU7E~{?5s{tY$<`8zINYdO2DzNXsiWvTO?pK2AdAKtvV7!T9;2@gG;Kg7mE7rcT71176@+(J=d18am@&M(RG60P;&-G3 zV0w1&CM2quo_5Cj_Q&6yoDsglCGKIxZ~Dt+`jX^zaAr!%+yU`cQ(HgW2l)N}V*k(r ztsnpa2tWV=5P$##AOHafKmY>EB!Kt-WtuJY6#@`|00bZa0SG_<0uX=z1R!uR0sQ@c z7jr`^2tWV=5P$##AOHafKmY;|fWR^d;P?M!nl1Dd0uX=z1Rwwb2tWV=5P$##AaF4O zy#HU!4Xq#m0SG_<0uX=z1Rwwb2tWV=%Orq*|9_cg3w?zE1Rwwb2tWV=5P$##AOHaf zTucDJ|6j}vtsnpa2tWV=5P$##AOHafKmY>EB!Kt-WtuJY6#@`|00bZa0SG_<0uX=z z1R!uR0lfcT%nhv|009U<00Izz00bZa0SG_<0?Q=e{P+Lm@_!Vb`oMdix$^1C-l}~0 zH`qt~9|Rx(0SG_<0?Q{b{yFzTKkJ@<4{@F4|*$7VO zAAwB!%1|22cv|t_79WHkb>VUN?P}u_`&oA~9=+fW#X6li83RS7-i*u|#}E8*^xDnc zUN9$fN6sA!n*v?xn~J82&cwKVa{ds^RgJuSmlyb;fHe0=yVE7@UaK`eus>Di`i;_~ z+C0NOrc$^bXASuK7Z`9n_M$_cHBvUp*HnAG%rzRNHzZR!7|I5!Q06oWhDTni3yr&Vq59nIS|Vz+7fF}D-*wt} zUj^Ht-P_@XW}|xJ<~n)47L_ZiNsp)=f0*A;GAY?$86>KEplJgtspL+l)8gyxsNfYt zQ^|{a9rr8eiH5fngQ$tF_I1ia%c5ku;k(TpK2d&8XztX7eX`B(ld2-SeckK`d~>Vq zd{<2X)`-AwvZdW_@OzUJ5>+(ZK+c-l;9ERPijDeSqrTw|EgssJpB2=pGHv#bj&v%G`dll$plD7NR?BuOn&4PFS({z4>-^*dP`;b3=!f zNpfZvPGg@ebDv|w%}Qh8bHsR_N!{&X)#7&-9dJDM1%@20nCXPg(indKU%ty7dJF*w XKmY;|fB*y_009U<00IzLRN#LB9kx&+ delta 439 zcmZp8P|~nKYJ!vyLm&eKLnaWzK)^&DBL|?UUYjN>P>hxTIY=gf|2O|P{*U}`_@8rK zMVa)F0w3Rsb(}|c**c`vS5Mt#+MO%(+_N8WSQ=| zo^cV#EdQY9H~j5y_!)tiY5N;~W~&D*Aj79?ePF&lF@R+{>qqAA+deTfzSHHt$H2oZ zz`#A3>oL13+X^-V);X*)EPX73%#F+fJg1oU^Vl${GEQgs#SqTSG2L*3pw{$=2P^^8 zvp%uD-~Qquiw5KL#y2dU96)n8KvrxQc+7H{efp1AEWi1I+&ALp=8S#JC5cHnsnZQ! zvxrVt`NV9++{hg={q;i@)#=i2Skl^0yJ6(ovpREmE#VPH;U+PGP;pp$9)kFTtE8Mn**U@c{4bB|{ek2am$$RaU) z!*^zu>EFMzs)O7Eant1Athp@PB|ot`Fhbmn;(+yxT$>pM{>v{?5Ll$(044 None: + """创建库存配置主数据和受控路由规则表。""" + op.create_table( + 'shipping_rpa_profiles', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('profile_code', sa.String(length=64), nullable=False), + sa.Column('display_name', sa.String(length=128), nullable=False), + sa.Column('connector_type', sa.String(length=32), nullable=False), + sa.Column('login_url', sa.String(length=500), nullable=False), + sa.Column('username_ciphertext', sa.Text(), nullable=True), + sa.Column('password_ciphertext', sa.Text(), nullable=True), + # 后续 8a9b0c1d2e3f 将该历史列重命名为 login_config_json。 + sa.Column('operation_config_json', sa.JSON(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('config_version', sa.Integer(), nullable=False, server_default=sa.text('1')), + sa.Column('credential_updated_at', sa.DateTime(), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'), + sa.CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'), + ) + op.create_table( + 'shipping_inventory_sources', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('display_name', sa.String(length=128), nullable=False), + sa.Column('connector_type', sa.String(length=32), nullable=False), + sa.Column('rpa_profile_id', sa.Integer(), sa.ForeignKey('shipping_rpa_profiles.id'), nullable=False), + sa.Column('warehouse_resolution_mode', sa.String(length=32), nullable=False), + sa.Column('fixed_warehouse_id', sa.String(length=64), nullable=True), + sa.Column('snapshot_ttl_seconds', sa.Integer(), nullable=False, server_default=sa.text('86400')), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('config_version', sa.Integer(), nullable=False, server_default=sa.text('1')), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'), + sa.CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'), + sa.CheckConstraint( + "(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) " + "OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)", + name='ck_shipping_inventory_sources_warehouse_mode', + ), + ) + op.create_index('ix_shipping_inventory_sources_rpa_profile_id', 'shipping_inventory_sources', ['rpa_profile_id']) + op.create_table( + 'shipping_inventory_routing_rules', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('rule_code', sa.String(length=64), nullable=False), + sa.Column('rule_name', sa.String(length=128), nullable=False), + sa.Column('scope', sa.String(length=16), nullable=False), + sa.Column('priority', sa.Integer(), nullable=False, server_default=sa.text('0')), + sa.Column('match_mode', sa.String(length=16), nullable=False, server_default=sa.text("'all'")), + sa.Column('status', sa.String(length=16), nullable=False, server_default=sa.text("'draft'")), + sa.Column('action_type', sa.String(length=64), nullable=False), + sa.Column('action_payload_json', sa.JSON(), nullable=False), + sa.Column('version', sa.Integer(), nullable=False, server_default=sa.text('1')), + sa.Column('effective_from', sa.DateTime(), nullable=True), + sa.Column('effective_to', sa.DateTime(), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'), + sa.CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'), + sa.CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'), + sa.CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'), + ) + op.create_table( + 'shipping_inventory_routing_rule_conditions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('rule_id', sa.Integer(), sa.ForeignKey('shipping_inventory_routing_rules.id'), nullable=False), + sa.Column('condition_group', sa.Integer(), nullable=False, server_default=sa.text('1')), + sa.Column('fact_path', sa.String(length=128), nullable=False), + sa.Column('operator', sa.String(length=32), nullable=False), + sa.Column('expected_value_json', sa.JSON(), nullable=True), + sa.Column('sequence', sa.Integer(), nullable=False), + sa.UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'), + ) + op.create_index('ix_shipping_inventory_routing_rule_conditions_rule_id', 'shipping_inventory_routing_rule_conditions', ['rule_id']) + op.create_table( + 'shipping_inventory_routing_rule_versions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('rule_id', sa.Integer(), sa.ForeignKey('shipping_inventory_routing_rules.id'), nullable=False), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('definition_json', sa.JSON(), nullable=False), + sa.Column('published_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('published_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'), + ) + op.create_index('ix_shipping_inventory_routing_rule_versions_rule_id', 'shipping_inventory_routing_rule_versions', ['rule_id']) + op.create_table( + 'shipping_inventory_external_mappings', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('inventory_source_id', sa.Integer(), sa.ForeignKey('shipping_inventory_sources.id'), nullable=False), + sa.Column('freight_warehouse_id', sa.String(length=64), nullable=True), + sa.Column('external_system_code', sa.String(length=32), nullable=False), + sa.Column('external_organization_code', sa.String(length=64), nullable=True), + sa.Column('external_site_code', sa.String(length=64), nullable=True), + sa.Column('external_warehouse_code', sa.String(length=64), nullable=False), + sa.Column('external_warehouse_name', sa.String(length=128), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('version', sa.Integer(), nullable=False, server_default=sa.text('1')), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + ) + op.create_index('ix_shipping_inventory_external_mappings_inventory_source_id', 'shipping_inventory_external_mappings', ['inventory_source_id']) + op.create_index( + 'uq_shipping_inventory_external_mappings_source_default_enabled', + 'shipping_inventory_external_mappings', + ['inventory_source_id'], + unique=True, + postgresql_where=sa.text('freight_warehouse_id IS NULL AND enabled = true'), + sqlite_where=sa.text('freight_warehouse_id IS NULL AND enabled = 1'), + ) + op.create_index( + 'uq_shipping_inventory_external_mappings_source_warehouse_enabled', + 'shipping_inventory_external_mappings', + ['inventory_source_id', 'freight_warehouse_id'], + unique=True, + postgresql_where=sa.text('freight_warehouse_id IS NOT NULL AND enabled = true'), + sqlite_where=sa.text('freight_warehouse_id IS NOT NULL AND enabled = 1'), + ) + + +def downgrade() -> None: + """删除阶段一新增表及索引。""" + op.drop_table('shipping_inventory_external_mappings') + op.drop_table('shipping_inventory_routing_rule_versions') + op.drop_table('shipping_inventory_routing_rule_conditions') + op.drop_table('shipping_inventory_routing_rules') + op.drop_table('shipping_inventory_sources') + op.drop_table('shipping_rpa_profiles') diff --git a/backend/migrations/versions/3c4d5e6f7a8b_remove_shipping_inventory_site_id.py b/backend/migrations/versions/3c4d5e6f7a8b_remove_shipping_inventory_site_id.py new file mode 100644 index 00000000..37a7bedf --- /dev/null +++ b/backend/migrations/versions/3c4d5e6f7a8b_remove_shipping_inventory_site_id.py @@ -0,0 +1,79 @@ +"""Remove obsolete site_id from the shipping inventory identity. + +Revision ID: 3c4d5e6f7a8b +Revises: 2b3c4d5e6f7a +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '3c4d5e6f7a8b' +down_revision = '2b3c4d5e6f7a' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Replace legacy source/site/warehouse identity with source/warehouse identity.""" + with op.batch_alter_table('shipping_task_inventory_links') as batch_op: + batch_op.drop_index('ix_shipping_task_inventory_links_task_source') + batch_op.drop_column('matched_site_id') + batch_op.create_index( + 'ix_shipping_task_inventory_links_task_source', + ['task_id', 'matched_source_code'], + unique=False, + ) + + # The partial ready-identity index was introduced by a later branch. + # Existing databases at this revision only have the legacy identity index. + op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_inventory_files_rpa_identity_ready')) + + with op.batch_alter_table('shipping_inventory_files') as batch_op: + batch_op.drop_index('ix_shipping_inventory_files_source_site_wh') + batch_op.drop_index('ix_shipping_inventory_files_site_id') + batch_op.drop_column('site_id') + batch_op.create_index( + 'ix_shipping_inventory_files_source_warehouse', + ['source_code', 'warehouse_id'], + unique=False, + ) + batch_op.create_index( + 'uq_shipping_inventory_files_rpa_identity_ready', + ['rpa_run_no', 'source_code', 'warehouse_id'], + unique=True, + postgresql_where="snapshot_status = 'ready' AND rpa_run_no IS NOT NULL AND source_code IS NOT NULL AND warehouse_id IS NOT NULL", + sqlite_where="snapshot_status = 'ready' AND rpa_run_no IS NOT NULL AND source_code IS NOT NULL AND warehouse_id IS NOT NULL", + ) + + with op.batch_alter_table('shipping_tasks') as batch_op: + batch_op.drop_index('ix_shipping_tasks_inventory_site_id') + batch_op.drop_column('inventory_site_id') + + +def downgrade() -> None: + """Restore the legacy columns for migration rollback only.""" + import sqlalchemy as sa + + with op.batch_alter_table('shipping_tasks') as batch_op: + batch_op.add_column(sa.Column('inventory_site_id', sa.String(length=64), nullable=True)) + batch_op.create_index('ix_shipping_tasks_inventory_site_id', ['inventory_site_id'], unique=False) + + with op.batch_alter_table('shipping_inventory_files') as batch_op: + batch_op.drop_index('uq_shipping_inventory_files_rpa_identity_ready') + batch_op.drop_index('ix_shipping_inventory_files_source_warehouse') + batch_op.add_column(sa.Column('site_id', sa.String(length=64), nullable=True)) + batch_op.create_index('ix_shipping_inventory_files_site_id', ['site_id'], unique=False) + batch_op.create_index('ix_shipping_inventory_files_source_site_wh', ['source_code', 'site_id', 'warehouse_id'], unique=False) + batch_op.create_index( + 'uq_shipping_inventory_files_rpa_identity_ready', + ['rpa_run_no', 'source_code', 'site_id', 'warehouse_id'], + unique=True, + postgresql_where="snapshot_status = 'ready' AND rpa_run_no IS NOT NULL AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL", + sqlite_where="snapshot_status = 'ready' AND rpa_run_no IS NOT NULL AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL", + ) + + with op.batch_alter_table('shipping_task_inventory_links') as batch_op: + batch_op.drop_index('ix_shipping_task_inventory_links_task_source') + batch_op.add_column(sa.Column('matched_site_id', sa.String(length=64), nullable=True)) + batch_op.create_index('ix_shipping_task_inventory_links_task_source', ['task_id', 'matched_source_code', 'matched_site_id'], unique=False) diff --git a/backend/migrations/versions/4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency.py b/backend/migrations/versions/4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency.py new file mode 100644 index 00000000..43681f1a --- /dev/null +++ b/backend/migrations/versions/4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency.py @@ -0,0 +1,38 @@ +"""Add dynamic inventory snapshot callback idempotency. + +Revision ID: 4c5d6e7f8a9 +Revises: 3c4d5e6f7a8b +Create Date: 2026-07-16 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '4c5d6e7f8a9' +down_revision = '3c4d5e6f7a8b' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Make a multi-Warehouse source file idempotent for one RPA run.""" + op.create_index( + 'uq_shipping_inventory_files_rpa_dynamic_source_ready', + 'shipping_inventory_files', + ['rpa_run_no', 'source_code'], + unique=True, + postgresql_where=sa.text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NULL" + ), + sqlite_where=sa.text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NULL" + ), + ) + + +def downgrade() -> None: + """Remove the dynamic-source callback idempotency index.""" + op.drop_index('uq_shipping_inventory_files_rpa_dynamic_source_ready', table_name='shipping_inventory_files') diff --git a/backend/migrations/versions/5d6e7f8a9b0c_shipping_customer_lifecycle_foundation.py b/backend/migrations/versions/5d6e7f8a9b0c_shipping_customer_lifecycle_foundation.py new file mode 100644 index 00000000..8512e5dd --- /dev/null +++ b/backend/migrations/versions/5d6e7f8a9b0c_shipping_customer_lifecycle_foundation.py @@ -0,0 +1,129 @@ +"""Add customer lifecycle audit and normalized shadow matches. + +Revision ID: 5d6e7f8a9b0c +Revises: 4c5d6e7f8a9 +Create Date: 2026-07-16 + +用途:为货代客户的删除资格、后续合并和审计建立可反查的引用基础。 +依赖:shipping_customers、shipping_customer_shadow_resolutions、users。 +逻辑:生命周期审计仅保存客户快照;影子候选关系规范化后可作为业务审计引用统计。 +""" + +from __future__ import annotations + +import json +from datetime import datetime + +import sqlalchemy as sa +from alembic import op + + +revision = '5d6e7f8a9b0c' +down_revision = '4c5d6e7f8a9' +branch_labels = None +depends_on = None + + +def _json_matches(value: object) -> list[dict]: + """将既有 JSON 候选安全转换为列表,避免坏审计数据阻断迁移。""" + if isinstance(value, str): + try: + value = json.loads(value) + except (TypeError, ValueError): + return [] + return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else [] + + +def upgrade() -> None: + """创建生命周期审计和影子候选表,并回填可识别的既有 JSON 候选。""" + op.create_table( + 'shipping_customer_lifecycle_events', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('event_type', sa.String(length=32), nullable=False), + sa.Column('customer_id_snapshot', sa.Integer(), 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('actor_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('reason', sa.Text(), nullable=True), + sa.Column('detail_json', sa.JSON(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + ) + op.create_index( + 'ix_shipping_customer_lifecycle_events_customer_created', + 'shipping_customer_lifecycle_events', + ['customer_id_snapshot', 'created_at'], + ) + op.create_index( + 'ix_shipping_customer_lifecycle_events_event_created', + 'shipping_customer_lifecycle_events', + ['event_type', 'created_at'], + ) + op.create_index('ix_shipping_customer_lifecycle_events_created_at', 'shipping_customer_lifecycle_events', ['created_at']) + + op.create_table( + 'shipping_customer_shadow_matches', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('resolution_id', sa.Integer(), sa.ForeignKey('shipping_customer_shadow_resolutions.id', ondelete='CASCADE'), nullable=False), + sa.Column('customer_id', sa.Integer(), sa.ForeignKey('shipping_customers.id'), nullable=False), + sa.Column('match_rank', sa.Integer(), nullable=False), + sa.Column('score', sa.Float(), nullable=False), + sa.Column('standard_name_snapshot', sa.String(length=200), nullable=False), + sa.Column('short_code_snapshot', sa.String(length=6), nullable=False), + sa.Column('reasons_json', sa.JSON(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('resolution_id', 'customer_id', name='uq_shipping_customer_shadow_matches_resolution_customer'), + ) + op.create_index('ix_shipping_customer_shadow_matches_resolution_id', 'shipping_customer_shadow_matches', ['resolution_id']) + op.create_index('ix_shipping_customer_shadow_matches_customer', 'shipping_customer_shadow_matches', ['customer_id']) + + bind = op.get_bind() + existing_customer_ids = { + int(row[0]) for row in bind.execute(sa.text('SELECT id FROM shipping_customers')).all() + } + rows = bind.execute(sa.text( + 'SELECT id, candidate_matches_json, created_at, updated_at FROM shipping_customer_shadow_resolutions' + )).mappings().all() + shadow_matches = sa.table( + 'shipping_customer_shadow_matches', + sa.column('resolution_id', sa.Integer()), + sa.column('customer_id', sa.Integer()), + sa.column('match_rank', sa.Integer()), + sa.column('score', sa.Float()), + sa.column('standard_name_snapshot', sa.String()), + sa.column('short_code_snapshot', sa.String()), + sa.column('reasons_json', sa.JSON()), + sa.column('created_at', sa.DateTime()), + sa.column('updated_at', sa.DateTime()), + ) + for row in rows: + seen_customer_ids: set[int] = set() + values: list[dict] = [] + for rank, item in enumerate(_json_matches(row['candidate_matches_json']), start=1): + try: + customer_id = int(item.get('customer_id')) + score = float(item.get('score')) + except (TypeError, ValueError): + continue + if customer_id not in existing_customer_ids or customer_id in seen_customer_ids: + continue + seen_customer_ids.add(customer_id) + values.append({ + 'resolution_id': int(row['id']), + 'customer_id': customer_id, + 'match_rank': rank, + 'score': score, + 'standard_name_snapshot': str(item.get('standard_name') or ''), + 'short_code_snapshot': str(item.get('short_code') or ''), + 'reasons_json': list(item.get('reasons') or []), + 'created_at': row['created_at'] or datetime.utcnow(), + 'updated_at': row['updated_at'] or datetime.utcnow(), + }) + if values: + bind.execute(shadow_matches.insert(), values) + + +def downgrade() -> None: + """移除阶段二基础表;原影子 JSON 审计保持不变。""" + op.drop_table('shipping_customer_shadow_matches') + op.drop_table('shipping_customer_lifecycle_events') diff --git a/backend/migrations/versions/6e7f8a9b0c1d_shipping_customer_merge_foundation.py b/backend/migrations/versions/6e7f8a9b0c1d_shipping_customer_merge_foundation.py new file mode 100644 index 00000000..d6baa9ba --- /dev/null +++ b/backend/migrations/versions/6e7f8a9b0c1d_shipping_customer_merge_foundation.py @@ -0,0 +1,70 @@ +"""Add shipping customer merge relationship and immutable merge audit. + +Revision ID: 6e7f8a9b0c1d +Revises: 5d6e7f8a9b0c +Create Date: 2026-07-16 + +用途:建立客户身份归并关系和快照审计,不改写既有业务或识别审计引用。 +依赖:shipping_customers、shipping_customer_lifecycle_events、users。 +逻辑:源客户以 merged 状态保留并指向启用目标客户;合并记录仅存快照,避免成为未来删除资格的反向外键。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = '6e7f8a9b0c1d' +down_revision = '5d6e7f8a9b0c' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """增加源客户到目标客户的关联,并创建不可变合并审计表。""" + with op.batch_alter_table('shipping_customers', schema=None) as batch_op: + batch_op.add_column(sa.Column('merged_into_customer_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + 'fk_shipping_customers_merged_into_customer_id', + 'shipping_customers', + ['merged_into_customer_id'], + ['id'], + ) + batch_op.create_index( + 'ix_shipping_customers_merged_into_customer_id', + ['merged_into_customer_id'], + unique=False, + ) + + op.create_table( + 'shipping_customer_merges', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('source_customer_id_snapshot', sa.Integer(), nullable=False), + sa.Column('source_name_snapshot', sa.String(length=200), nullable=False), + sa.Column('source_short_code_snapshot', sa.String(length=6), nullable=False), + sa.Column('target_customer_id_snapshot', sa.Integer(), nullable=False), + sa.Column('target_name_snapshot', sa.String(length=200), nullable=False), + sa.Column('target_short_code_snapshot', sa.String(length=6), nullable=False), + sa.Column('actor_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('reason', sa.Text(), nullable=False), + sa.Column('detail_json', sa.JSON(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('source_customer_id_snapshot', name='uq_shipping_customer_merges_source_snapshot'), + ) + op.create_index( + 'ix_shipping_customer_merges_target_created', + 'shipping_customer_merges', + ['target_customer_id_snapshot', 'created_at'], + unique=False, + ) + op.create_index('ix_shipping_customer_merges_created_at', 'shipping_customer_merges', ['created_at'], unique=False) + + +def downgrade() -> None: + """移除合并审计和源客户关联;不尝试恢复已执行的业务归并。""" + op.drop_table('shipping_customer_merges') + with op.batch_alter_table('shipping_customers', schema=None) as batch_op: + batch_op.drop_index('ix_shipping_customers_merged_into_customer_id') + batch_op.drop_constraint('fk_shipping_customers_merged_into_customer_id', type_='foreignkey') + batch_op.drop_column('merged_into_customer_id') diff --git a/backend/migrations/versions/7f8e9d0c1b2a_add_inventory_source_business_config.py b/backend/migrations/versions/7f8e9d0c1b2a_add_inventory_source_business_config.py new file mode 100644 index 00000000..434b5de8 --- /dev/null +++ b/backend/migrations/versions/7f8e9d0c1b2a_add_inventory_source_business_config.py @@ -0,0 +1,43 @@ +"""Add source-owned inventory report configuration. + +Revision ID: 7f8e9d0c1b2a +Revises: 6e7f8a9b0c1d +Create Date: 2026-07-17 + +用途:将 DBS 报表路径、查询参数和库存源识别别名持久化到库存源。 +依赖:shipping_inventory_sources;由 inventory_source_repository 投影为 RPA worker 契约。 +逻辑:连接配置只保留登录与凭据;本迁移不读取或转换历史 YAML。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = '7f8e9d0c1b2a' +down_revision = '6e7f8a9b0c1d' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """为每个库存源增加业务报表配置,使用空 JSON 保持列非空。""" + with op.batch_alter_table('shipping_inventory_sources') as batch_op: + batch_op.add_column( + sa.Column('report_path_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'")), + ) + batch_op.add_column( + sa.Column('query_parameters_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'")), + ) + batch_op.add_column( + sa.Column('match_aliases_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'")), + ) + + +def downgrade() -> None: + """删除 Source 业务报表配置列,仅用于迁移回滚。""" + with op.batch_alter_table('shipping_inventory_sources') as batch_op: + batch_op.drop_column('match_aliases_json') + batch_op.drop_column('query_parameters_json') + batch_op.drop_column('report_path_json') diff --git a/backend/migrations/versions/8a9b0c1d2e3f_rename_rpa_operation_to_login_config.py b/backend/migrations/versions/8a9b0c1d2e3f_rename_rpa_operation_to_login_config.py new file mode 100644 index 00000000..7cfafb13 --- /dev/null +++ b/backend/migrations/versions/8a9b0c1d2e3f_rename_rpa_operation_to_login_config.py @@ -0,0 +1,32 @@ +"""Rename RPA profile operation JSON to login configuration. + +Revision ID: 8a9b0c1d2e3f +Revises: 7f8e9d0c1b2a +Create Date: 2026-07-17 + +用途:将货代连接配置从通用页面操作 JSON 收紧为登录配置。 +依赖:shipping_rpa_profiles;页面操作和下载策略由 DBS/Crane Driver 模板维护。 +逻辑:本项目不做历史兼容,升级后 Profile 不再承载报表路径、参数或 selector。 +""" + +from __future__ import annotations + +from alembic import op + + +revision = '8a9b0c1d2e3f' +down_revision = '7f8e9d0c1b2a' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """将 operation_config_json 重命名为 login_config_json。""" + with op.batch_alter_table('shipping_rpa_profiles') as batch_op: + batch_op.alter_column('operation_config_json', new_column_name='login_config_json') + + +def downgrade() -> None: + """仅为迁移回滚恢复旧列名。""" + with op.batch_alter_table('shipping_rpa_profiles') as batch_op: + batch_op.alter_column('login_config_json', new_column_name='operation_config_json') diff --git a/backend/migrations/versions/9b0c1d2e3f4a_add_shipping_order_schema.py b/backend/migrations/versions/9b0c1d2e3f4a_add_shipping_order_schema.py new file mode 100644 index 00000000..07b8332d --- /dev/null +++ b/backend/migrations/versions/9b0c1d2e3f4a_add_shipping_order_schema.py @@ -0,0 +1,268 @@ +""" +backend/migrations/versions/9b0c1d2e3f4a_add_shipping_order_schema.py + +用途:新增唯一订单 Schema、版本化动态字段和订单解析审计表。 +依赖:8a9b0c1d2e3f 库存配置迁移、users、shipping_tasks、shipping_notice_intakes/documents。 +逻辑:先创建 Schema/字段/版本,再创建 Extraction/Line/Observation/Decision/Value,最后为 Task 增加当前解析引用。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '9b0c1d2e3f4a' +down_revision = '8a9b0c1d2e3f' +branch_labels = None +depends_on = None + + +def upgrade(): + """创建订单 Schema 和动态解析数据结构。""" + op.create_table( + 'shipping_order_schemas', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_code', sa.String(64), nullable=False), + sa.Column('display_name', sa.String(128), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.String(16), server_default='active', nullable=False), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint("schema_code = 'SHIPPING_ORDER'", name='ck_shipping_order_schemas_single_code'), + sa.UniqueConstraint('schema_code', name='uq_shipping_order_schemas_schema_code'), + ) + op.create_table( + 'shipping_order_fields', + sa.Column('id', sa.String(36), primary_key=True), + sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False), + sa.Column('field_code', sa.String(64), nullable=False), + sa.Column('scope', sa.String(16), nullable=False), + sa.Column('value_type', sa.String(16), nullable=False), + sa.Column('status', sa.String(16), server_default='active', nullable=False), + sa.Column('published_once', sa.Boolean(), server_default=sa.text('false'), nullable=False), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'), + sa.CheckConstraint( + "value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')", + name='ck_shipping_order_fields_value_type', + ), + sa.CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'), + sa.UniqueConstraint('schema_id', 'field_code', name='uq_shipping_order_fields_schema_code'), + ) + op.create_index('ix_shipping_order_fields_schema_scope', 'shipping_order_fields', ['schema_id', 'scope']) + op.create_table( + 'shipping_order_schema_versions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('status', sa.String(16), server_default='draft', nullable=False), + sa.Column('definition_json', sa.JSON(), nullable=False), + sa.Column('checksum', sa.String(64), nullable=True), + sa.Column('change_note', sa.Text(), nullable=True), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('published_by_id', sa.Integer(), sa.ForeignKey('users.id'), 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.CheckConstraint( + "status IN ('draft', 'published', 'retired')", + name='ck_shipping_order_schema_versions_status', + ), + sa.UniqueConstraint('schema_id', 'version', name='uq_shipping_order_schema_versions_schema_version'), + ) + op.create_index( + 'uq_shipping_order_schema_one_published', + 'shipping_order_schema_versions', + ['schema_id'], + unique=True, + postgresql_where=sa.text("status = 'published'"), + sqlite_where=sa.text("status = 'published'"), + ) + op.create_table( + 'shipping_order_schema_version_fields', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False), + sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False), + sa.Column('display_name', sa.String(128), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('required', sa.Boolean(), server_default=sa.text('false'), nullable=False), + sa.Column('aliases_json', sa.JSON(), nullable=False), + sa.Column('normalizer_key', sa.String(64), server_default='trim', nullable=False), + sa.Column('validator_keys_json', sa.JSON(), nullable=False), + sa.Column('enum_options_json', sa.JSON(), nullable=False), + sa.Column('evidence_policy_json', sa.JSON(), nullable=False), + sa.Column('relation_role', sa.String(32), nullable=True), + sa.Column('comparator_key', sa.String(64), server_default='normalized_text', nullable=False), + sa.Column('extraction_instruction', sa.Text(), nullable=True), + sa.Column('sequence', sa.Integer(), nullable=False), + sa.UniqueConstraint( + 'schema_version_id', 'field_id', name='uq_shipping_order_schema_version_fields_field' + ), + sa.UniqueConstraint( + 'schema_version_id', 'sequence', name='uq_shipping_order_schema_version_fields_sequence' + ), + ) + op.create_table( + 'shipping_order_extractions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('task_id', sa.Integer(), sa.ForeignKey('shipping_tasks.id'), nullable=True), + sa.Column('intake_id', sa.Integer(), sa.ForeignKey('shipping_notice_intakes.id'), nullable=True), + sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False), + sa.Column('input_snapshot_hash', sa.String(64), nullable=False), + sa.Column('status', sa.String(32), server_default='created', nullable=False), + sa.Column('raw_llm_output_json', sa.JSON(), nullable=True), + sa.Column('normalized_result_json', sa.JSON(), nullable=True), + sa.Column('validation_result_json', sa.JSON(), nullable=True), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "status IN ('created', 'extracting', 'needs_review', 'accepted', 'failed', 'superseded')", + name='ck_shipping_order_extractions_status', + ), + ) + op.create_index( + 'ix_shipping_order_extractions_task_created', 'shipping_order_extractions', ['task_id', 'created_at'] + ) + op.create_index( + 'ix_shipping_order_extractions_intake_created', 'shipping_order_extractions', ['intake_id', 'created_at'] + ) + op.create_table( + 'shipping_order_lines', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column( + 'extraction_id', sa.Integer(), sa.ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False + ), + sa.Column('position', sa.Integer(), nullable=False), + sa.Column('line_key', sa.String(128), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'), + ) + op.create_table( + 'shipping_order_field_observations', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column( + 'extraction_id', sa.Integer(), sa.ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False + ), + sa.Column('line_id', sa.Integer(), sa.ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True), + sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False), + sa.Column('source_document_id', sa.Integer(), sa.ForeignKey('shipping_notice_documents.id'), nullable=True), + sa.Column('source_type', sa.String(32), nullable=False), + sa.Column('extractor', sa.String(32), nullable=False), + sa.Column('raw_value_json', sa.JSON(), nullable=True), + sa.Column('normalized_value_json', sa.JSON(), nullable=True), + sa.Column('evidence_quote', sa.Text(), nullable=True), + sa.Column('confidence', sa.Numeric(5, 4), nullable=True), + sa.Column('evidence_verified', sa.Boolean(), server_default=sa.text('false'), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + ) + op.create_index( + 'ix_shipping_order_observations_extraction_field', + 'shipping_order_field_observations', + ['extraction_id', 'field_id'], + ) + op.create_table( + 'shipping_order_field_decisions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column( + 'extraction_id', sa.Integer(), sa.ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False + ), + sa.Column('line_id', sa.Integer(), sa.ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True), + sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False), + sa.Column('decision_status', sa.String(32), nullable=False), + sa.Column( + 'selected_observation_id', sa.Integer(), sa.ForeignKey('shipping_order_field_observations.id'), nullable=True + ), + sa.Column('supporting_observation_ids_json', sa.JSON(), nullable=False), + sa.Column('resolved_value_json', sa.JSON(), nullable=True), + sa.Column('reason_code', sa.String(64), nullable=True), + sa.Column('decided_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "decision_status IN ('accepted', 'corroborated', 'needs_review', 'blocked', 'missing')", + name='ck_shipping_order_decisions_status', + ), + ) + op.create_index( + 'uq_shipping_order_decisions_header_field', + 'shipping_order_field_decisions', + ['extraction_id', 'field_id'], + unique=True, + postgresql_where=sa.text('line_id IS NULL'), + sqlite_where=sa.text('line_id IS NULL'), + ) + op.create_index( + 'uq_shipping_order_decisions_line_field', + 'shipping_order_field_decisions', + ['extraction_id', 'line_id', 'field_id'], + unique=True, + postgresql_where=sa.text('line_id IS NOT NULL'), + sqlite_where=sa.text('line_id IS NOT NULL'), + ) + op.create_table( + 'shipping_order_field_values', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column( + 'extraction_id', sa.Integer(), sa.ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False + ), + sa.Column('line_id', sa.Integer(), sa.ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True), + sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False), + sa.Column('value_text', sa.Text(), nullable=True), + sa.Column('value_decimal', sa.Numeric(24, 8), nullable=True), + sa.Column('value_integer', sa.Integer(), nullable=True), + sa.Column('value_date', sa.Date(), nullable=True), + sa.Column('value_boolean', sa.Boolean(), nullable=True), + sa.Column('value_json', sa.JSON(), nullable=True), + sa.Column('decision_id', sa.Integer(), sa.ForeignKey('shipping_order_field_decisions.id'), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + ) + op.create_index( + 'uq_shipping_order_field_values_header_field', + 'shipping_order_field_values', + ['extraction_id', 'field_id'], + unique=True, + postgresql_where=sa.text('line_id IS NULL'), + sqlite_where=sa.text('line_id IS NULL'), + ) + op.create_index( + 'uq_shipping_order_field_values_line_field', + 'shipping_order_field_values', + ['extraction_id', 'line_id', 'field_id'], + unique=True, + postgresql_where=sa.text('line_id IS NOT NULL'), + sqlite_where=sa.text('line_id IS NOT NULL'), + ) + op.create_index('ix_shipping_order_field_values_field_text', 'shipping_order_field_values', ['field_id', 'value_text']) + op.create_index( + 'ix_shipping_order_field_values_field_decimal', 'shipping_order_field_values', ['field_id', 'value_decimal'] + ) + with op.batch_alter_table('shipping_tasks') as batch_op: + batch_op.add_column(sa.Column('current_order_extraction_id', sa.Integer(), nullable=True)) + batch_op.create_index( + 'ix_shipping_tasks_current_order_extraction_id', ['current_order_extraction_id'] + ) + batch_op.create_foreign_key( + 'fk_shipping_tasks_current_order_extraction_id', + 'shipping_order_extractions', + ['current_order_extraction_id'], + ['id'], + ) + + +def downgrade(): + """移除订单 Schema 和动态解析结构。""" + with op.batch_alter_table('shipping_tasks') as batch_op: + batch_op.drop_constraint('fk_shipping_tasks_current_order_extraction_id', type_='foreignkey') + batch_op.drop_index('ix_shipping_tasks_current_order_extraction_id') + batch_op.drop_column('current_order_extraction_id') + op.drop_table('shipping_order_field_values') + op.drop_table('shipping_order_field_decisions') + op.drop_table('shipping_order_field_observations') + op.drop_table('shipping_order_lines') + op.drop_table('shipping_order_extractions') + op.drop_table('shipping_order_schema_version_fields') + op.drop_table('shipping_order_schema_versions') + op.drop_table('shipping_order_fields') + op.drop_table('shipping_order_schemas') diff --git a/backend/migrations/versions/a0b1c2d3e4f5_dynamic_order_fields_for_inventory_routing.py b/backend/migrations/versions/a0b1c2d3e4f5_dynamic_order_fields_for_inventory_routing.py new file mode 100644 index 00000000..d175cdf3 --- /dev/null +++ b/backend/migrations/versions/a0b1c2d3e4f5_dynamic_order_fields_for_inventory_routing.py @@ -0,0 +1,42 @@ +""" +用途:将库存源路由条件从固定 fact_path 切换为动态订单 field_id 或受控系统事实。 +依赖:9b0c1d2e3f4a 订单 Schema、shipping_inventory_routing_rule_conditions。 +逻辑:不保留历史兼容,直接移除 fact_path 并新增互斥字段来源。 +""" + +from alembic import op +import sqlalchemy as sa + +revision = 'a0b1c2d3e4f5' +down_revision = '9b0c1d2e3f4a' +branch_labels = None +depends_on = None + + +def upgrade(): + """替换库存路由条件字段引用结构。""" + with op.batch_alter_table('shipping_inventory_routing_rule_conditions') as batch: + batch.drop_column('fact_path') + batch.add_column(sa.Column('source_kind', sa.String(16), server_default='order_field', nullable=False)) + batch.add_column(sa.Column('order_field_id', sa.String(36), nullable=True)) + batch.add_column(sa.Column('system_fact_key', sa.String(128), nullable=True)) + batch.create_foreign_key( + 'fk_inventory_routing_conditions_order_field', 'shipping_order_fields', + ['order_field_id'], ['id'], + ) + batch.create_check_constraint( + 'ck_inventory_routing_condition_source', + "(source_kind = 'order_field' AND order_field_id IS NOT NULL AND system_fact_key IS NULL) OR " + "(source_kind = 'system_fact' AND order_field_id IS NULL AND system_fact_key IS NOT NULL)", + ) + + +def downgrade(): + """恢复旧固定 fact_path 结构。""" + with op.batch_alter_table('shipping_inventory_routing_rule_conditions') as batch: + batch.drop_constraint('ck_inventory_routing_condition_source', type_='check') + batch.drop_constraint('fk_inventory_routing_conditions_order_field', type_='foreignkey') + batch.drop_column('system_fact_key') + batch.drop_column('order_field_id') + batch.drop_column('source_kind') + batch.add_column(sa.Column('fact_path', sa.String(128), nullable=False)) diff --git a/backend/migrations/versions/b17e3d4c5a60_inventory_parsing_profiles.py b/backend/migrations/versions/b17e3d4c5a60_inventory_parsing_profiles.py new file mode 100644 index 00000000..18273dee --- /dev/null +++ b/backend/migrations/versions/b17e3d4c5a60_inventory_parsing_profiles.py @@ -0,0 +1,39 @@ +"""新增可复用库存解析 Profile,并允许库存源绑定 published Profile。""" +from alembic import op +import sqlalchemy as sa + +revision = 'b17e3d4c5a60' +down_revision = 'a0b1c2d3e4f5' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'shipping_inventory_parsing_profiles', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('profile_code', sa.String(64), nullable=False), + sa.Column('display_name', sa.String(128), nullable=False), + sa.Column('version', sa.Integer(), server_default='1', nullable=False), + sa.Column('status', sa.String(16), server_default='draft', nullable=False), + sa.Column('file_format', sa.String(16), server_default='xlsx', nullable=False), + sa.Column('definition_json', sa.JSON(), nullable=False), + sa.Column('checksum', sa.String(64), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('published_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('published_at', sa.DateTime(), nullable=True), + sa.UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'), + ) + with op.batch_alter_table('shipping_inventory_sources') as batch: + batch.add_column(sa.Column('parsing_profile_id', sa.Integer(), nullable=True)) + batch.create_index('ix_shipping_inventory_sources_parsing_profile_id', ['parsing_profile_id']) + batch.create_foreign_key('fk_inventory_sources_parsing_profile', 'shipping_inventory_parsing_profiles', ['parsing_profile_id'], ['id']) + + +def downgrade(): + with op.batch_alter_table('shipping_inventory_sources') as batch: + batch.drop_constraint('fk_inventory_sources_parsing_profile', type_='foreignkey') + batch.drop_index('ix_shipping_inventory_sources_parsing_profile_id') + batch.drop_column('parsing_profile_id') + op.drop_table('shipping_inventory_parsing_profiles') diff --git a/backend/migrations/versions/c27e3d4c5a61_shipping_excel_templates.py b/backend/migrations/versions/c27e3d4c5a61_shipping_excel_templates.py new file mode 100644 index 00000000..d01c4534 --- /dev/null +++ b/backend/migrations/versions/c27e3d4c5a61_shipping_excel_templates.py @@ -0,0 +1,81 @@ +"""新增版本化发货 Excel 模板、库存源绑定与不可变导出产物。""" +from alembic import op +import sqlalchemy as sa + +revision = 'c27e3d4c5a61' +down_revision = 'b17e3d4c5a60' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'shipping_excel_templates', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('template_code', sa.String(64), nullable=False), + sa.Column('display_name', sa.String(128), nullable=False), + sa.Column('version', sa.Integer(), server_default='1', nullable=False), + sa.Column('status', sa.String(16), server_default='draft', nullable=False), + sa.Column('storage_provider', sa.String(32), server_default='minio', nullable=False), + sa.Column('storage_bucket', sa.String(128), nullable=False), + sa.Column('storage_key', sa.String(512), nullable=False), + sa.Column('original_filename', sa.String(255), nullable=False), + sa.Column('file_checksum', sa.String(64), nullable=False), + sa.Column('definition_json', sa.JSON(), nullable=False), + sa.Column('definition_checksum', sa.String(64), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('published_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('published_at', sa.DateTime(), nullable=True), + sa.UniqueConstraint('template_code', 'version', name='uq_shipping_excel_templates_code_version'), + ) + op.create_index('ix_shipping_excel_templates_status', 'shipping_excel_templates', ['status']) + with op.batch_alter_table('shipping_inventory_sources') as batch: + batch.add_column(sa.Column('excel_template_id', sa.Integer(), nullable=True)) + batch.create_index('ix_shipping_inventory_sources_excel_template_id', ['excel_template_id']) + batch.create_foreign_key('fk_inventory_sources_excel_template', 'shipping_excel_templates', ['excel_template_id'], ['id']) + op.execute( + sa.text( + 'UPDATE shipping_inventory_sources SET enabled = false ' + 'WHERE parsing_profile_id IS NULL OR excel_template_id IS NULL' + ) + ) + with op.batch_alter_table('shipping_inventory_sources') as batch: + batch.create_check_constraint( + 'ck_shipping_inventory_sources_enabled_bindings', + 'enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)', + ) + op.create_table( + 'shipping_export_artifacts', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('artifact_no', sa.String(64), nullable=False), + sa.Column('task_id', sa.Integer(), sa.ForeignKey('shipping_tasks.id'), nullable=False), + sa.Column('batch_id', sa.Integer(), sa.ForeignKey('shipping_batches.id'), nullable=True), + sa.Column('template_id', sa.Integer(), sa.ForeignKey('shipping_excel_templates.id'), nullable=False), + sa.Column('order_schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False), + sa.Column('order_extraction_id', sa.Integer(), sa.ForeignKey('shipping_order_extractions.id'), nullable=False), + sa.Column('inventory_parsing_profile_id', sa.Integer(), sa.ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False), + sa.Column('inventory_snapshot_id', sa.Integer(), sa.ForeignKey('shipping_inventory_files.id'), nullable=True), + sa.Column('input_checksum', sa.String(64), nullable=False), + sa.Column('file_path', sa.String(500), nullable=False), + sa.Column('file_name', sa.String(255), nullable=False), + sa.Column('file_checksum', sa.String(64), nullable=False), + sa.Column('file_size', sa.Integer(), nullable=False), + sa.Column('status', sa.String(16), server_default='ready', nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('artifact_no', name='uq_shipping_export_artifacts_no'), + ) + op.create_index('ix_shipping_export_artifacts_task_id', 'shipping_export_artifacts', ['task_id']) + op.create_index('ix_shipping_export_artifacts_task_created', 'shipping_export_artifacts', ['task_id', 'created_at']) + op.create_index('ix_shipping_export_artifacts_batch_created', 'shipping_export_artifacts', ['batch_id', 'created_at']) + + +def downgrade(): + op.drop_table('shipping_export_artifacts') + with op.batch_alter_table('shipping_inventory_sources') as batch: + batch.drop_constraint('ck_shipping_inventory_sources_enabled_bindings', type_='check') + batch.drop_constraint('fk_inventory_sources_excel_template', type_='foreignkey') + batch.drop_index('ix_shipping_inventory_sources_excel_template_id') + batch.drop_column('excel_template_id') + op.drop_index('ix_shipping_excel_templates_status', table_name='shipping_excel_templates') + op.drop_table('shipping_excel_templates') diff --git a/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py b/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py new file mode 100644 index 00000000..ca8fe61c --- /dev/null +++ b/backend/migrations/versions/d38f4a5b6c7d_rename_erp_mappings_to_external_mappings.py @@ -0,0 +1,120 @@ +""" +rename erp mappings to external mappings + +Revision ID: d38f4a5b6c7d +Revises: c27e3d4c5a61 +Create Date: 2026-07-17 10:28:00.000000 + +用途:将库存 ERP 映射表重命名为外部系统映射,对齐模型 ShippingInventoryExternalMapping。 +依赖:Alembic;承接 shipping_excel_templates 迁移后的库表。 +逻辑:本地库在 2b3c 应用后仍保留 erp_* 表名,而模型已切到 external_*;本迁移做兼容重命名。 +""" + +from __future__ import annotations + +from alembic import op + + +revision = 'd38f4a5b6c7d' +down_revision = 'c27e3d4c5a61' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """将 shipping_inventory_erp_mappings 重命名为 shipping_inventory_external_mappings。""" + # [STEP 1] 表名 + op.rename_table('shipping_inventory_erp_mappings', 'shipping_inventory_external_mappings') + + # [STEP 2] 列名:erp_* -> external_* + op.alter_column( + 'shipping_inventory_external_mappings', + 'erp_system_code', + new_column_name='external_system_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'erp_company_code', + new_column_name='external_organization_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'erp_plant_code', + new_column_name='external_site_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'erp_warehouse_code', + new_column_name='external_warehouse_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'erp_warehouse_name', + new_column_name='external_warehouse_name', + ) + + # [STEP 3] 索引名 + op.execute( + 'ALTER INDEX IF EXISTS ix_shipping_inventory_erp_mappings_inventory_source_id ' + 'RENAME TO ix_shipping_inventory_external_mappings_inventory_source_id' + ) + op.execute( + 'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_default_enabled ' + 'RENAME TO uq_shipping_inventory_external_mappings_source_default_enabled' + ) + op.execute( + 'ALTER INDEX IF EXISTS uq_shipping_inventory_erp_mappings_source_warehouse_enabled ' + 'RENAME TO uq_shipping_inventory_external_mappings_source_warehouse_enabled' + ) + op.execute( + 'ALTER INDEX IF EXISTS shipping_inventory_erp_mappings_pkey ' + 'RENAME TO shipping_inventory_external_mappings_pkey' + ) + + +def downgrade() -> None: + """回滚为 erp_* 表与列名。""" + op.execute( + 'ALTER INDEX IF EXISTS shipping_inventory_external_mappings_pkey ' + 'RENAME TO shipping_inventory_erp_mappings_pkey' + ) + op.execute( + 'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_warehouse_enabled ' + 'RENAME TO uq_shipping_inventory_erp_mappings_source_warehouse_enabled' + ) + op.execute( + 'ALTER INDEX IF EXISTS uq_shipping_inventory_external_mappings_source_default_enabled ' + 'RENAME TO uq_shipping_inventory_erp_mappings_source_default_enabled' + ) + op.execute( + 'ALTER INDEX IF EXISTS ix_shipping_inventory_external_mappings_inventory_source_id ' + 'RENAME TO ix_shipping_inventory_erp_mappings_inventory_source_id' + ) + + op.alter_column( + 'shipping_inventory_external_mappings', + 'external_warehouse_name', + new_column_name='erp_warehouse_name', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'external_warehouse_code', + new_column_name='erp_warehouse_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'external_site_code', + new_column_name='erp_plant_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'external_organization_code', + new_column_name='erp_company_code', + ) + op.alter_column( + 'shipping_inventory_external_mappings', + 'external_system_code', + new_column_name='erp_system_code', + ) + + op.rename_table('shipping_inventory_external_mappings', 'shipping_inventory_erp_mappings') diff --git a/backend/migrations/versions/e49a5b6c7d8e_add_shipping_order_customer_matches.py b/backend/migrations/versions/e49a5b6c7d8e_add_shipping_order_customer_matches.py new file mode 100644 index 00000000..ebc4d44c --- /dev/null +++ b/backend/migrations/versions/e49a5b6c7d8e_add_shipping_order_customer_matches.py @@ -0,0 +1,100 @@ +""" +新增订单解析角色化客户匹配表。 + +Revision ID: e49a5b6c7d8e +Revises: d38f4a5b6c7d + +用途:分别保存 Bill-to / Ship-to 与货代客户主数据的匹配结果和简称快照。 +依赖:shipping_order_extractions、shipping_customers、users。 +逻辑:订单字段保留原文,本表保存候选与确认结果;每个解析记录每种角色唯一。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'e49a5b6c7d8e' +down_revision = 'd38f4a5b6c7d' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建客户站点、站点标识及订单客户角色匹配表。""" + op.create_table( + 'shipping_customer_sites', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('customer_id', sa.Integer(), sa.ForeignKey('shipping_customers.id'), nullable=False), + sa.Column('site_name', sa.String(200), nullable=False), + sa.Column('site_code', sa.String(64), nullable=False), + sa.Column('address', sa.Text(), nullable=True), + sa.Column('city', sa.String(128), nullable=True), + sa.Column('country', sa.String(64), nullable=True), + sa.Column('status', sa.String(32), server_default='active', nullable=False), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('customer_id', 'site_code', name='uq_shipping_customer_sites_customer_code'), + ) + op.create_index('ix_shipping_customer_sites_customer_id', 'shipping_customer_sites', ['customer_id']) + op.create_index('ix_shipping_customer_sites_status_name', 'shipping_customer_sites', ['status', 'site_name']) + op.create_table( + 'shipping_customer_site_identifiers', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('site_id', sa.Integer(), sa.ForeignKey('shipping_customer_sites.id'), nullable=False), + sa.Column('identifier_type', sa.String(32), nullable=False), + sa.Column('source_system', sa.String(64), server_default='', nullable=False), + sa.Column('raw_value', sa.String(500), nullable=False), + sa.Column('normalized_value', sa.String(500), nullable=False), + sa.Column('status', sa.String(32), server_default='approved', nullable=False), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('site_id', 'identifier_type', 'source_system', 'normalized_value', name='uq_shipping_customer_site_identifiers_value'), + ) + op.create_index('ix_shipping_customer_site_identifiers_site_id', 'shipping_customer_site_identifiers', ['site_id']) + op.create_index('ix_shipping_customer_site_identifiers_lookup', 'shipping_customer_site_identifiers', ['identifier_type', 'source_system', 'normalized_value', 'status']) + op.create_table( + 'shipping_order_customer_matches', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('extraction_id', sa.Integer(), sa.ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False), + sa.Column('role', sa.String(16), nullable=False), + sa.Column('raw_name', sa.Text(), nullable=True), + sa.Column('normalized_name', sa.String(500), nullable=True), + sa.Column('source_system', sa.String(64), nullable=True), + sa.Column('external_code', sa.String(128), nullable=True), + sa.Column('status', sa.String(32), server_default='unmatched', nullable=False), + sa.Column('customer_id', sa.Integer(), sa.ForeignKey('shipping_customers.id'), nullable=True), + sa.Column('site_id', sa.Integer(), sa.ForeignKey('shipping_customer_sites.id'), nullable=True), + sa.Column('customer_name_snapshot', sa.String(200), nullable=True), + sa.Column('customer_short_code_snapshot', sa.String(6), nullable=True), + sa.Column('candidates_json', sa.JSON(), nullable=False), + sa.Column('resolution_method', sa.String(32), nullable=True), + sa.Column('confirmed_by_id', sa.Integer(), sa.ForeignKey('users.id'), 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.CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'), + sa.CheckConstraint( + "status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')", + name='ck_shipping_order_customer_matches_status', + ), + sa.UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'), + ) + op.create_index('ix_shipping_order_customer_matches_extraction_id', 'shipping_order_customer_matches', ['extraction_id']) + op.create_index('ix_shipping_order_customer_matches_customer_role', 'shipping_order_customer_matches', ['customer_id', 'role']) + + +def downgrade() -> None: + """删除角色化客户匹配及客户站点表。""" + op.drop_index('ix_shipping_order_customer_matches_customer_role', table_name='shipping_order_customer_matches') + op.drop_index('ix_shipping_order_customer_matches_extraction_id', table_name='shipping_order_customer_matches') + op.drop_table('shipping_order_customer_matches') + op.drop_index('ix_shipping_customer_site_identifiers_lookup', table_name='shipping_customer_site_identifiers') + op.drop_index('ix_shipping_customer_site_identifiers_site_id', table_name='shipping_customer_site_identifiers') + op.drop_table('shipping_customer_site_identifiers') + op.drop_index('ix_shipping_customer_sites_status_name', table_name='shipping_customer_sites') + op.drop_index('ix_shipping_customer_sites_customer_id', table_name='shipping_customer_sites') + op.drop_table('shipping_customer_sites') diff --git a/backend/migrations/versions/f61b7c8d9e0a_add_schema_version_field_enabled.py b/backend/migrations/versions/f61b7c8d9e0a_add_schema_version_field_enabled.py new file mode 100644 index 00000000..72d495ef --- /dev/null +++ b/backend/migrations/versions/f61b7c8d9e0a_add_schema_version_field_enabled.py @@ -0,0 +1,28 @@ +""" +backend/migrations/versions/f61b7c8d9e0a_add_schema_version_field_enabled.py + +用途:让订单 Schema 草稿保存未纳入字段的版本级显示名称和识别规则。 +依赖:shipping_order_schema_version_fields、Alembic Operations。 +逻辑:现有配置回填为已纳入;后续草稿用 enabled 区分“保存配置”和“进入发布契约”。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f61b7c8d9e0a' +down_revision = 'e49a5b6c7d8e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增非空 enabled 标记,现有版本字段保持已纳入语义。""" + with op.batch_alter_table('shipping_order_schema_version_fields') as batch_op: + batch_op.add_column(sa.Column('enabled', sa.Boolean(), server_default=sa.true(), nullable=False)) + + +def downgrade() -> None: + """移除版本字段纳入标记,回退到仅保存已纳入字段的旧模型。""" + with op.batch_alter_table('shipping_order_schema_version_fields') as batch_op: + batch_op.drop_column('enabled') diff --git a/backend/migrations/versions/f72c8d9e0f1a_add_inventory_structure_analyses.py b/backend/migrations/versions/f72c8d9e0f1a_add_inventory_structure_analyses.py new file mode 100644 index 00000000..08cf8696 --- /dev/null +++ b/backend/migrations/versions/f72c8d9e0f1a_add_inventory_structure_analyses.py @@ -0,0 +1,41 @@ +"""新增库存文件结构分析记录。""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f72c8d9e0f1a' +down_revision = 'f61b7c8d9e0a' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建样本上传和后续 RPA 文件共用的结构分析审计表。""" + op.create_table( + 'shipping_inventory_structure_analyses', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('source_kind', sa.String(32), server_default='sample_upload', nullable=False), + sa.Column('source_file_name', sa.String(255), nullable=False), + sa.Column('storage_path', sa.String(500), nullable=False), + sa.Column('file_checksum', sa.String(64), nullable=False), + sa.Column('file_format', sa.String(16), nullable=False), + sa.Column('analysis_status', sa.String(32), server_default='ready', nullable=False), + sa.Column('structure_json', sa.JSON(), nullable=False), + sa.Column('suggested_mapping_json', sa.JSON(), nullable=False), + sa.Column('validation_summary_json', sa.JSON(), nullable=False), + sa.Column('warning_json', sa.JSON(), nullable=False), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.CheckConstraint("source_kind IN ('sample_upload', 'configuration_test', 'production_snapshot')", name='ck_inventory_structure_analysis_source_kind'), + sa.CheckConstraint("file_format IN ('xlsx', 'csv')", name='ck_inventory_structure_analysis_file_format'), + ) + op.create_index('ix_inv_structure_analysis_file_hash', 'shipping_inventory_structure_analyses', ['file_checksum']) + op.create_index('ix_inv_structure_analysis_created', 'shipping_inventory_structure_analyses', ['created_at']) + + +def downgrade() -> None: + """删除结构分析记录表。""" + op.drop_index('ix_inv_structure_analysis_created', table_name='shipping_inventory_structure_analyses') + op.drop_index('ix_inv_structure_analysis_file_hash', table_name='shipping_inventory_structure_analyses') + op.drop_table('shipping_inventory_structure_analyses') diff --git a/backend/migrations/versions/f83d9e0f1a2b_add_inventory_structure_fingerprints.py b/backend/migrations/versions/f83d9e0f1a2b_add_inventory_structure_fingerprints.py new file mode 100644 index 00000000..bb452373 --- /dev/null +++ b/backend/migrations/versions/f83d9e0f1a2b_add_inventory_structure_fingerprints.py @@ -0,0 +1,44 @@ +"""为库存解析方案和分析记录增加结构指纹。""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f83d9e0f1a2b' +down_revision = 'f72c8d9e0f1a' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """保存文件结构和兼容性指纹,不以库存数据内容作为模板身份。""" + with op.batch_alter_table('shipping_inventory_parsing_profiles') as batch: + batch.add_column(sa.Column('structure_definition_json', sa.JSON(), server_default=sa.text("'{}'"), nullable=False)) + batch.add_column(sa.Column('exact_structure_fingerprint', sa.String(64), nullable=True)) + batch.add_column(sa.Column('compatibility_fingerprint', sa.String(64), nullable=True)) + batch.add_column(sa.Column('fingerprint_version', sa.String(32), nullable=True)) + batch.create_index('ix_inv_parse_profile_exact_fp', ['exact_structure_fingerprint']) + batch.create_index('ix_inv_parse_profile_compat_fp', ['compatibility_fingerprint']) + with op.batch_alter_table('shipping_inventory_structure_analyses') as batch: + batch.add_column(sa.Column('exact_structure_fingerprint', sa.String(64), nullable=True)) + batch.add_column(sa.Column('compatibility_fingerprint', sa.String(64), nullable=True)) + batch.add_column(sa.Column('match_result_json', sa.JSON(), server_default=sa.text("'{}'"), nullable=False)) + batch.create_index('ix_inv_structure_analysis_exact_fp', ['exact_structure_fingerprint']) + batch.create_index('ix_inv_structure_analysis_compat_fp', ['compatibility_fingerprint']) + + +def downgrade() -> None: + """移除结构指纹字段。""" + with op.batch_alter_table('shipping_inventory_structure_analyses') as batch: + batch.drop_index('ix_inv_structure_analysis_compat_fp') + batch.drop_index('ix_inv_structure_analysis_exact_fp') + batch.drop_column('match_result_json') + batch.drop_column('compatibility_fingerprint') + batch.drop_column('exact_structure_fingerprint') + with op.batch_alter_table('shipping_inventory_parsing_profiles') as batch: + batch.drop_index('ix_inv_parse_profile_compat_fp') + batch.drop_index('ix_inv_parse_profile_exact_fp') + batch.drop_column('fingerprint_version') + batch.drop_column('compatibility_fingerprint') + batch.drop_column('exact_structure_fingerprint') + batch.drop_column('structure_definition_json') diff --git a/backend/migrations/versions/f94e0f1a2b3c_add_inventory_configuration_test_runs.py b/backend/migrations/versions/f94e0f1a2b3c_add_inventory_configuration_test_runs.py new file mode 100644 index 00000000..4c12dca7 --- /dev/null +++ b/backend/migrations/versions/f94e0f1a2b3c_add_inventory_configuration_test_runs.py @@ -0,0 +1,27 @@ +"""新增库存站点配置测试运行记录。""" +from alembic import op +import sqlalchemy as sa + +revision = 'f94e0f1a2b3c' +down_revision = 'f83d9e0f1a2b' +branch_labels = None +depends_on = None + +def upgrade() -> None: + """测试运行独立于生产库存快照,避免测试数据进入订单匹配。""" + op.create_table('shipping_inventory_configuration_test_runs', + sa.Column('id', sa.Integer(), primary_key=True), sa.Column('run_no', sa.String(64), nullable=False), + sa.Column('inventory_source_id', sa.Integer(), sa.ForeignKey('shipping_inventory_sources.id'), nullable=False), + sa.Column('source_config_version', sa.Integer(), nullable=False), sa.Column('status', sa.String(32), server_default='awaiting_rpa', nullable=False), + sa.Column('stage', sa.String(32), server_default='waiting_worker', nullable=False), + sa.Column('analysis_id', sa.Integer(), sa.ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True), + sa.Column('result_json', sa.JSON(), nullable=False), sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'), + ) + op.create_index('ix_inv_config_test_source_created', 'shipping_inventory_configuration_test_runs', ['inventory_source_id', 'created_at']) + +def downgrade() -> None: + """删除测试运行记录表。""" + op.drop_index('ix_inv_config_test_source_created', table_name='shipping_inventory_configuration_test_runs') + op.drop_table('shipping_inventory_configuration_test_runs') diff --git a/backend/migrations/versions/f95a0b1c2d3e_add_shipping_inventory_field_catalog.py b/backend/migrations/versions/f95a0b1c2d3e_add_shipping_inventory_field_catalog.py new file mode 100644 index 00000000..d5093db1 --- /dev/null +++ b/backend/migrations/versions/f95a0b1c2d3e_add_shipping_inventory_field_catalog.py @@ -0,0 +1,43 @@ +"""新增货代库存字段目录。""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f95a0b1c2d3e' +down_revision = 'f94e0f1a2b3c' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """建立空的库存业务字段目录,具体字段全部由管理员维护。""" + op.create_table( + 'shipping_inventory_fields', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('field_code', sa.String(64), nullable=False), + sa.Column('display_name', sa.String(128), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('value_type', sa.String(16), nullable=False, server_default='text'), + sa.Column('usage_type', sa.String(32), nullable=False, server_default='general'), + # Kept only for migration-chain correctness; the next schema revision removes it. + sa.Column('is_core', sa.Boolean(), nullable=False, server_default=sa.text('false')), + sa.Column('status', sa.String(16), nullable=False, server_default='active'), + sa.Column('sort_order', sa.Integer(), nullable=False, server_default='100'), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')), + sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')), + sa.UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'), + sa.UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'), + sa.CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'), + sa.CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'), + sa.CheckConstraint("usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')", name='ck_shipping_inventory_fields_usage_type'), + ) + op.create_index('ix_shipping_inventory_fields_status_order', 'shipping_inventory_fields', ['status', 'sort_order']) + + +def downgrade() -> None: + """删除库存字段目录。""" + op.drop_index('ix_shipping_inventory_fields_status_order', table_name='shipping_inventory_fields') + op.drop_table('shipping_inventory_fields') diff --git a/backend/migrations/versions/f96b1c2d3e4f_unify_shipping_order_schema_versions.py b/backend/migrations/versions/f96b1c2d3e4f_unify_shipping_order_schema_versions.py new file mode 100644 index 00000000..dbd25d8a --- /dev/null +++ b/backend/migrations/versions/f96b1c2d3e4f_unify_shipping_order_schema_versions.py @@ -0,0 +1,101 @@ +""" +backend/migrations/versions/f96b1c2d3e4f_unify_shipping_order_schema_versions.py + +用途:统一订单 Schema 草稿与发布版本的数据源,并建立配置审计基础。 +依赖:shipping_order_schema_versions、shipping_order_schema_version_fields、users。 +逻辑:清理旧草稿,版本定义统一使用 definition_json;删除旧字段关联表并新增锁、来源和审计事件。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f96b1c2d3e4f' +down_revision = 'f95a0b1c2d3e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """切换到单一 JSON 版本定义,并创建追加式审计表。""" + # Draft versions still have child field rows on upgraded databases; remove children before parents. + op.execute( + "DELETE FROM shipping_order_schema_version_fields " + "WHERE schema_version_id IN (SELECT id FROM shipping_order_schema_versions WHERE status = 'draft')" + ) + op.execute("DELETE FROM shipping_order_schema_versions WHERE status = 'draft'") + op.drop_table('shipping_order_schema_version_fields') + + with op.batch_alter_table('shipping_order_schema_versions') as batch_op: + batch_op.add_column(sa.Column('lock_version', sa.Integer(), server_default='1', nullable=False)) + batch_op.add_column(sa.Column('source_version_id', sa.Integer(), nullable=True)) + batch_op.add_column(sa.Column('retired_at', sa.DateTime(), nullable=True)) + batch_op.create_foreign_key( + 'fk_shipping_order_schema_versions_source_version_id', + 'shipping_order_schema_versions', ['source_version_id'], ['id'], + ) + + op.create_table( + 'shipping_order_schema_audit_events', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False), + sa.Column( + 'version_id', sa.Integer(), + sa.ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True, + ), + sa.Column('event_type', sa.String(32), nullable=False), + sa.Column('actor_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('before_snapshot_json', sa.JSON(), nullable=True), + sa.Column('after_snapshot_json', sa.JSON(), nullable=True), + sa.Column('change_summary_json', sa.JSON(), nullable=False), + sa.Column('request_id', sa.String(64), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.CheckConstraint( + "event_type IN ('draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', " + "'field_saved', 'field_retired', 'field_deleted')", + name='ck_shipping_order_schema_audit_event_type', + ), + ) + op.create_index( + 'ix_shipping_order_schema_audit_version_created', + 'shipping_order_schema_audit_events', ['version_id', 'created_at'], + ) + op.create_index( + 'ix_shipping_order_schema_audit_schema_created', + 'shipping_order_schema_audit_events', ['schema_id', 'created_at'], + ) + + +def downgrade() -> None: + """恢复旧版本字段关联表;审计事件和新版本治理字段会被移除。""" + op.drop_index('ix_shipping_order_schema_audit_schema_created', table_name='shipping_order_schema_audit_events') + op.drop_index('ix_shipping_order_schema_audit_version_created', table_name='shipping_order_schema_audit_events') + op.drop_table('shipping_order_schema_audit_events') + + with op.batch_alter_table('shipping_order_schema_versions') as batch_op: + batch_op.drop_constraint('fk_shipping_order_schema_versions_source_version_id', type_='foreignkey') + batch_op.drop_column('retired_at') + batch_op.drop_column('source_version_id') + batch_op.drop_column('lock_version') + + op.create_table( + 'shipping_order_schema_version_fields', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False), + sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False), + sa.Column('enabled', sa.Boolean(), server_default=sa.true(), nullable=False), + sa.Column('display_name', sa.String(128), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('required', sa.Boolean(), server_default=sa.false(), nullable=False), + sa.Column('aliases_json', sa.JSON(), nullable=False), + sa.Column('normalizer_key', sa.String(64), server_default='trim', nullable=False), + sa.Column('validator_keys_json', sa.JSON(), nullable=False), + sa.Column('enum_options_json', sa.JSON(), nullable=False), + sa.Column('evidence_policy_json', sa.JSON(), nullable=False), + sa.Column('relation_role', sa.String(32), nullable=True), + sa.Column('comparator_key', sa.String(64), server_default='normalized_text', nullable=False), + sa.Column('extraction_instruction', sa.Text(), nullable=True), + sa.Column('sequence', sa.Integer(), nullable=False), + sa.UniqueConstraint('schema_version_id', 'field_id', name='uq_shipping_order_schema_version_fields_field'), + sa.UniqueConstraint('schema_version_id', 'sequence', name='uq_shipping_order_schema_version_fields_sequence'), + ) diff --git a/backend/migrations/versions/f97c2d3e4f5a_add_shipping_temporary_inventory_sessions.py b/backend/migrations/versions/f97c2d3e4f5a_add_shipping_temporary_inventory_sessions.py new file mode 100644 index 00000000..9fa75ef3 --- /dev/null +++ b/backend/migrations/versions/f97c2d3e4f5a_add_shipping_temporary_inventory_sessions.py @@ -0,0 +1,48 @@ +"""新增对话临时库存文件会话。""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f97c2d3e4f5a' +down_revision = 'f96b1c2d3e4f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """创建临时库存会话表,确保对话文件不会直接成为生产库存快照。""" + op.create_table( + 'shipping_temporary_inventory_sessions', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('session_no', sa.String(64), nullable=False), + sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False), + sa.Column('conversation_id', sa.String(100), nullable=False), + sa.Column('asset_id', sa.Integer(), sa.ForeignKey('file_assets.id'), nullable=False), + sa.Column('analysis_id', sa.Integer(), sa.ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True), + sa.Column('batch_id', sa.Integer(), sa.ForeignKey('shipping_batches.id'), nullable=True), + sa.Column('task_id', sa.Integer(), sa.ForeignKey('shipping_tasks.id'), nullable=True), + sa.Column('declared_intent', sa.String(32), nullable=False, server_default='inventory_candidate'), + sa.Column('file_classification_status', sa.String(32), nullable=False, server_default='created'), + sa.Column('status', sa.String(32), nullable=False, server_default='created'), + sa.Column('classification_reason', sa.Text(), nullable=True), + sa.Column('candidate_source_ids_json', sa.JSON(), nullable=False), + sa.Column('result_json', sa.JSON(), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'), + ) + op.create_index('ix_shipping_temp_inventory_user_created', 'shipping_temporary_inventory_sessions', ['user_id', 'created_at']) + op.create_index('ix_shipping_temp_inventory_conversation_created', 'shipping_temporary_inventory_sessions', ['conversation_id', 'created_at']) + op.create_index('ix_shipping_temp_inventory_asset', 'shipping_temporary_inventory_sessions', ['asset_id']) + op.create_index('ix_shipping_temp_inventory_status_expires', 'shipping_temporary_inventory_sessions', ['status', 'expires_at']) + + +def downgrade() -> None: + """删除临时库存会话表。""" + op.drop_index('ix_shipping_temp_inventory_status_expires', table_name='shipping_temporary_inventory_sessions') + op.drop_index('ix_shipping_temp_inventory_asset', table_name='shipping_temporary_inventory_sessions') + op.drop_index('ix_shipping_temp_inventory_conversation_created', table_name='shipping_temporary_inventory_sessions') + op.drop_index('ix_shipping_temp_inventory_user_created', table_name='shipping_temporary_inventory_sessions') + op.drop_table('shipping_temporary_inventory_sessions') diff --git a/backend/migrations/versions/f98d3e4f5a6b_add_temporary_inventory_analysis_source.py b/backend/migrations/versions/f98d3e4f5a6b_add_temporary_inventory_analysis_source.py new file mode 100644 index 00000000..7980b553 --- /dev/null +++ b/backend/migrations/versions/f98d3e4f5a6b_add_temporary_inventory_analysis_source.py @@ -0,0 +1,31 @@ +"""允许库存结构分析记录标记为对话临时文件。""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f98d3e4f5a6b' +down_revision = 'f97c2d3e4f5a' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """扩展结构分析来源枚举,不改变生产快照的既有语义。""" + with op.batch_alter_table('shipping_inventory_structure_analyses') as batch_op: + batch_op.drop_constraint('ck_inventory_structure_analysis_source_kind', type_='check') + batch_op.create_check_constraint( + 'ck_inventory_structure_analysis_source_kind', + "source_kind IN ('sample_upload', 'configuration_test', 'production_snapshot', 'temporary_conversation')", + ) + + +def downgrade() -> None: + """回退时拒绝保留临时对话分析记录,再恢复旧来源枚举。""" + op.execute("DELETE FROM shipping_inventory_structure_analyses WHERE source_kind = 'temporary_conversation'") + with op.batch_alter_table('shipping_inventory_structure_analyses') as batch_op: + batch_op.drop_constraint('ck_inventory_structure_analysis_source_kind', type_='check') + batch_op.create_check_constraint( + 'ck_inventory_structure_analysis_source_kind', + "source_kind IN ('sample_upload', 'configuration_test', 'production_snapshot')", + ) diff --git a/backend/migrations/versions/f99e4f5a6b7c_add_shipping_order_extraction_audit_snapshot.py b/backend/migrations/versions/f99e4f5a6b7c_add_shipping_order_extraction_audit_snapshot.py new file mode 100644 index 00000000..5a69d8b9 --- /dev/null +++ b/backend/migrations/versions/f99e4f5a6b7c_add_shipping_order_extraction_audit_snapshot.py @@ -0,0 +1,27 @@ +"""Add frozen input snapshots and version-usage index for order extraction audits.""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'f99e4f5a6b7c' +down_revision = 'f98d3e4f5a6b' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Preserve the exact adjudicated input and accelerate Schema-version usage history queries.""" + with op.batch_alter_table('shipping_order_extractions') as batch_op: + batch_op.add_column(sa.Column('input_snapshot_json', sa.JSON(), nullable=True)) + batch_op.create_index( + 'ix_shipping_order_extractions_schema_version_created', + ['schema_version_id', 'created_at'], + ) + + +def downgrade() -> None: + """Remove the phase-four audit additions without changing existing extraction records.""" + with op.batch_alter_table('shipping_order_extractions') as batch_op: + batch_op.drop_index('ix_shipping_order_extractions_schema_version_created') + batch_op.drop_column('input_snapshot_json') diff --git a/backend/migrations/versions/fa0b1c2d3e4f_remove_inventory_field_core_flag.py b/backend/migrations/versions/fa0b1c2d3e4f_remove_inventory_field_core_flag.py new file mode 100644 index 00000000..cd30b4d1 --- /dev/null +++ b/backend/migrations/versions/fa0b1c2d3e4f_remove_inventory_field_core_flag.py @@ -0,0 +1,22 @@ +"""移除库存字段核心标记,字段能力全部由用户配置用途决定。""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'fa0b1c2d3e4f' +down_revision = 'f99e4f5a6b7c' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """删除不再参与业务判断的 is_core 字段。""" + with op.batch_alter_table('shipping_inventory_fields') as batch_op: + batch_op.drop_column('is_core') + + +def downgrade() -> None: + """仅恢复结构,不恢复任何预置字段或核心语义。""" + with op.batch_alter_table('shipping_inventory_fields') as batch_op: + batch_op.add_column(sa.Column('is_core', sa.Boolean(), nullable=False, server_default=sa.text('false'))) diff --git a/backend/migrations/versions/fb1c2d3e4f5a_remove_legacy_inventory_mapping_cache.py b/backend/migrations/versions/fb1c2d3e4f5a_remove_legacy_inventory_mapping_cache.py new file mode 100644 index 00000000..070784aa --- /dev/null +++ b/backend/migrations/versions/fb1c2d3e4f5a_remove_legacy_inventory_mapping_cache.py @@ -0,0 +1,51 @@ +"""Remove the retired task-level inventory mapping cache.""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'fb1c2d3e4f5a' +down_revision = 'fa0b1c2d3e4f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """Drop the table superseded by reusable inventory parsing profiles.""" + op.drop_table('shipping_inventory_mappings') + + +def downgrade() -> None: + """Restore only the historical table shape for migration rollback.""" + op.create_table( + 'shipping_inventory_mappings', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('customer_code', sa.String(length=64), nullable=False), + sa.Column('header_hash', sa.String(length=64), nullable=False), + sa.Column('headers_json', sa.JSON(), nullable=True), + sa.Column('field_mapping_json', sa.JSON(), nullable=False), + sa.Column('last_used_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint( + 'customer_code', + 'header_hash', + name='uq_shipping_inventory_mappings_customer_header', + ), + ) + op.create_index( + 'ix_shipping_inventory_mappings_customer_code', + 'shipping_inventory_mappings', + ['customer_code'], + ) + op.create_index( + 'ix_shipping_inventory_mappings_created_at', + 'shipping_inventory_mappings', + ['created_at'], + ) + op.create_index( + 'ix_shipping_inventory_mappings_updated_at', + 'shipping_inventory_mappings', + ['updated_at'], + ) diff --git a/backend/scripts/import_shipping_inventory_sources.py b/backend/scripts/import_shipping_inventory_sources.py new file mode 100644 index 00000000..747d48c6 --- /dev/null +++ b/backend/scripts/import_shipping_inventory_sources.py @@ -0,0 +1,167 @@ +"""Import legacy YAML inventory sources into the shipping configuration database. + +Purpose: migrate business report paths, query inputs, aliases, and warehouse policies from +``config/shipping_inventory_sources.yaml`` into the new source master data. +Dependencies: Flask app context, SQLAlchemy models, PyYAML. +Flow: reuses connections by platform and login URL, keeps all imported sources disabled, and +never imports YAML selectors or credentials because those are worker implementation/secrets. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +from typing import Any + +import yaml + +from app import create_app +from app.extensions import db +from app.models import ShippingInventorySource, ShippingRpaProfile + + +CONNECTOR_TYPES = {"dsv360": "dbs", "crane_footprint": "crane"} + + +def _source_payload(raw: dict[str, Any]) -> dict[str, Any]: + """Convert one legacy source while excluding worker-only selector configuration. + + Args: + raw: A source item from the legacy YAML document. + + Returns: + Normalized source fields suitable for ``ShippingInventorySource``. + """ + connector_type = CONNECTOR_TYPES.get(str(raw.get("connector_type") or "").strip().lower()) + if connector_type is None: + raise ValueError(f"Unsupported connector_type: {raw.get('connector_type')!r}") + navigation = raw.get("navigation") if isinstance(raw.get("navigation"), dict) else {} + parameters: list[dict[str, Any]] = [] + for parameter in raw.get("parameters") or []: + if not isinstance(parameter, dict): + continue + parameters.append({ + "name": str(parameter.get("name") or "").strip(), + "mode": str(parameter.get("mode") or "single").strip(), + "values": [str(value).strip() for value in parameter.get("values") or [] if str(value).strip()], + "required": bool(parameter.get("required", False)), + "select_all": bool(parameter.get("select_all", False)), + **({"joiner": str(parameter.get("joiner") or ",")} if str(parameter.get("mode") or "") == "multi_text" else {}), + }) + dynamic = str(raw.get("warehouse_resolution") or "").strip() == "alias_match" + return { + "source_code": str(raw["source_code"]).strip().upper(), + "display_name": str(raw.get("display_name") or raw["source_code"]).strip(), + "connector_type": connector_type, + "login_url": str(raw.get("entry_url") or "").strip(), + "warehouse_resolution_mode": "inventory_match" if dynamic else "fixed", + "fixed_warehouse_id": None if dynamic else str(raw.get("warehouse_id") or "").strip() or None, + "report_path_json": ({ + key: str(navigation.get(key) or "").strip() + for key in ("program_group", "program_label", "report_group", "report_name") + } if connector_type == "dbs" else {}), + "query_parameters_json": parameters, + "match_aliases_json": [str(alias).strip() for alias in raw.get("match_aliases") or [] if str(alias).strip()], + } + + +def _connection_for(source: dict[str, Any]) -> ShippingRpaProfile: + """Return a compatible connection, reusing configured credentials whenever possible.""" + profile = ShippingRpaProfile.query.filter_by( + connector_type=source["connector_type"], login_url=source["login_url"], + ).order_by(ShippingRpaProfile.id).first() + if profile is not None and (profile.username_ciphertext or profile.password_ciphertext): + return profile + # Legacy YAML stores the portal root while a configured DBS connection can use a portal path. + # Prefer an existing credential-bearing platform connection instead of creating an unusable duplicate. + if source["connector_type"] == "dbs": + profile = ShippingRpaProfile.query.filter_by(connector_type="dbs").filter( + (ShippingRpaProfile.username_ciphertext.is_not(None)) | (ShippingRpaProfile.password_ciphertext.is_not(None)) + ).order_by(ShippingRpaProfile.credential_updated_at.desc(), ShippingRpaProfile.id).first() + if profile is not None: + return profile + if profile is not None: + return profile + # The historical Crane connection was initially stored as DBS before source master data existed. + if source["connector_type"] == "crane": + profile = ShippingRpaProfile.query.filter_by(profile_code="CRANE").first() + if profile is not None: + profile.connector_type = "crane" + profile.login_url = source["login_url"] + return profile + code = "DBS_S360" if source["connector_type"] == "dbs" else "CRANE" + profile = ShippingRpaProfile( + profile_code=code, + display_name="DBS 平台" if source["connector_type"] == "dbs" else "Crane 平台", + connector_type=source["connector_type"], + login_url=source["login_url"], + login_config_json={"auth_mode": "password"}, + enabled=True, + ) + db.session.add(profile) + db.session.flush() + return profile + + +def import_sources(path: Path) -> tuple[int, int]: + """Idempotently insert/update YAML source master data with imported rows disabled. + + Returns: + A pair of ``(created, updated)`` counts. + """ + document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + rows = document.get("sources") if isinstance(document, dict) else None + if not isinstance(rows, list): + raise ValueError("YAML must contain a sources list") + created = updated = 0 + for raw in rows: + if not isinstance(raw, dict): + continue + data = _source_payload(raw) + profile = _connection_for(data) + source = ShippingInventorySource.query.filter_by(source_code=data["source_code"]).first() + if source is None: + source = ShippingInventorySource( + source_code=data["source_code"], display_name=data["display_name"], + connector_type=data["connector_type"], rpa_profile=profile, + warehouse_resolution_mode=data["warehouse_resolution_mode"], enabled=False, + ) + db.session.add(source) + created += 1 + else: + updated += 1 + source.display_name = data["display_name"] + source.connector_type = data["connector_type"] + source.rpa_profile = profile + source.parsing_profile_id = None + source.excel_template_id = None + source.warehouse_resolution_mode = data["warehouse_resolution_mode"] + source.fixed_warehouse_id = data["fixed_warehouse_id"] + source.report_path_json = data["report_path_json"] + source.query_parameters_json = data["query_parameters_json"] + source.match_aliases_json = data["match_aliases_json"] + source.snapshot_ttl_seconds = 86400 + # Templates are not present in legacy YAML; activation requires published bindings. + source.enabled = False + db.session.commit() + # A previous run may have created this deterministic placeholder before a configured DBS connection was found. + placeholder = ShippingRpaProfile.query.filter_by(profile_code="DBS_S360").first() + if placeholder and not placeholder.sources and not placeholder.username_ciphertext and not placeholder.password_ciphertext: + db.session.delete(placeholder) + db.session.commit() + return created, updated + + +def main() -> None: + """Run the controlled YAML import and print counts without exposing credentials.""" + parser = argparse.ArgumentParser(description="Import legacy shipping inventory sources") + parser.add_argument("--file", type=Path, default=Path("config/shipping_inventory_sources.yaml")) + args = parser.parse_args() + app = create_app() + with app.app_context(): + created, updated = import_sources(args.file) + print(f"Imported inventory sources: created={created}, updated={updated}") + + +if __name__ == "__main__": + main() diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 3f47e84f..af5e32e7 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -54,8 +54,8 @@ def _isolate_persisted_settings(monkeypatch, tmp_path): def _shipping_notice_stable_auto_config(app, request, monkeypatch): """发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。""" tmp_path = request.getfixturevalue("tmp_path") - app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue") - app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str( + app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue") + app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str( tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers" ) if request.node.get_closest_marker("auto_rpa"): @@ -132,12 +132,12 @@ def seed_task_inventory_source( compute_routing_fingerprint, extract_routing_context, ) - from app.services.shipping_notice.inventory_sources import ( - get_inventory_source, - get_inventory_sources_config_version, + from app.services.shipping_notice.inventory_source_repository import ( + get_database_inventory_source, + inventory_sources_runtime_version, ) - source = get_inventory_source(source_code) + source = get_database_inventory_source(source_code) if not source: raise ValueError(f"unknown inventory source for tests: {source_code}") from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity @@ -151,11 +151,10 @@ def seed_task_inventory_source( identity = resolution.identity task.inventory_source_code = identity.source_code 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" task.inventory_source_method = "rule_exact" - task.inventory_source_config_version = get_inventory_sources_config_version() + task.inventory_source_config_version = inventory_sources_runtime_version() task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) @@ -184,9 +183,10 @@ def inventory_xlsx_with_warehouse( warehouse_id: str, *, sku: str = "A001", + reservation_id: str = "R-1", qty: int = 1, ) -> "BytesIO": - """生成带 Warehouse ID 列的库存 Excel,供身份校验测试使用。""" + """生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。""" from io import BytesIO from openpyxl import Workbook @@ -194,8 +194,8 @@ def inventory_xlsx_with_warehouse( buf = BytesIO() wb = Workbook() ws = wb.active - ws.append(["Warehouse ID", "SKU", "Qty"]) - ws.append([warehouse_id, sku, qty]) + ws.append(["Warehouse ID", "SKU", "Reservation ID", "Qty"]) + ws.append([warehouse_id, sku, reservation_id, qty]) wb.save(buf) wb.close() buf.seek(0) @@ -220,25 +220,23 @@ def inventory_csv_with_warehouse( def batch_rpa_item_identity(task: "ShippingTask") -> dict[str, str]: - """构造 batch 成功回调 item 须携带的 Worker 身份字段。""" + """构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。""" return { "source_code": str(task.inventory_source_code or ""), - "site_id": str(task.inventory_site_id or ""), "warehouse_id": str(task.inventory_warehouse_id or ""), } def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]: - """构造定时 batch 成功回调 item 的四字段身份(与 YAML 配置一致)。""" - from app.services.shipping_notice.inventory_sources import get_inventory_source + """构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。""" + from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - source = get_inventory_source(source_code) + source = get_database_inventory_source(source_code) if not source: raise ValueError(f"unknown inventory source for tests: {source_code}") item = { "source_code": source_code, - "site_id": str(source.get("site_id") or ""), - "warehouse_id": str(source.get("warehouse_id") or ""), + "warehouse_id": str(source.get("fixed_warehouse_id") or ""), } item.update(overrides) return item @@ -258,7 +256,6 @@ def rpa_callback_payload( "file_path": str(file_path), "run_no": run_no, "source_code": task.inventory_source_code, - "site_id": task.inventory_site_id, "warehouse_id": task.inventory_warehouse_id, } @@ -281,11 +278,130 @@ def app(): app = create_app('testing') with app.app_context(): db.create_all() + _seed_test_inventory_configuration() yield app db.session.remove() db.drop_all() +def _seed_test_inventory_configuration() -> None: + """为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。""" + from app import db + from app.models import ( + ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryRoutingRule, + ShippingInventoryRoutingRuleCondition, ShippingInventorySource, ShippingRpaProfile, + ) + from app.services.shipping_notice.inventory_structure_fingerprint import ( + FINGERPRINT_VERSION, + compatibility_fingerprint, + exact_fingerprint, + structure_definition, + ) + + # 各测试显式创建所需用户字段;生产目录本身保持零预置。 + if not ShippingInventoryField.query.filter_by(field_code='part_number').first(): + db.session.add_all([ + ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10), + ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20), + ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30), + ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40), + ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100), + ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110), + ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120), + ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130), + ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140), + ]) + + db.session.flush() + inventory_fields = { + item.field_code: item + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_([ + 'part_number', 'reservation_id', 'available_qty', 'warehouse_id', + ]) + ).all() + } + field_mapping = { + str(inventory_fields['part_number'].id): 'SKU', + str(inventory_fields['reservation_id'].id): 'Reservation ID', + str(inventory_fields['available_qty'].id): 'Qty', + str(inventory_fields['warehouse_id'].id): 'Warehouse ID', + } + # 测试专用稳定字段 ID 避免全局创建订单模板,后者会破坏订单模板初始化专项测试。 + match_keys = [ + { + 'order_field_id': 'test-order-part-number', + 'inventory_field_id': str(inventory_fields['part_number'].id), + }, + { + 'order_field_id': 'test-order-reservation-id', + 'inventory_field_id': str(inventory_fields['reservation_id'].id), + }, + ] + definition = { + 'sheet_name': 'Sheet', + 'header_row_index': 1, + 'field_mapping': field_mapping, + 'match_keys': match_keys, + } + structure = structure_definition( + file_format='xlsx', sheet_name='Sheet', header_row_index=1, + headers=['Warehouse ID', 'SKU', 'Reservation ID', 'Qty'], + ) + import hashlib + import json + + checksum = hashlib.sha256( + json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() + ).hexdigest() + parsing_profile = ShippingInventoryParsingProfile( + profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published', + file_format='xlsx', definition_json=definition, checksum=checksum, + structure_definition_json=structure, + exact_structure_fingerprint=exact_fingerprint(structure), + compatibility_fingerprint=compatibility_fingerprint( + definition=structure, field_mapping=field_mapping, match_keys=match_keys, + ), + fingerprint_version=FINGERPRINT_VERSION, + ) + excel_template = ShippingExcelTemplate( + template_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published', + storage_provider='minio', storage_bucket='test', storage_key='test/runtime/template.xlsx', + original_filename='template.xlsx', + file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64, + ) + + profile = ShippingRpaProfile( + profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs', + login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'}, + ) + source = ShippingInventorySource( + source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs', + rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU', + report_path_json={ + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv', + }, + query_parameters_json=[ + {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False}, + ], + match_aliases_json=['AWSDU', 'DUB'], + enabled=True, + ) + rule = ShippingInventoryRoutingRule( + rule_code='TEST_DUB', rule_name='Test DUB route', scope='task', priority=100, + match_mode='all', status='published', action_type='add_source_candidates', + action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1, + ) + rule.conditions.append(ShippingInventoryRoutingRuleCondition( + condition_group=1, source_kind='system_fact', system_fact_key='task.destination_port', operator='equals', + expected_value_json='DUB', sequence=1, + )) + db.session.add_all([profile, parsing_profile, excel_template, source, rule]) + db.session.commit() + + @pytest.fixture def client(app): return app.test_client() diff --git a/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py new file mode 100644 index 00000000..038a2f4c --- /dev/null +++ b/backend/tests/services/admin/test_shipping_customer_lifecycle_service.py @@ -0,0 +1,280 @@ +""" +tests/services/admin/test_shipping_customer_lifecycle_service.py + +用途:验证货代客户删除资格必须覆盖业务、导入、外部来源与影子识别引用。 +依赖:客户领域模型、shipping_customer_lifecycle_service、内存数据库。 +逻辑:分别构造每类引用,断言后端统一影响结果阻断删除而识别证据仅作为可级联配置。 +""" + +from __future__ import annotations + +from datetime import date + +import pytest + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingBusinessSequence, + ShippingCase, + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerLifecycleEvent, + ShippingCustomerImportBatch, + ShippingCustomerImportRow, + ShippingCustomerShadowMatch, + ShippingCustomerShadowResolution, +) +from app.services.admin.shipping_customer_lifecycle_service import ( + delete_customer, + get_customer_lifecycle_impact, + get_customer_lifecycle_timeline, +) + + +def _customer(code: str = 'WYC') -> ShippingCustomer: + """创建可用于生命周期影响测试的最小标准客户。""" + customer = ShippingCustomer(standard_name=f'客户 {code}', short_code=code, status='active') + db.session.add(customer) + db.session.flush() + return customer + + +def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app): + """仅有识别证据的误建客户可删除,证据不应成为业务阻断引用。""" + with app.app_context(): + customer = _customer() + 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() + + impact = get_customer_lifecycle_impact(customer.id) + assert impact['can_delete'] is True + assert impact['cascade']['identifiers'] == 1 + assert not any(impact['blockers'].values()) + + +@pytest.mark.parametrize('reference_kind', [ + 'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', +]) +def test_business_and_audit_references_block_delete(app, reference_kind: str): + """每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。""" + with app.app_context(): + customer = _customer() + if reference_kind == 'case': + db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id)) + elif reference_kind == 'sequence': + db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) + elif reference_kind == 'external_ref': + db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='C-1')) + elif reference_kind in {'import_target', 'import_result'}: + batch = ShippingCustomerImportBatch( + batch_no=f'BATCH-{reference_kind}', file_name='test.xlsx', file_hash=f'{reference_kind:0<64}'[:64], + file_size=1, source_system='ERP', + ) + db.session.add(batch) + db.session.flush() + values = { + 'batch_id': batch.id, 'sheet_name': 'customers', 'row_no': 2, 'row_order': 1, + 'row_type': 'customer', 'raw_json': {}, 'normalized_json': {}, + } + if reference_kind == 'import_target': + values['target_customer_id'] = customer.id + else: + values['result_customer_id'] = customer.id + db.session.add(ShippingCustomerImportRow(**values)) + else: + # 影子引用仅需最小分辨记录;生命周期统计不要求 Candidate 外键链完整。 + resolution = ShippingCustomerShadowResolution( + candidate_id=1000 + customer.id, + intake_id=1000 + customer.id, + resolution_version='shadow-v1', status='unmatched', evidence_json=[], candidate_matches_json=[], + ) + if reference_kind == 'shadow_top': + resolution.top_customer_id = customer.id + if reference_kind == 'shadow_manual': + resolution.manual_customer_id = customer.id + db.session.add(resolution) + db.session.flush() + if reference_kind == 'shadow_match': + db.session.add(ShippingCustomerShadowMatch( + resolution_id=resolution.id, customer_id=customer.id, match_rank=1, score=60, + standard_name_snapshot=customer.standard_name, short_code_snapshot=customer.short_code, reasons_json=[], + )) + db.session.commit() + + impact = get_customer_lifecycle_impact(customer.id) + assert impact['can_delete'] is False + assert any(impact['blockers'].values()) + + +def test_lifecycle_impact_rejects_missing_customer(app): + """不存在的客户必须返回统一 not-found 错误,不能返回伪空影响结果。""" + with app.app_context(): + with pytest.raises(NotFoundError) as exc_info: + get_customer_lifecycle_impact(99999) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND' + + +def test_delete_unused_customer_cascades_identifiers_and_keeps_snapshot_audit(app): + """仅含配置证据的误建客户删除后,客户和证据消失但快照审计必须保留。""" + with app.app_context(): + customer = _customer('DEL') + db.session.add(ShippingCustomerIdentifier( + customer_id=customer.id, + identifier_type='name_alias', raw_value='Delete Me', normalized_value='DELETEME', + status='approved', source='manual', + )) + db.session.commit() + customer_id = customer.id + + result = delete_customer( + customer_id, + confirmation_short_code='del', + reason='误建客户', + actor_id=None, + ) + + assert result['deleted_customer']['short_code'] == 'DEL' + assert result['cascade']['identifiers'] == 1 + assert db.session.get(ShippingCustomer, customer_id) is None + assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=customer_id).count() == 0 + event = db.session.get(ShippingCustomerLifecycleEvent, result['lifecycle_event_id']) + assert event is not None + assert event.event_type == 'deleted' + assert event.customer_id_snapshot == customer_id + assert event.customer_short_code_snapshot == 'DEL' + assert event.reason == '误建客户' + + +@pytest.mark.parametrize('reference_kind', [ + 'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match', +]) +def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str): + """永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。""" + with app.app_context(): + customer = _customer('BLK') + if reference_kind == 'case': + db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id)) + elif reference_kind == 'sequence': + db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16))) + elif reference_kind == 'external_ref': + db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='DELETE-BLOCK')) + elif reference_kind in {'import_target', 'import_result'}: + batch = ShippingCustomerImportBatch( + batch_no=f'BATCH-DELETE-{reference_kind}', file_name='test.xlsx', + file_hash=f'delete-{reference_kind}'.ljust(64, 'x')[:64], file_size=1, source_system='ERP', + ) + db.session.add(batch) + db.session.flush() + values = { + 'batch_id': batch.id, 'sheet_name': 'customers', 'row_no': 2, 'row_order': 1, + 'row_type': 'customer', 'raw_json': {}, 'normalized_json': {}, + } + values['target_customer_id' if reference_kind == 'import_target' else 'result_customer_id'] = customer.id + db.session.add(ShippingCustomerImportRow(**values)) + else: + resolution = ShippingCustomerShadowResolution( + candidate_id=2000 + customer.id, intake_id=2000 + customer.id, + resolution_version='shadow-v1', status='unmatched', evidence_json=[], candidate_matches_json=[], + ) + if reference_kind == 'shadow_top': + resolution.top_customer_id = customer.id + if reference_kind == 'shadow_manual': + resolution.manual_customer_id = customer.id + db.session.add(resolution) + db.session.flush() + if reference_kind == 'shadow_match': + db.session.add(ShippingCustomerShadowMatch( + resolution_id=resolution.id, customer_id=customer.id, match_rank=1, score=60, + standard_name_snapshot=customer.standard_name, short_code_snapshot=customer.short_code, reasons_json=[], + )) + db.session.commit() + + with pytest.raises(ConflictError) as exc_info: + delete_customer(customer.id, confirmation_short_code='BLK', reason='尝试删除', actor_id=None) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED' + assert any(exc_info.value.details['blockers'].values()) + assert db.session.get(ShippingCustomer, customer.id) is not None + + +def test_delete_requires_current_short_code_and_reason(app): + """删除请求必须同时带当前简码和非空原因,不能仅依赖前端确认。""" + with app.app_context(): + customer = _customer('CHK') + db.session.commit() + + with pytest.raises(ValidationError) as code_error: + delete_customer(customer.id, confirmation_short_code='BAD', reason='删除', actor_id=None) + assert code_error.value.code == 'SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID' + with pytest.raises(ValidationError) as reason_error: + delete_customer(customer.id, confirmation_short_code='CHK', reason=' ', actor_id=None) + assert reason_error.value.code == 'SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED' + assert db.session.get(ShippingCustomer, customer.id) is not None + + +def test_delete_blocks_reference_created_after_preview(app): + """预检只是展示;提交删除时必须重新统计预检后新增的业务引用。""" + with app.app_context(): + customer = _customer('RCE') + db.session.commit() + preview = get_customer_lifecycle_impact(customer.id) + assert preview['can_delete'] is True + + db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id)) + db.session.commit() + with pytest.raises(ConflictError) as exc_info: + delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None) + + assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED' + assert exc_info.value.details['blockers']['business_cases'] == 1 + assert db.session.get(ShippingCustomer, customer.id) is not None + + +def test_customer_lifecycle_timeline_returns_snapshot_events(app): + """时间线按最新事件倒序返回当前客户的快照审计,不混入其他客户记录。""" + with app.app_context(): + customer = _customer('TIM') + other = _customer('OTH') + db.session.add_all([ + ShippingCustomerLifecycleEvent( + event_type='created', customer_id_snapshot=customer.id, + customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, + detail_json={'after': {'short_code': 'TIM'}}, + ), + ShippingCustomerLifecycleEvent( + event_type='created', customer_id_snapshot=other.id, + customer_name_snapshot=other.standard_name, customer_short_code_snapshot=other.short_code, + detail_json={}, + ), + ]) + db.session.commit() + + result = get_customer_lifecycle_timeline(customer.id) + assert result['customer']['id'] == customer.id + assert len(result['items']) == 1 + assert result['items'][0]['event_type'] == 'created' + + +def test_customer_lifecycle_timeline_replays_deleted_customer_snapshot(app): + """永久删除后仍能通过事件快照读取时间线,不能因主表不存在而丢失审计。""" + with app.app_context(): + customer = _customer('DEL') + db.session.commit() + delete_customer(customer.id, confirmation_short_code='DEL', reason='误建', actor_id=None) + + result = get_customer_lifecycle_timeline(customer.id) + assert result['customer'] == { + 'id': customer.id, + 'standard_name': '客户 DEL', + 'short_code': 'DEL', + 'status': 'deleted', + } + assert result['items'][0]['event_type'] == 'deleted' diff --git a/backend/tests/services/admin/test_shipping_customer_merge_service.py b/backend/tests/services/admin/test_shipping_customer_merge_service.py new file mode 100644 index 00000000..f064e00f --- /dev/null +++ b/backend/tests/services/admin/test_shipping_customer_merge_service.py @@ -0,0 +1,185 @@ +""" +tests/services/admin/test_shipping_customer_merge_service.py + +用途:验证客户归并只迁移未来配置,不改写历史业务与审计引用。 +依赖:客户模型、合并服务、内存数据库。 +逻辑:覆盖正常归并、重复证据去重、受控校验以及归并后的删除资格保护。 +""" + +from __future__ import annotations + +from datetime import date + +import pytest + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import ( + ShippingBusinessSequence, + ShippingCase, + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerLifecycleEvent, + ShippingCustomerMerge, + ShippingCustomerShadowResolution, +) +from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact +from app.services.admin.shipping_customer_merge_service import get_customer_merge_impact, merge_customer +from app.services.admin.shipping_customer_service import update_customer +from app.services.admin.shipping_customer_service import create_identifier, update_identifier +from app.services.shipping_notice.customer_identity_gate import list_customer_options +from app.services.shipping_notice.customer_shadow_resolution import label_shadow_resolution + + +def _customer(name: str, code: str, *, status: str = 'active') -> ShippingCustomer: + """创建最小客户记录,供归并两端和非法状态测试复用。""" + customer = ShippingCustomer(standard_name=name, short_code=code, status=status) + db.session.add(customer) + db.session.flush() + return customer + + +def test_merge_moves_future_configuration_and_preserves_history(app): + """归并迁移证据和来源键,但业务单、流水及其客户快照始终保留源客户。""" + with app.app_context(): + source = _customer('重复客户', 'SRC') + target = _customer('标准客户', 'TGT') + db.session.add_all([ + ShippingCustomerIdentifier( + customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias', + normalized_value='SOURCEALIAS', status='approved', source='manual', + ), + ShippingCustomerIdentifier( + customer_id=source.id, identifier_type='email', raw_value='same@example.com', + normalized_value='same@example.com', status='approved', source='manual', + ), + ShippingCustomerIdentifier( + customer_id=target.id, identifier_type='email', raw_value='same@example.com', + normalized_value='same@example.com', status='approved', source='manual', + ), + ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'), + ShippingCase( + case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601', + customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code, + ), + ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1), + ]) + db.session.commit() + source_id = source.id + target_id = target.id + + preview = get_customer_merge_impact(source_id, target_id) + assert preview['historical_references']['business_cases'] == 1 + assert preview['migrate'] == { + 'identifiers': 1, 'duplicate_identifiers': 1, 'external_references': 1, 'sites': 0, + } + + result = merge_customer( + source_id, target_customer_id=target_id, confirmation_short_code='SRC', reason='重复建档', actor_id=None, + ) + + assert result['migrate'] == { + 'identifiers': 1, 'duplicate_identifiers': 1, 'external_references': 1, 'sites': 0, + } + source_after = db.session.get(ShippingCustomer, source_id) + target_after = db.session.get(ShippingCustomer, target_id) + assert source_after is not None and source_after.status == 'merged' + assert source_after.merged_into_customer_id == target_id + assert target_after is not None and target_after.status == 'active' + assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0 + assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2 + assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1 + historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one() + assert historical_case.customer_id == source_id + assert historical_case.business_no == 'SRC26071601' + assert historical_case.customer_short_code_snapshot == 'SRC' + assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1 + merge = db.session.get(ShippingCustomerMerge, result['merge_id']) + assert merge is not None and merge.source_customer_id_snapshot == source_id + assert db.session.query(ShippingCustomerLifecycleEvent).filter_by(event_type='merged_source').count() == 1 + assert db.session.query(ShippingCustomerLifecycleEvent).filter_by(event_type='merged_target').count() == 1 + assert {item['id'] for item in list_customer_options()} == {target_id} + + +@pytest.mark.parametrize('mode', ['same', 'inactive_target', 'wrong_confirmation', 'missing_reason']) +def test_merge_rejects_invalid_request(app, mode: str): + """归并请求必须选择不同的启用目标客户,并由服务端校验简码和原因。""" + with app.app_context(): + source = _customer('源客户', 'SRC') + target = _customer('目标客户', 'TGT', status='inactive' if mode == 'inactive_target' else 'active') + db.session.commit() + kwargs = { + 'target_customer_id': source.id if mode == 'same' else target.id, + 'confirmation_short_code': 'BAD' if mode == 'wrong_confirmation' else 'SRC', + 'reason': '' if mode == 'missing_reason' else '重复', + 'actor_id': None, + } + expected = { + 'same': 'SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER', + 'inactive_target': 'SHIPPING.CUSTOMER_MERGE_TARGET_INVALID', + 'wrong_confirmation': 'SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID', + 'missing_reason': 'SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED', + }[mode] + with pytest.raises((ConflictError, ValidationError)) as exc_info: + merge_customer(source.id, **kwargs) + assert exc_info.value.code == expected + assert db.session.get(ShippingCustomer, source.id).status == 'active' + + +def test_merged_customer_cannot_be_edited_or_merged_twice_and_blocks_deletion(app): + """源客户归并后锁定,且源/目标均必须被删除资格服务拒绝。""" + with app.app_context(): + source = _customer('源客户', 'SRC') + target = _customer('目标客户', 'TGT') + db.session.commit() + merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='SRC', reason='重复', actor_id=None) + + with pytest.raises(ConflictError) as edit_error: + update_customer(source.id, {'remark': 'cannot edit'}, actor_id=None) + assert edit_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED' + with pytest.raises(ConflictError) as merge_error: + merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='SRC', reason='again', actor_id=None) + assert merge_error.value.code == 'SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED' + source_impact = get_customer_lifecycle_impact(source.id) + target_impact = get_customer_lifecycle_impact(target.id) + assert source_impact['blockers']['merged_into_customer'] == 1 + assert target_impact['blockers']['merged_source_customers'] == 1 + + +def test_merged_customer_cannot_receive_future_identifier_or_shadow_label(app): + """归并后所有新的识别入口都必须拒绝源客户,避免未来任务重新命中旧身份。""" + with app.app_context(): + source = _customer('源客户', 'SRC') + target = _customer('目标客户', 'TGT') + db.session.add(ShippingCustomerIdentifier( + customer_id=source.id, identifier_type='name_alias', raw_value='Old Alias', + normalized_value='OLDALIAS', status='approved', source='manual', + )) + db.session.commit() + merge_customer(source.id, target_customer_id=target.id, confirmation_short_code='SRC', reason='重复', actor_id=None) + + with pytest.raises(ConflictError) as create_error: + create_identifier(source.id, { + 'identifier_type': 'name_alias', 'identifier_value': 'New Alias', 'status': 'pending', + }, actor_id=None) + assert create_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED' + # 原证据已经归并至目标;直接构造源客户证据编辑场景以验证服务端防御。 + blocked_identifier = ShippingCustomerIdentifier( + customer_id=source.id, identifier_type='contact', raw_value='Old Contact', + normalized_value='OLDCONTACT', status='pending', source='manual', + ) + db.session.add(blocked_identifier) + db.session.commit() + with pytest.raises(ConflictError) as update_error: + update_identifier(blocked_identifier.id, {'status': 'approved'}, actor_id=None) + assert update_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED' + shadow = ShippingCustomerShadowResolution( + candidate_id=9000 + source.id, intake_id=9000 + source.id, + resolution_version='shadow-v1', status='unmatched', evidence_json=[], candidate_matches_json=[], + ) + db.session.add(shadow) + db.session.commit() + with pytest.raises(ConflictError) as label_error: + label_shadow_resolution(shadow.id, customer_id=source.id, actor_id=None) + assert label_error.value.code == 'SHIPPING.CUSTOMER_MERGED_LOCKED' diff --git a/backend/tests/services/admin/test_shipping_customer_service.py b/backend/tests/services/admin/test_shipping_customer_service.py index d0976df9..fdb722c4 100644 --- a/backend/tests/services/admin/test_shipping_customer_service.py +++ b/backend/tests/services/admin/test_shipping_customer_service.py @@ -13,11 +13,12 @@ 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.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent from app.services.admin.shipping_customer_service import ( create_customer, create_identifier, list_customers, + update_customer, update_identifier, ) @@ -113,7 +114,11 @@ def test_identifier_loses_auto_match_when_approval_is_revoked(app): actor_id=None, ) - updated = update_identifier(identifier['id'], {'status': 'pending'}, actor_id=None) + updated = update_identifier( + identifier['id'], + {'status': 'pending', 'reason': '识别证据失效'}, + actor_id=None, + ) assert updated['status'] == 'pending' assert updated['auto_match_allowed'] is False @@ -136,7 +141,7 @@ def test_identifier_validation_failure_does_not_leave_dirty_state(app): with pytest.raises(ValidationError) as exc_info: update_identifier( identifier['id'], - {'status': 'pending', 'auto_match_allowed': True}, + {'status': 'pending', 'auto_match_allowed': True, 'reason': '验证失败'}, actor_id=None, ) assert exc_info.value.code == 'SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED' @@ -145,6 +150,71 @@ def test_identifier_validation_failure_does_not_leave_dirty_state(app): assert persisted.auto_match_allowed is True +def test_lifecycle_events_capture_customer_and_identifier_governance_changes(app): + """客户简码、状态及证据自动授权变更必须留存前后快照和操作者原因。""" + with app.app_context(): + customer = _create_customer() + updated = update_customer( + customer['id'], + {'short_code': 'NEW', 'status': 'inactive', 'reason': '客户资料纠正'}, + actor_id=42, + ) + identifier = create_identifier( + customer['id'], + { + 'identifier_type': 'domain', + 'identifier_value': 'wyc.example.com', + 'status': 'approved', + 'auto_match_allowed': False, + }, + actor_id=42, + ) + update_identifier( + identifier['id'], + {'auto_match_allowed': True, 'reason': '人工审核后授权'}, + actor_id=42, + ) + + events = ShippingCustomerLifecycleEvent.query.order_by(ShippingCustomerLifecycleEvent.id).all() + assert [item.event_type for item in events] == ['created', 'updated', 'identifier_created', 'identifier_updated'] + assert events[1].reason == '客户资料纠正' + assert events[1].detail_json['changes']['short_code'] == {'before': 'WYC', 'after': 'NEW'} + assert events[1].detail_json['changes']['status'] == {'before': 'active', 'after': 'inactive'} + assert events[-1].reason == '人工审核后授权' + assert events[-1].detail_json['changes']['auto_match_allowed'] == {'before': False, 'after': True} + assert updated['short_code'] == 'NEW' + + +def test_high_risk_governance_changes_require_reason(app): + """简码、状态和自动匹配授权属于高风险变更,服务端不能依赖前端补原因。""" + with app.app_context(): + customer = _create_customer() + with pytest.raises(ValidationError) as customer_error: + update_customer(customer['id'], {'short_code': 'NEW'}, actor_id=None) + assert customer_error.value.code == 'SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED' + persisted_customer = db.session.get(ShippingCustomer, customer['id']) + assert persisted_customer.short_code == 'WYC' + + unchanged = update_customer(customer['id'], {'standard_name': '无锡宇辰精密有限公司'}, actor_id=None) + assert unchanged['standard_name'] == '无锡宇辰精密有限公司' + + identifier = create_identifier( + customer['id'], + { + 'identifier_type': 'domain', + 'identifier_value': 'wyc.example.com', + 'status': 'approved', + 'auto_match_allowed': False, + }, + actor_id=None, + ) + with pytest.raises(ValidationError) as identifier_error: + update_identifier(identifier['id'], {'auto_match_allowed': True}, actor_id=None) + assert identifier_error.value.code == 'SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED' + persisted_identifier = db.session.get(ShippingCustomerIdentifier, identifier['id']) + assert persisted_identifier.auto_match_allowed is False + + def test_customer_list_returns_preaggregated_reference_counts(app): """列表返回业务单和识别证据数量,避免管理端逐客户补查。""" with app.app_context(): diff --git a/backend/tests/services/admin/test_shipping_inventory_service.py b/backend/tests/services/admin/test_shipping_inventory_service.py new file mode 100644 index 00000000..07dd28dd --- /dev/null +++ b/backend/tests/services/admin/test_shipping_inventory_service.py @@ -0,0 +1,402 @@ +""" +tests/services/admin/test_shipping_inventory_service.py + +用途:验证库存主数据管理服务的安全性和关键业务约束。 +依赖:Flask app/db、shipping_inventory_service、库存配置模型。 +逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。 +""" + +from __future__ import annotations + +from cryptography.fernet import Fernet +import pytest + +from app.core.errors import ConflictError, ValidationError +from app.services.admin import shipping_inventory_service +from app.services.shipping_notice import inventory_parsing_profile +from app.services.shipping_notice.order_schema import service as order_schema_service +from app import db +from app.models import ShippingExcelTemplate, ShippingInventoryField + + +def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict: + return { + 'profile_code': code, 'display_name': code, 'connector_type': connector_type, + 'login_url': 'https://example.invalid/login', 'login_config_json': {'auth_mode': 'password'}, + 'username': 'test-user', 'password': 'test-password', 'enabled': True, + } + + +def _parsing_profile() -> dict: + """发布可由多个库存源共享的最小库存解析 Profile。""" + state = order_schema_service.get_state() + if state['schema'] is None: + order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) + fields = {item['field_code']: item for item in order_schema_service.get_state()['fields']} + for code in ('part_number', 'reservation_id'): + if code not in fields: + fields[code] = order_schema_service.save_field( + {'field_code': code, 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + if not any(item['status'] == 'published' for item in order_schema_service.get_state()['versions']): + schema_draft = order_schema_service.create_draft({}, actor_id=None) + saved_schema = order_schema_service.save_draft(schema_draft['id'], {'fields': [{ + 'field_id': field['id'], 'display_name': code, 'required': True, 'aliases': [], + 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': 'normalized_text', + 'extraction_instruction': f'提取订单行 {code}', + } for code, field in fields.items()], 'expected_lock_version': schema_draft['lock_version']}) + order_schema_service.publish( + schema_draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'], + ) + inventory_fields = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + ShippingInventoryField.status == 'active', + ).all() + } + assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'} + draft = inventory_parsing_profile.save_draft({ + 'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx', + 'definition': { + 'header_row_index': 1, + 'field_mapping': { + inventory_fields['part_number']: 'Supplier Sku', + inventory_fields['reservation_id']: 'Reservation ID', + inventory_fields['available_qty']: 'Qty Available', + }, + 'match_keys': [{ + 'order_field_id': fields['part_number']['id'], + 'inventory_field_id': inventory_fields['part_number'], + }], + }, + }, actor_id=None) + return inventory_parsing_profile.publish(draft['id'], actor_id=None) + + +def _excel_template_id() -> int: + """创建库存源绑定所需的最小已发布 Excel 模板版本。""" + current = ShippingExcelTemplate.query.filter_by(template_code='COMMON_EXPORT').first() + if current: + return current.id + current = ShippingExcelTemplate( + template_code='COMMON_EXPORT', display_name='Common Export', version=1, status='published', + storage_provider='minio', storage_bucket='test', storage_key='test/common-export.xlsx', + original_filename='template.xlsx', + file_checksum='0' * 64, definition_json={'filename_pattern': 'shipment_{task_no}.xlsx', 'mappings': []}, + definition_checksum='1' * 64, + ) + db.session.add(current) + db.session.flush() + return current.id + + +def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code: str = 'DBS_DUB', connector_type: str = 'dbs') -> dict: + return { + 'source_code': code, 'display_name': code, 'connector_type': connector_type, + 'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'], + 'excel_template_id': _excel_template_id(), + 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', + 'snapshot_ttl_seconds': 3600, 'enabled': True, + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv', + }, + 'query_parameters_json': [ + {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, + ], + 'match_aliases_json': ['DUB'], + } + + +def test_profile_credentials_are_not_returned(app): + """Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + assert payload['password_configured'] is True + assert payload['username_masked'] == 'configured' + assert 'password' not in payload + assert 'ciphertext' not in payload + + +def test_profile_rejects_page_operation_configuration(app): + """货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + payload = _profile_data() + payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}} + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_profile(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID' + + +def test_multiple_dbs_profiles_bind_independent_sources(app): + """同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) + second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None) + first_source = shipping_inventory_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None) + second_source = shipping_inventory_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None) + assert first_source['rpa_profile_id'] == first['id'] + assert second_source['rpa_profile_id'] == second['id'] + + +def test_source_rejects_profile_connector_mismatch(app): + """库存源不能绑定不同 Driver 的 Profile。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH' + + +def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): + """禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None) + payload = _source_data(login['id'], code='DRAFT_SOURCE') + payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) + draft = shipping_inventory_service.save_source(payload, actor_id=None) + assert draft['enabled'] is False + assert draft['parsing_profile_id'] is None + assert draft['excel_template_id'] is None + + payload.update({'enabled': True}) + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id']) + assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED' + + payload.update({ + 'parsing_profile_id': _parsing_profile()['id'], + 'excel_template_id': _excel_template_id(), + }) + enabled = shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id']) + assert enabled['enabled'] is True + + +def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): + """普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) + payload = _source_data(login['id'], code='ACTIVATION_SOURCE') + payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) + draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) + assert draft['activation']['ready'] is False + assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + + payload['enabled'] = True + saved = shipping_inventory_service.save_source( + payload, actor_id=None, source_id=draft['id'], allow_enable_transition=False, + ) + assert saved['enabled'] is False + + with pytest.raises(ConflictError) as exc_info: + shipping_inventory_service.activate_source(draft['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' + assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + + +def test_enabled_source_rejects_disabled_rpa_profile(app): + """启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile( + {**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None, + ) + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None) + assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED' + + +def test_dbs_source_persists_report_path_parameters_and_aliases(app): + """数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + assert source['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv' + assert source['query_parameters_json'] == [ + {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, + ] + assert source['match_aliases_json'] == ['DUB'] + + +def test_source_rejects_driver_selector_in_business_parameters(app): + """业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + payload = _source_data(profile['id']) + payload['query_parameters_json'][0]['selector_env'] = 'SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_source(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID' + + +def test_crane_source_rejects_dbs_report_path(app): + """动态仓 Crane 库存源不得误填 DBS 四级报表路径。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None) + payload = _source_data(profile['id'], code='CRANE', connector_type='crane') + payload['warehouse_resolution_mode'] = 'inventory_match' + payload['fixed_warehouse_id'] = None + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_source(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID' + + +def test_published_rule_cannot_be_mutated_in_place(app): + """发布规则必须依靠新版本演进,避免改写历史任务依据。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) + source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None) + rule = shipping_inventory_service.save_rule({ + 'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line', + 'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates', + 'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}], + }, actor_id=None) + shipping_inventory_service.publish_rule(rule['id'], actor_id=None) + with pytest.raises(ConflictError) as exc_info: + shipping_inventory_service.save_rule({ + 'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}], + }, actor_id=None, rule_id=rule['id']) + assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE' + + +def test_draft_rule_update_keeps_the_same_draft(app): + """草稿更新应原地替换条件,不能偷偷新增同版本规则记录。""" + with app.app_context(): + rule = shipping_inventory_service.save_rule({ + 'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'task', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'task.destination_port', 'operator': 'equals', 'expected_value_json': 'DUB'}], + }, actor_id=None) + updated = shipping_inventory_service.save_rule({ + 'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'task', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'task.destination_port', 'operator': 'equals', 'expected_value_json': 'FRA'}], + }, actor_id=None, rule_id=rule['id']) + assert updated['id'] == rule['id'] + assert updated['rule_name'] == 'After' + assert updated['conditions'][0]['expected_value_json'] == 'FRA' + + +def test_rule_condition_value_type_follows_the_selected_operator(app): + """列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。""" + with app.app_context(): + rule = shipping_inventory_service.save_rule({ + 'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'in', 'expected_value_json': ['1001', '1002']}], + }, actor_id=None) + assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002'] + + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_rule({ + 'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'in', 'expected_value_json': '1001'}], + }, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID' + + +def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app): + """未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) + shipping_inventory_service.delete_profile(unused['id']) + assert all(item['profile_code'] != 'UNUSED' for item in shipping_inventory_service.list_profiles()) + + profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + with pytest.raises(ConflictError) as exc_info: + shipping_inventory_service.delete_profile(profile['id']) + assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED' + with pytest.raises(ConflictError) as exc_info: + shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id']) + assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED' + + rule = shipping_inventory_service.save_rule({ + 'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '1'}], + }, actor_id=None) + shipping_inventory_service.publish_rule(rule['id'], actor_id=None) + retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None) + assert retired['status'] == 'retired' + with pytest.raises(ConflictError) as exc_info: + shipping_inventory_service.delete_draft_rule(rule['id']) + assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED' + + +def test_publish_rule_rejects_missing_or_disabled_source(app): + """发布规则只能引用启用库存源,避免运行期落入无法确认的伪候选。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) + source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None) + disabled_payload = _source_data(profile['id'], code='DISABLED_ROUTE_SOURCE') + disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) + shipping_inventory_service.save_source(disabled_payload, actor_id=None) + + for index, code in enumerate(('MISSING_SOURCE', 'DISABLED_ROUTE_SOURCE'), start=1): + rule = shipping_inventory_service.save_rule({ + 'rule_code': f'INVALID_SOURCE_{index}', 'rule_name': 'Invalid source rule', 'scope': 'line', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [code]}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': str(index)}], + }, actor_id=None) + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.publish_rule(rule['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID' + + valid_rule = shipping_inventory_service.save_rule({ + 'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line', + 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]}, + 'conditions': [{'source_kind': 'system_fact', 'system_fact_key': 'line.reservation_id', 'operator': 'prefix', 'expected_value_json': '9'}], + }, actor_id=None) + assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published' + + +def test_active_default_external_mapping_is_unique_per_source(app): + """同一库存源只能有一条启用的默认外部系统映射。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + payload = { + 'inventory_source_id': source['id'], 'external_system_code': 'TOPGP', 'external_organization_code': None, + 'external_site_code': 'EU01', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True, + } + shipping_inventory_service.save_external_mapping(payload, actor_id=None) + with pytest.raises(ConflictError): + shipping_inventory_service.save_external_mapping(payload, actor_id=None) + + +def test_external_mapping_normalizes_freight_warehouse_identity(app): + """配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + mapping = shipping_inventory_service.save_external_mapping({ + 'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub', + 'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01', + 'external_warehouse_name': 'Dublin', 'enabled': True, + }, actor_id=None) + assert mapping['freight_warehouse_id'] == 'DUB' diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index a05a620c..6473f234 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -13,6 +13,7 @@ from app.models import ( FileAsset, ShippingCase, ShippingCustomer, + ShippingCustomerIdentifier, ShippingCustomerShadowResolution, ShippingNoticeCandidate, ShippingNoticeDocument, @@ -80,29 +81,227 @@ def test_shipping_customer_admin_routes_reject_non_admin(app, client): assert parse_api_error(response.get_json())['code'] == 'AUTH.FORBIDDEN' -def test_shipping_customer_historical_backfill_api_does_not_number(app, client): - """管理员可为历史任务回填客户,且响应与业务单均不生成历史业务号。""" +def test_shipping_customer_lifecycle_impact_api_is_admin_only(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]) + customer = ShippingCustomer(standard_name='生命周期客户', short_code='LIF', status='active') + db.session.add(customer) 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}, + forbidden = client.get( + f'/api/admin/shipping-customers/{customer_id}/lifecycle-impact', + headers=_headers('shipping-user', 'user'), + ) + assert forbidden.status_code == 403 + + response = client.get( + f'/api/admin/shipping-customers/{customer_id}/lifecycle-impact', headers=_headers('shipping-admin', 'admin'), ) assert response.status_code == 200 - payload = parse_api_data(response.get_json()) - assert payload['business_no'] is None + impact = parse_api_data(response.get_json()) + assert impact['can_delete'] is True + assert impact['cascade']['identifiers'] == 0 + + +def test_shipping_customer_timeline_and_governance_quality_apis_are_admin_only(app, client): + """治理时间线和质量汇总必须复用管理员权限,并返回自动确认门禁状态。""" + app.config['AUTH_JWT_REQUIRED'] = False 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' + _create_users() + customer = ShippingCustomer(standard_name='时间线客户', short_code='TIM', status='active') + db.session.add(customer) + db.session.flush() + from app.models import ShippingCustomerLifecycleEvent + + db.session.add(ShippingCustomerLifecycleEvent( + event_type='created', customer_id_snapshot=customer.id, + customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, + detail_json={}, + )) + db.session.commit() + customer_id = customer.id + + admin_headers = _headers('shipping-admin', 'admin') + for path in ( + f'/api/admin/shipping-customers/{customer_id}/lifecycle-timeline', + '/api/admin/shipping-customers/governance-quality', + ): + forbidden = client.get(path, headers=_headers('shipping-user', 'user')) + assert forbidden.status_code == 403 + + timeline = client.get( + f'/api/admin/shipping-customers/{customer_id}/lifecycle-timeline', headers=admin_headers, + ) + assert timeline.status_code == 200 + assert parse_api_data(timeline.get_json())['items'][0]['event_type'] == 'created' + + quality = client.get('/api/admin/shipping-customers/governance-quality', headers=admin_headers) + assert quality.status_code == 200 + payload = parse_api_data(quality.get_json()) + assert payload['shadow_quality']['total'] == 0 + assert payload['shadow_quality']['auto_resolution']['quality_gate']['status'] == 'insufficient_labeled_samples' + assert payload['lifecycle_event_counts']['created'] == 1 + + +def test_shipping_customer_delete_api_is_admin_only_and_audited(app, client): + """删除 API 仅管理员可用,并在成功后保留客户快照审计。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + customer = ShippingCustomer(standard_name='可删除客户', short_code='DEL', status='active') + db.session.add(customer) + db.session.flush() + db.session.add(ShippingCustomerIdentifier( + customer_id=customer.id, identifier_type='name_alias', raw_value='Delete Customer', + normalized_value='DELETECUSTOMER', status='approved', source='manual', + )) + db.session.commit() + customer_id = customer.id + + payload = {'confirmation_short_code': 'DEL', 'reason': '误建'} + forbidden = client.delete( + f'/api/admin/shipping-customers/{customer_id}', json=payload, + headers=_headers('shipping-user', 'user'), + ) + assert forbidden.status_code == 403 + + response = client.delete( + f'/api/admin/shipping-customers/{customer_id}', json=payload, + headers=_headers('shipping-admin', 'admin'), + ) + assert response.status_code == 200 + deleted = parse_api_data(response.get_json()) + assert deleted['deleted_customer']['id'] == customer_id + assert deleted['cascade']['identifiers'] == 1 + + missing = client.get(f'/api/admin/shipping-customers/{customer_id}', headers=_headers('shipping-admin', 'admin')) + assert missing.status_code == 404 + + +def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(app, client): + """API 必须校验二次确认,并在删除提交时返回完整阻断明细。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active') + db.session.add(customer) + db.session.flush() + db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id)) + db.session.commit() + customer_id = customer.id + + headers = _headers('shipping-admin', 'admin') + invalid = client.delete( + f'/api/admin/shipping-customers/{customer_id}', + json={'confirmation_short_code': 'BAD', 'reason': '误建'}, headers=headers, + ) + assert invalid.status_code == 400 + assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID' + + blocked = client.delete( + f'/api/admin/shipping-customers/{customer_id}', + json={'confirmation_short_code': 'BLK', 'reason': '误建'}, headers=headers, + ) + assert blocked.status_code == 409 + error = parse_api_error(blocked.get_json()) + assert error['code'] == 'SHIPPING.CUSTOMER_DELETE_BLOCKED' + assert error['details']['blockers']['business_cases'] == 1 + + +def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(app, client): + """管理员归并客户时仅迁移未来证据,源客户历史业务仍保持原关联。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + source = ShippingCustomer(standard_name='重复客户', short_code='SRC', status='active') + target = ShippingCustomer(standard_name='标准客户', short_code='TGT', status='active') + db.session.add_all([source, target]) + db.session.flush() + db.session.add_all([ + ShippingCustomerIdentifier( + customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias', + normalized_value='SOURCEALIAS', status='approved', source='manual', + ), + ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'), + ]) + db.session.commit() + source_id = source.id + target_id = target.id + + admin_headers = _headers('shipping-admin', 'admin') + forbidden = client.post( + f'/api/admin/shipping-customers/{source_id}/merge', + json={'target_customer_id': target_id, 'confirmation_short_code': 'SRC', 'reason': '重复建档'}, + headers=_headers('shipping-user', 'user'), + ) + assert forbidden.status_code == 403 + + preview = client.get( + f'/api/admin/shipping-customers/{source_id}/merge-impact?target_customer_id={target_id}', + headers=admin_headers, + ) + assert preview.status_code == 200 + assert parse_api_data(preview.get_json())['historical_references']['business_cases'] == 1 + + response = client.post( + f'/api/admin/shipping-customers/{source_id}/merge', + json={'target_customer_id': target_id, 'confirmation_short_code': 'SRC', 'reason': '重复建档'}, + headers=admin_headers, + ) + assert response.status_code == 200 + result = parse_api_data(response.get_json()) + assert result['source']['id'] == source_id + assert result['target']['id'] == target_id + with app.app_context(): + assert db.session.get(ShippingCustomer, source_id).status == 'merged' + assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1 + assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id + + +def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client): + """合并 API 由服务端校验目标状态、源简码与原因,不能依赖前端限制。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + source = ShippingCustomer(standard_name='源客户', short_code='SRC', status='active') + target = ShippingCustomer(standard_name='停用目标', short_code='TGT', status='inactive') + db.session.add_all([source, target]) + db.session.commit() + source_id = source.id + target_id = target.id + + headers = _headers('shipping-admin', 'admin') + invalid_target = client.post( + f'/api/admin/shipping-customers/{source_id}/merge', + json={'target_customer_id': target_id, 'confirmation_short_code': 'SRC', 'reason': '重复'}, headers=headers, + ) + assert invalid_target.status_code == 400 + assert parse_api_error(invalid_target.get_json())['code'] == 'SHIPPING.CUSTOMER_MERGE_TARGET_INVALID' + + empty_reason = client.post( + f'/api/admin/shipping-customers/{source_id}/merge', + json={'target_customer_id': source_id, 'confirmation_short_code': 'SRC', 'reason': ''}, headers=headers, + ) + assert empty_reason.status_code == 400 + assert parse_api_error(empty_reason.get_json())['code'] == 'SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED' + + +def test_shipping_customer_historical_backfill_api_is_not_registered(app, client): + """新契约不保留历史客户回填入口,管理员也不能调用。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + + response = client.post( + '/api/admin/shipping-customers/historical-task-backfill', + json={'task_no': 'SN-20200101-HISTAPI', 'customer_id': 1}, + headers=_headers('shipping-admin', 'admin'), + ) + assert response.status_code == 404 def test_shipping_customer_shadow_report_and_label_api(app, client): diff --git a/backend/tests/test_admin_shipping_inventory.py b/backend/tests/test_admin_shipping_inventory.py new file mode 100644 index 00000000..9ee5e850 --- /dev/null +++ b/backend/tests/test_admin_shipping_inventory.py @@ -0,0 +1,178 @@ +""" +tests/test_admin_shipping_inventory.py + +用途:验证货代库存后台的只读快照/导出记录接口及管理员权限。 +依赖:Flask 测试客户端、库存文件和排程运行模型。 +逻辑:库存快照来自库存文件;没有库存文件的失败 RPA 运行也必须出现在导出记录中。 +""" + +from __future__ import annotations + +from datetime import datetime +from pathlib import Path + +from app import db +from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, User +from app.models import ShippingInventorySource, ShippingRpaProfile +from app.services.shipping_notice.order_schema import service as order_schema_service +from tests.conftest import parse_api_data, parse_api_error + + +def _create_users() -> None: + """创建接口权限验证所需的管理员和普通用户。""" + db.session.add_all([ + User(username='inventory-admin', email='inventory-admin@example.com', role='admin', status='active'), + User(username='inventory-user', email='inventory-user@example.com', role='user', status='active'), + ]) + db.session.commit() + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造遗留 Header 认证上下文,匹配现有管理 API 测试方式。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_path): + """快照和导出记录仅管理员可读,且失败排程不因无库存文件而丢失。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + snapshot_file = Path(tmp_path) / 'snapshot.xlsx' + snapshot_file.write_bytes(b'admin-snapshot') + file_record = ShippingInventoryFile( + inventory_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB', + warehouse_id='DUB', snapshot_status='ready', identity_status='verified', + exported_at=datetime(2026, 7, 17, 10, 0, 0), rpa_run_no='RUN-READY-01', + ) + schedule_task = ScheduleTask( + schedule_no='SCH-INVENTORY-FAILED', name='Inventory Export', schedule_type='platform_job', + owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='shipping-inventory-rpa', + ) + db.session.add_all([file_record, schedule_task]) + db.session.flush() + db.session.add(ScheduleRun( + run_no='RUN-FAILED-01', schedule_task_id=schedule_task.id, status='failed', + api_request_json={'run_no': 'RUN-FAILED-01', 'source_codes': ['CRANE']}, + error_message='login timeout', created_at=datetime(2026, 7, 17, 11, 0, 0), + )) + db.session.commit() + + for path in ('/api/admin/shipping-notice/snapshots', '/api/admin/shipping-notice/export-records'): + forbidden = client.get(path, headers=_headers('inventory-user', 'user')) + assert forbidden.status_code == 403 + assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN' + + snapshots = client.get('/api/admin/shipping-notice/snapshots', headers=_headers('inventory-admin', 'admin')) + assert snapshots.status_code == 200 + snapshot_rows = parse_api_data(snapshots.get_json()) + assert snapshot_rows[0]['inventory_file_no'] == 'SIF-ADMIN-READY' + assert 'storage_path' not in snapshot_rows[0] + assert snapshot_rows[0]['download_available'] is True + + downloaded = client.get('/api/admin/shipping-notice/snapshots/1/download', headers=_headers('inventory-admin', 'admin')) + assert downloaded.status_code == 200 + assert downloaded.data == b'admin-snapshot' + + exports = client.get('/api/admin/shipping-notice/export-records', headers=_headers('inventory-admin', 'admin')) + assert exports.status_code == 200 + export_rows = parse_api_data(exports.get_json()) + failed_row = next(item for item in export_rows if item['rpa_run_no'] == 'RUN-FAILED-01') + assert failed_row['snapshot_status'] == 'failed' + assert failed_row['source_code'] == 'CRANE' + assert failed_row['error_message'] == 'login timeout' + + +def test_inventory_configuration_catalog_is_admin_only_and_backend_controlled(app, client): + """结构化配置目录仅管理员可读,字段和白名单均来自当前后端契约。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = order_schema_service.save_field({ + 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + draft = order_schema_service.create_draft({}, actor_id=None) + saved = order_schema_service.save_draft(draft['id'], {'fields': [{ + 'field_id': field['id'], 'display_name': '内部料号', 'required': True, + 'aliases': [], 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': 'normalized_text', + 'extraction_instruction': '提取内部料号', + }], 'expected_lock_version': draft['lock_version']}) + order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + + path = '/api/admin/shipping-notice/configuration-catalog' + forbidden = client.get(path, headers=_headers('inventory-user', 'user')) + assert forbidden.status_code == 403 + + response = client.get(path, headers=_headers('inventory-admin', 'admin')) + assert response.status_code == 200 + catalog = parse_api_data(response.get_json()) + assert catalog['order_fields'][0]['field_id'] == field['id'] + assert {'内部料号', '预约号', '可用库存数量'} <= { + field['display_name'] for field in catalog['inventory_fields'] + } + assert {'order_field', 'inventory_field', 'system_fact', 'constant'} == set(catalog['template_source_kinds']) + assert {'header', 'line'} == set(catalog['template_row_modes']) + assert 'decimal' in catalog['template_formatters'] + + +def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app, client): + """订单字段尚未发布时,库存配置页应得到空目录而不是将前置条件误报为 500。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + + for path in ( + '/api/admin/shipping-notice/routing-fields', + '/api/admin/shipping-notice/configuration-catalog', + ): + response = client.get(path, headers=_headers('inventory-admin', 'admin')) + assert response.status_code == 200 + catalog = parse_api_data(response.get_json()) + assert catalog['order_schema_published'] is False + assert catalog['order_fields'] == [] + + +def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_missing_steps(app, client): + """管理端普通保存不允许跳过测试直接启用,独立启用接口应返回业务缺失项。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + profile = ShippingRpaProfile( + profile_code='API_ACTIVATION_LOGIN', display_name='API Activation', connector_type='dbs', + login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True, + ) + db.session.add(profile) + db.session.commit() + profile_id = profile.id + + payload = { + 'source_code': 'API_ACTIVATION_SOURCE', 'display_name': 'API Activation Source', 'connector_type': 'dbs', + 'rpa_profile_id': profile_id, 'parsing_profile_id': None, 'excel_template_id': None, + 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600, + 'enabled': True, + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand', + }, + 'query_parameters_json': [], 'match_aliases_json': [], + } + created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin')) + assert created.status_code == 201 + source = parse_api_data(created.get_json()) + assert source['enabled'] is False + assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + + activation = client.post( + f"/api/admin/shipping-notice/sources/{source['id']}/activate", + json={}, headers=_headers('inventory-admin', 'admin'), + ) + assert activation.status_code == 409 + error = parse_api_error(activation.get_json()) + assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' + assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] diff --git a/backend/tests/test_admin_shipping_order_schema_history.py b/backend/tests/test_admin_shipping_order_schema_history.py new file mode 100644 index 00000000..022ebd48 --- /dev/null +++ b/backend/tests/test_admin_shipping_order_schema_history.py @@ -0,0 +1,101 @@ +""" +backend/tests/test_admin_shipping_order_schema_history.py + +用途:验证订单 Schema 历史版本分页和只读快照 API。 +依赖:Flask 管理 API、订单 Schema service、测试用户模型。 +逻辑:创建连续发布版本后,历史列表仅返回概要;详情固定读取发布快照并保持权限边界。 +""" + +from __future__ import annotations + +from app import db +from app.models import User +from app.services.shipping_notice.order_schema import service +from tests.conftest import parse_api_data, parse_api_error + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造管理 API 使用的遗留 Header 身份。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +def _config(field_id: str, *, display_name: str) -> dict: + """构造可发布的 Header 文本字段规则。""" + return { + 'field_id': field_id, + 'display_name': display_name, + 'required': True, + 'aliases': ['PO'], + 'normalizer_key': 'trim', + 'validator_keys': ['non_empty'], + 'enum_options': [], + 'evidence_policy': { + 'required': True, + 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', + 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'normalized_text', + 'extraction_instruction': '提取采购订单号', + } + + +def _publish_version(field_id: str, *, display_name: str, source_version_id: int | None = None) -> dict: + """创建、保存并发布一个版本,返回不可变发布快照。""" + draft = service.create_draft( + {'copy_from_version_id': source_version_id} if source_version_id else {}, actor_id=1, + ) + saved = service.save_draft(draft['id'], { + 'fields': [_config(field_id, display_name=display_name)], + 'expected_lock_version': draft['lock_version'], + }, actor_id=1) + return service.publish(draft['id'], actor_id=1, expected_lock_version=saved['lock_version']) + + +def test_admin_can_list_and_view_immutable_schema_history(app, client): + """历史列表分页返回概要,详情固定返回版本快照且普通用户无权访问。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + db.session.add_all([ + User(id=1, username='schema-history-admin', email='schema-history-admin@example.com', role='admin', status='active', real_name='版本管理员'), + User(id=2, username='schema-history-user', email='schema-history-user@example.com', role='user', status='active'), + ]) + db.session.commit() + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1) + field = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=1) + first = _publish_version(field['id'], display_name='采购订单号') + second = _publish_version(field['id'], display_name='客户订单号', source_version_id=first['id']) + service.save_field({ + 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', + }, actor_id=1, field_id=field['id']) + + forbidden = client.get('/api/admin/shipping-order-schema/versions', headers=_headers('schema-history-user', 'user')) + assert forbidden.status_code == 403 + assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN' + + response = client.get('/api/admin/shipping-order-schema/versions?page=1&page_size=1', headers=_headers('schema-history-admin', 'admin')) + assert response.status_code == 200 + page = parse_api_data(response.get_json()) + assert page['total'] == 2 + assert page['items'][0]['id'] == second['id'] + assert 'definition' not in page['items'][0] + assert page['items'][0]['published_by']['display_name'] == '版本管理员' + + exact = client.get('/api/admin/shipping-order-schema/versions?version_number=1', headers=_headers('schema-history-admin', 'admin')) + assert exact.status_code == 200 + assert parse_api_data(exact.get_json())['items'][0]['id'] == first['id'] + + first_detail = client.get( + f"/api/admin/shipping-order-schema/versions/{first['id']}", headers=_headers('schema-history-admin', 'admin'), + ) + assert first_detail.status_code == 200 + definition = parse_api_data(first_detail.get_json())['definition'] + assert definition['fields'][0]['display_name'] == '采购订单号' + assert definition['fields'][0]['field_code'] == 'po_number' + + state = client.get('/api/admin/shipping-order-schema', headers=_headers('schema-history-admin', 'admin')) + assert state.status_code == 200 + assert [item['status'] for item in parse_api_data(state.get_json())['versions']] == ['published'] diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index a4dbf619..83a0df3e 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -203,6 +203,50 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkey assert "run.failed" not in event_names +def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch): + """任务级库存附件必须进入 formal upload handler,而不是临时对话库存会话。""" + from io import BytesIO + + user = _create_user() + agent = _create_shipping_agent() + task_no = _create_task_for_user(user.id) + captured: dict[str, object] = {} + + def fake_upload_inventory(received_task_no, upload): + captured['task_no'] = received_task_no + captured['filename'] = upload.filename + captured['content'] = upload.read() + return { + 'status': 'ok', 'message': '库存文件已按发布方案解析。', + 'data': {'schema_preview': {'headers': ['Supplier Sku']}, 'inventory_file_no': 'SIF-TURN-001'}, + } + + monkeypatch.setattr( + 'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_inventory_file', + fake_upload_inventory, + ) + res = client.post( + '/api/chat/turns/stream', + headers={'X-Username': user.username, 'X-Role': user.role}, + data={ + 'agent_id': str(agent.id), + 'input': json.dumps({ + 'type': 'upload_followup', 'display_text': '上传库存文件:task.xls', + 'action_type': 'shipping.upload_inventory', 'payload': {'task_no': task_no}, + }, ensure_ascii=False), + 'files': (BytesIO(b'legacy-inventory'), 'task.xls'), + }, + content_type='multipart/form-data', + ) + + assert res.status_code == 200 + events = _parse_sse_events(res.get_data(as_text=True)) + assert 'run.failed' not in [item.get('event') for item in events] + assert captured == {'task_no': task_no, 'filename': 'task.xls', 'content': b'legacy-inventory'} + assistant_payloads = [item.get('data', {}).get('payload', {}) for item in events if item.get('event') == 'message.completed'] + assert all('schema_preview' not in payload for payload in assistant_payloads) + + def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path): """shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。""" from io import BytesIO diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index 1e99ba1a..b52a4819 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -32,13 +32,11 @@ def test_fill_parameters_skips_warehouse(monkeypatch): "parameters": [ { "name": "Warehouse", - "selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", "mode": "single", "values": ["TZR2"], }, { "name": "Owner", - "selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "mode": "single", "values": ["OWNER1"], }, @@ -49,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch): select_or_fill=_fake_select, ) - assert calls == [("FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")] + assert calls == [("SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")] def test_build_schedule_description_uses_short_uuid_hex(monkeypatch): @@ -75,7 +73,7 @@ def test_build_schedule_description_hex_len_env(): text = module._build_schedule_description( {"source_code": "CRANE_TZR2"}, None, - env=lambda name, default="": "16" if name == "FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default, + env=lambda name, default="": "16" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default, ) assert len(text) == 16 @@ -114,7 +112,7 @@ def test_export_scheduled_report_flow(monkeypatch): result = module.export_crane_inventory_report( page, - {"navigation": {"download_mode": "scheduled_report"}, "parameters": [], "source_code": "CRANE_TZR2"}, + {"parameters": [], "source_code": "CRANE_TZR2"}, trigger={"task_no": "SN-1001"}, env=lambda name, default="": default, browser_timeout_ms=5_000, @@ -128,8 +126,8 @@ def test_export_scheduled_report_flow(monkeypatch): assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST" -def test_should_run_report_before_schedule_defaults_true(): - """默认必须先 Run Report;仅显式 run_before_schedule=false 可关闭。""" +def test_should_run_report_before_schedule_uses_driver_environment_only(): + """默认必须先 Run Report;业务配置不得关闭 Driver 步骤。""" module = _load_export() assert ( module._should_run_report_before_schedule( @@ -143,12 +141,12 @@ def test_should_run_report_before_schedule_defaults_true(): {"navigation": {"run_before_schedule": False}}, env=lambda name, default="": default, ) - is False + is True ) assert ( module._should_run_report_before_schedule( {"navigation": {}}, - env=lambda name, default="": "false" if name == "FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE" else default, + env=lambda name, default="": "false" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default, ) is False ) @@ -430,17 +428,18 @@ def test_is_crane_login_blocking_ignores_login_flash_when_table_visible(): session.is_crane_login_page = original -def test_resolve_scheduled_report_file_name_prefers_navigation_config(): - """scheduled_report_file_name 应优先于环境变量默认值。""" +def test_resolve_scheduled_report_file_name_ignores_source_navigation(): + """调度报表文件名是 Driver 模板策略,不读 Source navigation。""" module = _load_export() name = module._resolve_scheduled_report_file_name( {"navigation": {"scheduled_report_file_name": "Custom.xlsx"}}, env=lambda name, default="": default, ) - assert name == "Custom.xlsx" + assert name == "OnHandDetails.xlsx" -def test_resolve_download_mode_defaults_to_scheduled_report(): - """未配置 download_mode 时默认走 scheduled_report。""" +def test_resolve_download_mode_uses_driver_environment_only(): + """下载模式只能由 Driver 环境变量决定。""" module = _load_export() - assert module._resolve_download_mode({"navigation": {}}) == "scheduled_report" + assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report" + assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download" diff --git a/backend/tests/test_crane_session.py b/backend/tests/test_crane_session.py index 8bb24ca4..090f4b52 100644 --- a/backend/tests/test_crane_session.py +++ b/backend/tests/test_crane_session.py @@ -108,15 +108,15 @@ def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monke module.maybe_auto_login_crane( page, env=lambda name, default="": { - "FREIGHT_RPA_CRANE_USERNAME": "crane-user", - "FREIGHT_RPA_CRANE_PASSWORD": "crane-pass", + "SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user", + "SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass", }.get(name, default), browser_timeout_ms=5_000, ) assert calls == [ - ("FREIGHT_RPA_CRANE_USERNAME_SELECTOR", "crane-user"), - ("FREIGHT_RPA_CRANE_PASSWORD_SELECTOR", "crane-pass"), + ("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"), + ("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"), ] @@ -133,7 +133,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch): locator = module._find_crane_sign_in_button( page, - selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR", + selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR", env=lambda name, default="": default, browser_timeout_ms=3_000, ) diff --git a/backend/tests/test_dsv_export_batch_smoke.py b/backend/tests/test_dsv_export_batch_smoke.py deleted file mode 100644 index 8815199c..00000000 --- a/backend/tests/test_dsv_export_batch_smoke.py +++ /dev/null @@ -1,74 +0,0 @@ -"""scripts/rpa/dsv_export_batch_smoke.py 轻量单测(退出码与 REQUIRE_EXPORT 开关)。""" - -from __future__ import annotations - -import importlib.util -from pathlib import Path - - -def _repo_root() -> Path: - return Path(__file__).resolve().parents[2] - - -def _load_dsv_export_batch_smoke(): - module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py" - spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_under_test", module_path) - assert spec is not None - assert spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def _load_freight_rpa_worker(): - module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke_exit_test", module_path) - assert spec is not None - assert spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def test_resolve_smoke_scenario_exit_code_all_skipped_default_passes(): - """默认不要求导出时,全 skipped 应退出 0。""" - smoke = _load_dsv_export_batch_smoke() - worker = _load_freight_rpa_worker() - results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}] - summary = worker._summarize_inventory_batch_results(results) - assert smoke._resolve_smoke_scenario_exit_code( - results=results, - summary=summary, - require_export=False, - ) == 0 - - -def test_resolve_smoke_scenario_exit_code_all_skipped_require_export_fails(): - """FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2。""" - smoke = _load_dsv_export_batch_smoke() - worker = _load_freight_rpa_worker() - results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}] - summary = worker._summarize_inventory_batch_results(results) - assert summary["status"] == "success" - assert summary["has_success"] is False - assert smoke._resolve_smoke_scenario_exit_code( - results=results, - summary=summary, - require_export=True, - ) == 2 - - -def test_resolve_smoke_scenario_exit_code_has_success_with_require_export(): - """require_export=true 但已有 success 导出时仍应退出 0。""" - smoke = _load_dsv_export_batch_smoke() - worker = _load_freight_rpa_worker() - results = [ - {"source_code": "A", "status": "success", "success": True}, - {"source_code": "B", "status": "skipped", "success": False, "skipped": True}, - ] - summary = worker._summarize_inventory_batch_results(results) - assert smoke._resolve_smoke_scenario_exit_code( - results=results, - summary=summary, - require_export=True, - ) == 0 diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index 36f4315b..bf6f091b 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -43,7 +43,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input(): module.fill_dsv_filter_if_needed( _FakePage(), - "FREIGHT_RPA_DSV_OWNER_SELECTOR", + "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", "CADU-0000000100", env=lambda name, default="": default, @@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue(): module.fill_dsv_filter_if_needed( _FakePage(), - "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", + "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", "BYAWSATL01", env=lambda name, default="": default, diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py index 69553915..26e5550d 100644 --- a/backend/tests/test_freight_rpa_heartbeat.py +++ b/backend/tests/test_freight_rpa_heartbeat.py @@ -22,7 +22,7 @@ def _load_freight_rpa_heartbeat_module(): def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch): module = _load_freight_rpa_heartbeat_module() - monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") payload = module.build_heartbeat_payload( trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers", drop_dir=r"C:\HxopsRpaTest\data\inventory_drop", @@ -33,15 +33,15 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch): def test_resolve_shared_scope_id_from_trigger_path(monkeypatch): module = _load_freight_rpa_heartbeat_module() - monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False) monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False) monkeypatch.setenv( - "FREIGHT_RPA_INVENTORY_TRIGGER_DIR", + "SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", r"C:\HxopsRpaTest\data\inventory_triggers", ) assert module._resolve_shared_scope_id() == "" monkeypatch.setenv( - "FREIGHT_RPA_INVENTORY_TRIGGER_DIR", + "SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", r"C:\mount\hxops-rpa-test-data\inventory_triggers", ) assert module._resolve_shared_scope_id() == "hxops-rpa-test-data" @@ -52,7 +52,7 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch): trigger_dir = tmp_path / "inventory_triggers" trigger_dir.mkdir() - monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01") sentinel = trigger_dir / ".hxops_rpa_shared_mount" diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index b11c93cc..a7b8ea18 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -16,6 +16,7 @@ import sys from pathlib import Path import pytest +from cryptography.fernet import Fernet from openpyxl import load_workbook @@ -33,16 +34,6 @@ def _load_freight_rpa_worker(): return module -def _load_dsv_export_batch_smoke(): - module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_batch_smoke.py" - spec = importlib.util.spec_from_file_location("dsv_export_batch_smoke_worker_test", module_path) - assert spec is not None - assert spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - def _build_inventory_export_trigger(task_no: str) -> dict[str, object]: """构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。""" return { @@ -72,20 +63,96 @@ def test_env_strips_wrapping_quotes(monkeypatch): """RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。""" worker = _load_freight_rpa_worker() - monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"user@example.com"') - monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "'secret-pass'") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"') + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'") - assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "user@example.com" - assert worker._env("FREIGHT_RPA_DSV_PASSWORD") == "secret-pass" + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com" + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "secret-pass" + + +def test_worker_accepts_business_connector_without_site_id(): + """数据库 Source 的 dbs/crane 业务类型不应要求已删除的 site_id 字段。""" + worker = _load_freight_rpa_worker() + worker._validate_inventory_source_for_rpa({ + "source_code": "DBS_DUB", "connector_type": "dbs", "warehouse_id": "DUB", + }) + worker._validate_inventory_source_for_rpa({ + "source_code": "CRANE", "connector_type": "crane", + }) + + +def test_worker_groups_same_connector_by_rpa_profile(): + """同 connector 的不同 Profile 必须分组,防止错误复用登录态。""" + worker = _load_freight_rpa_worker() + grouped = worker._group_batch_sources_by_profile([ + {"source_code": "DBS_DUB", "connector_type": "dbs", "rpa_profile_code": "DBS_EU_A"}, + {"source_code": "DBS_RTM", "connector_type": "dbs", "rpa_profile_code": "DBS_EU_B"}, + ]) + assert set(grouped) == {("dsv360", "DBS_EU_A"), ("dsv360", "DBS_EU_B")} + + +def test_worker_keeps_same_profile_sources_in_one_session_group(): + """同一登录连接的多个 Source 可复用登录会话,不与其他 Profile 混用。""" + worker = _load_freight_rpa_worker() + grouped = worker._group_batch_sources_by_profile([ + {'source_code': 'DBS_DUB', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_EU_A'}, + {'source_code': 'DBS_RTM', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_EU_A'}, + {'source_code': 'DBS_CMH', 'connector_type': 'dbs', 'rpa_profile_code': 'DBS_US_B'}, + ]) + assert [item['source_code'] for item in grouped[('dsv360', 'DBS_EU_A')]] == ['DBS_DUB', 'DBS_RTM'] + assert [item['source_code'] for item in grouped[('dsv360', 'DBS_US_B')]] == ['DBS_CMH'] + + +def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch): + """worker 解密 Profile 密文后必须在退出执行范围时恢复原有环境。""" + worker = _load_freight_rpa_worker() + key = Fernet.generate_key() + cipher = Fernet(key) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii")) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False) + monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False) + monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False) + source = { + "connector_type": "dbs", + "credential_envelope": { + "username_ciphertext": cipher.encrypt(b"test-user").decode("ascii"), + "password_ciphertext": cipher.encrypt(b"test-password").decode("ascii"), + }, + } + with worker._profile_credentials(source): + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user" + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password" + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "" + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "" + + +def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch): + """新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。""" + worker = _load_freight_rpa_worker() + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + monkeypatch.setenv("FREIGHT_RPA_MOCK", "true") + + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false" + + +def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch): + """规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。""" + worker = _load_freight_rpa_worker() + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False) + monkeypatch.setenv("FREIGHT_RPA_MOCK", "true") + + with pytest.warns(DeprecationWarning, match="FREIGHT_RPA_MOCK is deprecated"): + assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "true" def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys): - """配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。""" + """配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。""" worker = _load_freight_rpa_worker() log_path = tmp_path / "logs" / "worker.log" timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ") - monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path)) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path)) original_stdout = sys.stdout original_stderr = sys.stderr @@ -116,14 +183,14 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path): - """日志超过 FREIGHT_RPA_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。""" + """日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。""" worker = _load_freight_rpa_worker() log_path = tmp_path / "worker.log" log_path.write_text("current-log", encoding="utf-8") Path(f"{log_path}.1").write_text("old-1", encoding="utf-8") - monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1") - monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "2") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2") worker._rotate_log_file_if_needed(log_path) @@ -138,8 +205,8 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp log_path = tmp_path / "worker.log" log_path.write_text("current-log", encoding="utf-8") - monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1") - monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "0") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0") worker._rotate_log_file_if_needed(log_path) @@ -171,10 +238,10 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): def start(self): return _FakePlaywright() - monkeypatch.delenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", raising=False) - monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "true") - monkeypatch.delenv("FREIGHT_RPA_BROWSER_CHANNEL", raising=False) - monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true") + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False) + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) temp_roots: list[Path] = [] @@ -209,7 +276,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa """profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。""" worker = _load_freight_rpa_worker() monkeypatch.setenv( - "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "data/shipping_notice/freight_rpa/browser_profile", ) @@ -222,7 +289,7 @@ def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch): """本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。""" worker = _load_freight_rpa_worker() monkeypatch.setenv( - "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/freight_rpa/browser_profile", ) @@ -235,7 +302,7 @@ def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatc """本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。""" worker = _load_freight_rpa_worker() monkeypatch.setenv( - "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"), ) @@ -265,7 +332,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path out_file.write_bytes(b"fake inventory content") return out_file - monkeypatch.setenv("FREIGHT_RPA_MOCK", "false") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) @@ -312,8 +379,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat processed_dir = trigger_dir / "processed" callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("FREIGHT_RPA_MOCK", "true") - monkeypatch.delenv("FREIGHT_RPA_SAMPLE_INVENTORY", raising=False) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir) @@ -363,7 +430,7 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p def raise_no_inventory(_trigger: dict, _drop: Path): raise worker.NoInventoryDataError("DSV report has no inventory data") - monkeypatch.setenv("FREIGHT_RPA_MOCK", "false") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) @@ -447,37 +514,14 @@ def test_summarize_inventory_batch_item_empty_dict_counts_as_failed(): assert summary["success"] is False -def test_summarize_inventory_batch_results_all_skipped_smoke_exit_success(): - """全 skipped 时 summary status=success,smoke 应退出 0(链路正常、无 Excel)。""" +def test_summarize_inventory_batch_results_all_skipped_is_success(): + """全 skipped 代表链路正常但无库存,不得误报为批量导出失败。""" worker = _load_freight_rpa_worker() results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}] summary = worker._summarize_inventory_batch_results(results) assert summary["status"] == "success" assert summary["has_success"] is False assert summary["status"] not in {"failed", "partial_failed"} - smoke = _load_dsv_export_batch_smoke() - assert smoke._resolve_smoke_scenario_exit_code( - results=results, - summary=summary, - require_export=False, - ) == 0 - - -def test_summarize_inventory_batch_results_all_skipped_require_export_smoke_exit_fail(): - """FREIGHT_RPA_SMOKE_REQUIRE_EXPORT=true 时,全 skipped 应退出 2(无 Excel 导出)。""" - worker = _load_freight_rpa_worker() - smoke = _load_dsv_export_batch_smoke() - results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}] - summary = worker._summarize_inventory_batch_results(results) - assert summary["status"] == "success" - assert summary["has_success"] is False - assert smoke._resolve_smoke_scenario_exit_code( - results=results, - summary=summary, - require_export=True, - ) == 2 - - def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path): """真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。""" worker = _load_freight_rpa_worker() @@ -503,10 +547,10 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat def start(self): return _FakePlaywright() - monkeypatch.setenv("FREIGHT_RPA_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) - monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false") - monkeypatch.setenv("FREIGHT_RPA_BROWSER_CHANNEL", "msedge") - monkeypatch.delenv("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH", raising=False) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge") + monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads") @@ -1004,7 +1048,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input(): worker._fill_dsv_filter_if_needed( _FakePage(), - "FREIGHT_RPA_DSV_OWNER_SELECTOR", + "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", "CADU-0000000100", ) @@ -1159,26 +1203,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_ """ 手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。 - 默认跳过;仅当 FREIGHT_RPA_E2E=true 时执行。执行前需准备账号密码: - - FREIGHT_RPA_MOCK=false - - FREIGHT_RPA_HEADLESS=false(建议首次调试) - - FREIGHT_RPA_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录> - - FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD + 默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码: + - SHIPPING_NOTICE_RPA_WORKER_MOCK=false + - SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试) + - SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录> + - SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD """ - if str(os.getenv("FREIGHT_RPA_E2E") or "").strip().lower() != "true": - pytest.skip("set FREIGHT_RPA_E2E=true to run real freight RPA export") + if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true": + pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export") worker = _load_freight_rpa_worker() trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77") drop_dir = tmp_path / "drop" drop_dir.mkdir() - monkeypatch.setenv("FREIGHT_RPA_MOCK", "false") - if not os.getenv("FREIGHT_RPA_HEADLESS"): - monkeypatch.setenv("FREIGHT_RPA_HEADLESS", "false") - if not os.getenv("FREIGHT_RPA_BROWSER_PROFILE_DIR"): + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"): + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") + if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"): monkeypatch.setenv( - "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "browser_profile"), ) diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index 84a8c3cd..f564a6f2 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -42,12 +42,12 @@ def test_fill_report_parameter_multi_select(monkeypatch): page, { "name": "Warehouse", - "selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", + "selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "mode": "multi_select", "values": ["WH1", "WH2"], }, ) - assert calls == [("FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])] + assert calls == [("SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])] def test_fill_report_parameter_multi_select_with_select_all(monkeypatch): @@ -67,29 +67,22 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch): } ) - selectors = { - "text": "#ReportViewerMain_ctl08_ctl17_txtValue", - "toggle": "#ReportViewerMain_ctl08_ctl17_ctl01", - "dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown", - } monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi) worker._fill_report_parameter( page, { "name": "Warehouse", - "selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", - "mode": "multi_select", - "select_all": True, - "selectors": selectors, - "values": ["RTM"], + "mode": "multi_select", + "select_all": True, + "values": ["RTM"], }, ) assert calls == [ { - "selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", + "selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "label": "Warehouse", "values": ["RTM"], - "selectors": selectors, + "selectors": None, "select_all": True, } ] diff --git a/backend/tests/test_init_local_db.py b/backend/tests/test_init_local_db.py new file mode 100644 index 00000000..9aee62e9 --- /dev/null +++ b/backend/tests/test_init_local_db.py @@ -0,0 +1,78 @@ +""" +tests/test_init_local_db.py + +用途:验证本地 SQLite 初始化脚本只操作显式目标,并安全区分空库、版本库与未知旧库。 +依赖:init_local_db.py、SQLite、Alembic 迁移目录、subprocess。 +逻辑:使用临时路径执行真实脚本;检查全新库版本标记和种子数据,并确认未知旧库被拒绝且字节不变。 +""" + +from __future__ import annotations + +import os +import sqlite3 +import subprocess +import sys +from pathlib import Path + + +BACKEND_DIR = Path(__file__).resolve().parents[1] +SCRIPT_PATH = BACKEND_DIR / 'init_local_db.py' + + +def _run_initializer(database_path: Path) -> subprocess.CompletedProcess[str]: + """ + 在隔离 SQLite 路径运行真实初始化脚本。 + + Args: + database_path: 测试专用数据库文件,禁止指向仓库默认 local_test.db。 + + Returns: + 捕获标准输出和错误输出的子进程结果。 + """ + env = os.environ.copy() + env['HXOPS_LOCAL_DATABASE_PATH'] = str(database_path) + env['FIXED_ASSETS_SYNC_ENABLED'] = 'false' + return subprocess.run( + [sys.executable, str(SCRIPT_PATH)], + cwd=BACKEND_DIR, + env=env, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + + +def test_init_local_db_creates_isolated_current_schema(tmp_path): + """全新隔离库应初始化、标记 Alembic head,并写入最小本地账号。""" + database_path = tmp_path / 'isolated-local.db' + + result = _run_initializer(database_path) + + assert result.returncode == 0, result.stderr + assert database_path.is_file() + with sqlite3.connect(database_path) as connection: + version = connection.execute('SELECT version_num FROM alembic_version').fetchone() + admin = connection.execute( + "SELECT username, role FROM users WHERE username = 'admin'", + ).fetchone() + agent_count = connection.execute('SELECT COUNT(*) FROM agents').fetchone()[0] + assert version is not None and version[0] + assert admin == ('admin', 'admin') + assert int(agent_count) == 1 + + +def test_init_local_db_refuses_unversioned_database_without_modifying_it(tmp_path): + """已有业务表但无 Alembic 版本的数据库必须原样拒绝,不能静默 stamp 或删库。""" + database_path = tmp_path / 'legacy-local.db' + with sqlite3.connect(database_path) as connection: + connection.execute('CREATE TABLE legacy_orders (id INTEGER PRIMARY KEY, code TEXT NOT NULL)') + connection.execute("INSERT INTO legacy_orders (code) VALUES ('KEEP-ME')") + connection.commit() + before = database_path.read_bytes() + + result = _run_initializer(database_path) + + assert result.returncode == 2 + assert 'Refusing to modify legacy unversioned database' in result.stderr + assert database_path.read_bytes() == before diff --git a/backend/tests/test_internal_jobs_registry.py b/backend/tests/test_internal_jobs_registry.py index ce6ad068..5abdfe5e 100644 --- a/backend/tests/test_internal_jobs_registry.py +++ b/backend/tests/test_internal_jobs_registry.py @@ -9,7 +9,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat """POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): from app import db diff --git a/backend/tests/test_inventory_configuration_test.py b/backend/tests/test_inventory_configuration_test.py new file mode 100644 index 00000000..804a8744 --- /dev/null +++ b/backend/tests/test_inventory_configuration_test.py @@ -0,0 +1,238 @@ +"""验证库存站点测试导出的隔离、结构识别和解析方案确认。""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import patch + +import pytest +from cryptography.fernet import Fernet +from openpyxl import Workbook + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import ( + ShippingInventoryConfigurationTestRun, + ShippingInventoryExternalMapping, + ShippingExcelTemplate, + ShippingExcelTemplate, + ShippingInventoryFile, + ShippingInventoryField, + ShippingInventorySource, +) +from app.services.admin import shipping_inventory_service +from app.services.shipping_notice import ( + inventory_configuration_test, + inventory_parsing_profile, + inventory_structure_analysis, +) +from app.services.shipping_notice.order_schema import service as order_schema_service + + +def _inventory_field_id(field_code: str) -> str: + """获取测试显式创建的用户库存字段 ID。""" + return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id) + + +def _workbook(path: Path) -> None: + """生成模拟 RPA 下载完成的最小库存 Excel。""" + workbook = Workbook() + sheet = workbook.active + sheet.append(['Supplier Sku', 'Reservation ID', 'Qty Available']) + sheet.append(['PN-1', '1000140351', 9]) + workbook.save(path) + + +def _source() -> dict: + """创建一个保持停用的 DBS 库存站点。""" + login = shipping_inventory_service.save_profile({ + 'profile_code': 'TEST_EXPORT_LOGIN', 'display_name': 'Test Login', 'connector_type': 'dbs', + 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, + 'username': 'user', 'password': 'password', 'enabled': True, + }, actor_id=None) + return shipping_inventory_service.save_source({ + 'source_code': 'TEST_EXPORT_SOURCE', 'display_name': 'Test Export Source', 'connector_type': 'dbs', + 'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None, + 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600, + 'enabled': False, + 'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'}, + 'query_parameters_json': [], 'match_aliases_json': [], + }, actor_id=None) + + +def _published_order_field() -> str: + """创建测试解析方案所需的已发布订单明细字段。""" + order_schema_service.initialize_schema({'display_name': 'Configuration Test'}, actor_id=None) + field = order_schema_service.save_field({ + 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + draft = order_schema_service.create_draft({}, actor_id=None) + saved = order_schema_service.save_draft(draft['id'], {'fields': [{ + 'field_id': field['id'], 'display_name': '料号', 'required': True, 'aliases': [], + 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True}, + 'relation_role': None, 'comparator_key': 'normalized_text', 'extraction_instruction': '提取料号', + }], 'expected_lock_version': draft['lock_version']}) + order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + return field['id'] + + +def _publish_profile_from_analysis(analysis_id: int, field_id: str, *, code: str) -> dict: + """从测试分析创建并发布方案,模拟管理员确认解析配置的前置动作。""" + analysis = inventory_structure_analysis.get_analysis(analysis_id) + draft = inventory_structure_analysis.create_profile_draft(analysis_id, { + 'profile_code': code, 'display_name': code, 'sheet_name': 'Sheet', 'header_row_index': 1, + 'field_mapping': { + _inventory_field_id('part_number'): 'Supplier Sku', + _inventory_field_id('reservation_id'): 'Reservation ID', + _inventory_field_id('available_qty'): 'Qty Available', + }, + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}], + }, actor_id=None) + return inventory_parsing_profile.publish(draft['id'], actor_id=None) + + +def _complete_test_run(source: dict, tmp_path: Path) -> dict: + """完成一次模拟 RPA 测试导出,返回可供确认的测试运行。""" + started = inventory_configuration_test.start_test_export(source['id'], actor_id=None) + result_file = tmp_path / f"{started['run_no']}.xlsx" + _workbook(result_file) + return inventory_configuration_test.report_test_export({ + 'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file), + }) + + +def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path): + """测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(), patch( + 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', + ): + source = _source() + started = inventory_configuration_test.start_test_export(source['id'], actor_id=None) + assert started['status'] == 'awaiting_rpa' + assert inventory_configuration_test.start_test_export(source['id'], actor_id=None)['run_no'] == started['run_no'] + result_file = tmp_path / 'rpa-result.xlsx' + _workbook(result_file) + completed = inventory_configuration_test.report_test_export({ + 'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file), + }) + assert completed['status'] == 'completed' + assert completed['stage'] == 'ready_for_confirmation' + assert not ShippingInventoryFile.query.count() + assert ShippingInventoryConfigurationTestRun.query.count() == 1 + + +def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path): + """确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(), patch( + 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', + ): + source = _source() + completed = _complete_test_run(source, tmp_path) + profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_CONFIRMED') + + confirmed = inventory_configuration_test.confirm_test_profile( + source['id'], completed['run_no'], profile['id'], actor_id=None, + ) + + assert confirmed['parsing_profile_id'] == profile['id'] + source_model = db.session.get(ShippingInventorySource, source['id']) + assert source_model.parsing_profile_id == profile['id'] + assert 'configuration_test' not in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] + assert 'warehouse_mapping' in shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] + + db.session.add(ShippingInventoryExternalMapping( + inventory_source_id=source['id'], freight_warehouse_id='DUB', external_system_code='TOPGP', + external_warehouse_code='DUB-01', external_warehouse_name='Dublin', enabled=True, + )) + template = ShippingExcelTemplate( + template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published', + storage_bucket='test', storage_key='activation.xlsx', original_filename='activation.xlsx', + file_checksum='0' * 64, + definition_json={'filename_pattern': '{business_no}.xlsx', 'mappings': [{ + 'sheet': 'Sheet', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, + 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('part_number'), 'formatter': 'text', + }]}, definition_checksum='1' * 64, + ) + db.session.add(template) + db.session.flush() + source_model.excel_template_id = template.id + db.session.commit() + assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True + assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True + + +def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path): + """正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(), patch( + 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', + ): + source = _source() + completed = _complete_test_run(source, tmp_path) + profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_STALE') + + current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id']) + shipping_inventory_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id']) + with pytest.raises(ConflictError) as stale: + inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None) + assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE' + + source_model = db.session.get(ShippingInventorySource, source['id']) + source_model.parsing_profile_id = profile['id'] + template = ShippingExcelTemplate( + template_code='TEST_ENABLED', display_name='Test Enabled', version=1, status='published', + storage_bucket='test', storage_key='test.xlsx', original_filename='test.xlsx', + file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64, + ) + db.session.add(template) + db.session.flush() + source_model.excel_template_id = template.id + source_model.enabled = True + db.session.commit() + with pytest.raises(ConflictError) as enabled: + inventory_configuration_test.start_test_export(source['id'], actor_id=None) + assert enabled.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID' + + +def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path): + """失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(), patch( + 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', + ): + source = _source() + failed = inventory_configuration_test.start_test_export(source['id'], actor_id=None) + result = inventory_configuration_test.report_test_export({ + 'run_no': failed['run_no'], 'status': 'failed', 'error_message': 'RPA login failed', + }) + assert result['status'] == 'failed' + assert not ShippingInventoryFile.query.count() + + completed = _complete_test_run(source, tmp_path) + field_id = _published_order_field() + _publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED') + unrelated = inventory_parsing_profile.save_draft({ + 'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx', + 'definition': { + 'sheet_name': 'Other', 'header_row_index': 1, + 'field_mapping': { + _inventory_field_id('part_number'): 'Other Part', + _inventory_field_id('reservation_id'): 'Other Reservation', + _inventory_field_id('available_qty'): 'Other Qty', + }, + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}], + }, + }, actor_id=None) + unrelated = inventory_parsing_profile.publish(unrelated['id'], actor_id=None) + with pytest.raises(ValidationError) as rejected: + inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], unrelated['id'], actor_id=None) + assert rejected.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID' + assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None diff --git a/backend/tests/test_inventory_field_catalog.py b/backend/tests/test_inventory_field_catalog.py new file mode 100644 index 00000000..4e902811 --- /dev/null +++ b/backend/tests/test_inventory_field_catalog.py @@ -0,0 +1,68 @@ +""" +用途:验证库存字段目录零预置、用户字段维护和引用保护。 +依赖:inventory_field_catalog、库存字段 ORM 与统一测试应用上下文。 +逻辑:目录初始为空;用户字段未引用时可删除,引用后用途和数据格式受保护。 +""" + +import pytest + +from app.core.errors import ConflictError +from app import db +from app.models import ShippingInventoryField +from app.models import ShippingInventoryParsingProfile +from app.services.shipping_notice import inventory_field_catalog + + +def test_catalog_is_empty_until_user_creates_fields(app): + """新环境不得由迁移或服务自动创建任何具体库存字段。""" + with app.app_context(): + ShippingInventoryField.query.delete() + db.session.commit() + assert inventory_field_catalog.list_fields() == [] + + +def test_extension_field_can_be_created_updated_and_deleted(app): + """未被下游配置引用的扩展字段可完整维护,不需要再改 Python 白名单。""" + with app.app_context(): + created = inventory_field_catalog.create_field({ + 'display_name': '原产国', 'description': '货品原产地国家或地区。', + 'value_type': 'text', 'usage_type': 'general', 'sort_order': 200, + }, actor_id=None) + updated = inventory_field_catalog.update_field(created['id'], { + 'display_name': '原产国家', 'description': '货品原产地国家或地区。', + 'value_type': 'text', 'usage_type': 'general', 'sort_order': 210, + }, actor_id=None) + assert updated['display_name'] == '原产国家' + assert updated['sort_order'] == 210 + assert inventory_field_catalog.delete_field(created['id']) == {'action': 'deleted'} + assert db.session.get(ShippingInventoryField, created['id']) is None + + +def test_extension_field_referenced_by_parsing_profile_cannot_be_deleted_or_retired(app): + """解析方案已引用用户字段时,目录服务阻止删除、停用和改变能力用途。""" + with app.app_context(): + extension = ShippingInventoryField( + field_code='batch_no', display_name='库存批号', value_type='text', + usage_type='general', status='active', sort_order=100, + ) + db.session.add(extension) + db.session.flush() + db.session.add(ShippingInventoryParsingProfile( + profile_code='REFERENCE_FIELD', display_name='Reference field', version=1, + status='draft', file_format='xlsx', + definition_json={'field_mapping': {str(extension.id): 'Batch No'}, 'match_keys': []}, + )) + db.session.commit() + for operation, code in ( + (inventory_field_catalog.delete_field, 'SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED'), + (inventory_field_catalog.retire_field, 'SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED'), + ): + with pytest.raises(ConflictError) as error: + operation(extension.id) + assert error.value.code == code + with pytest.raises(ConflictError) as update_error: + inventory_field_catalog.update_field(extension.id, { + 'display_name': '库存批号', 'description': '', + 'value_type': 'decimal', 'usage_type': 'inventory_quantity', 'sort_order': 100, + }, actor_id=None) + assert update_error.value.code == 'SHIPPING.INVENTORY_FIELD_IMMUTABLE' diff --git a/backend/tests/test_inventory_parsing_profile.py b/backend/tests/test_inventory_parsing_profile.py new file mode 100644 index 00000000..e6f87ecf --- /dev/null +++ b/backend/tests/test_inventory_parsing_profile.py @@ -0,0 +1,214 @@ +""" +用途:验证可复用库存解析 Profile 的版本、共享绑定和订单字段匹配键门禁。 +依赖:inventory_parsing_profile、shipping_inventory_service、订单 Schema 服务。 +逻辑:发布一个 Profile 后绑定多个 Source;新版本并存且旧绑定稳定,非法字段、退役引用或非发布绑定被拒绝。 +""" + +from cryptography.fernet import Fernet +import pytest + +from app.core.errors import ValidationError +from app.services.admin import shipping_inventory_service +from app.services.shipping_notice import inventory_parsing_profile +from app.services.shipping_notice.order_schema import service as order_schema_service +from app import db +from app.models import ShippingExcelTemplate, ShippingInventoryField + + +def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]: + """以库存字段目录 ID 构造解析映射,禁止测试继续模拟旧字段编码配置。""" + rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()} + return { + str(rows['part_number'].id): part, + str(rows['reservation_id'].id): reservation, + str(rows['available_qty'].id): quantity, + } + + +def _part_number_field_id() -> str: + """返回内部料号目录 ID,作为订单明细匹配键的库存端引用。""" + return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id) + + +def _published_profile() -> dict: + """创建含 part_number 匹配键的 published 解析 Profile。""" + order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) + field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + schema_draft = order_schema_service.create_draft({}, actor_id=None) + saved_schema = order_schema_service.save_draft(schema_draft['id'], { + 'fields': [_schema_field_config(field['id'])], + 'expected_lock_version': schema_draft['lock_version'], + }) + order_schema_service.publish( + schema_draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'], + ) + draft = inventory_parsing_profile.save_draft({ + 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx', + 'definition': { + 'header_row_index': 1, + 'field_mapping': _inventory_mapping(), + 'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}], + }, + }, actor_id=None) + return inventory_parsing_profile.publish(draft['id'], actor_id=None) + + +def _schema_field_config(field_id: str) -> dict: + """构造库存匹配测试使用的最小可发布订单行字段规则。""" + return { + 'field_id': field_id, 'display_name': '内部料号', 'required': True, 'aliases': [], + 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': 'normalized_text', + 'extraction_instruction': '提取订单行内部料号', + } + + +def _source(profile_id: int, parsing_id: int, code: str) -> dict: + """构造绑定共享解析 Profile 的 DBS 库存源。""" + return { + 'source_code': code, 'display_name': code, 'connector_type': 'dbs', + 'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_id, + 'excel_template_id': _excel_template_id(), + 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': code, + 'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'}, + 'query_parameters_json': [], 'match_aliases_json': [], 'snapshot_ttl_seconds': 3600, 'enabled': True, + } + + +def _excel_template_id() -> int: + """创建本组 Source 绑定共享的最小已发布发货模板。""" + item = ShippingExcelTemplate.query.filter_by(template_code='COMMON_EXPORT').first() + if item: + return item.id + item = ShippingExcelTemplate( + template_code='COMMON_EXPORT', display_name='Common Export', version=1, status='published', + storage_provider='minio', storage_bucket='test', storage_key='test/common-export.xlsx', + original_filename='template.xlsx', + file_checksum='0' * 64, definition_json={'filename_pattern': 'shipment_{task_no}.xlsx', 'mappings': []}, + definition_checksum='1' * 64, + ) + db.session.add(item) + db.session.flush() + return item.id + + +def test_published_parsing_profile_can_be_shared_by_sources(app): + """同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + parsing = _published_profile() + login = shipping_inventory_service.save_profile({ + 'profile_code': 'DBS_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs', + 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, + 'username': 'u', 'password': 'p', 'enabled': True, + }, actor_id=None) + first = shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None) + second = shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None) + + assert first['parsing_profile_id'] == parsing['id'] + assert second['parsing_profile_id'] == parsing['id'] + assert inventory_parsing_profile.list_profiles()[0]['source_count'] == 2 + + +def test_source_rejects_draft_parsing_profile(app): + """库存源只能绑定 published Profile,避免运行期读取可变草稿。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) + field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + draft = inventory_parsing_profile.save_draft({ + 'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': { + 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), + 'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}], + }, + }, actor_id=None) + login = shipping_inventory_service.save_profile({ + 'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs', + 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, + 'username': 'u', 'password': 'p', 'enabled': True, + }, actor_id=None) + with pytest.raises(ValidationError) as exc_info: + shipping_inventory_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED' + + +def test_csv_parsing_profile_rejects_worksheet_configuration(app): + """CSV 没有工作表语义,保存 Profile 时不得接受会被运行期忽略的 sheet_name。""" + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) + field = order_schema_service.save_field({ + 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + with pytest.raises(ValidationError) as exc_info: + inventory_parsing_profile.save_draft({ + 'profile_code': 'CSV_SHEET', 'display_name': 'CSV Sheet', 'file_format': 'csv', + 'definition': { + 'sheet_name': 'Inventory', 'header_row_index': 1, + 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), + 'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}], + }, + }, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID' + + +def test_new_published_version_does_not_retire_bound_version(app): + """发布新版本不得使现有库存源绑定的旧 published 版本失效。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + first = _published_profile() + field_id = order_schema_service.get_state()['fields'][0]['id'] + second_draft = inventory_parsing_profile.save_draft({ + 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx', + 'definition': { + 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}], + }, + }, actor_id=None) + second = inventory_parsing_profile.publish(second_draft['id'], actor_id=None) + assert first['id'] != second['id'] + assert {item['status'] for item in inventory_parsing_profile.list_profiles()} == {'published'} + + +def test_referenced_published_profile_cannot_be_retired(app): + """已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + parsing = _published_profile() + login = shipping_inventory_service.save_profile({ + 'profile_code': 'RETIRE_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs', + 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, + 'username': 'u', 'password': 'p', 'enabled': True, + }, actor_id=None) + shipping_inventory_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None) + with pytest.raises(Exception) as exc_info: + inventory_parsing_profile.retire(parsing['id']) + assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED' + + +def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app): + """解析 Profile 不得发布仍引用旧 Schema 字段的匹配键。""" + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) + old_field = order_schema_service.save_field({'field_code': 'old_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + new_field = order_schema_service.save_field({'field_code': 'new_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + first = order_schema_service.create_draft({}, actor_id=None) + saved_schema = order_schema_service.save_draft(first['id'], { + 'fields': [_schema_field_config(new_field['id'])], 'expected_lock_version': first['lock_version'], + }) + order_schema_service.publish( + first['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'], + ) + profile = inventory_parsing_profile.save_draft({ + 'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field', + 'definition': { + 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), + 'match_keys': [{'order_field_id': old_field['id'], 'inventory_field_id': _part_number_field_id()}], + }, + }, actor_id=None) + with pytest.raises(ValidationError) as exc_info: + inventory_parsing_profile.publish(profile['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID' diff --git a/backend/tests/test_inventory_profile_matching.py b/backend/tests/test_inventory_profile_matching.py new file mode 100644 index 00000000..ecbcedea --- /dev/null +++ b/backend/tests/test_inventory_profile_matching.py @@ -0,0 +1,105 @@ +""" +tests/test_inventory_profile_matching.py + +用途:验证库存文件结构指纹与已发布解析方案的确定性复用推荐。 +依赖:库存结构分析、库存解析方案、订单字段 Schema 服务。 +逻辑:库存数据内容和文件名不参与判断;完全一致与兼容变化只产生管理员建议,绝不自动绑定库存站点。 +""" + +from __future__ import annotations + +from io import BytesIO + +from openpyxl import Workbook +from werkzeug.datastructures import FileStorage + +from app.services.shipping_notice import inventory_parsing_profile, inventory_structure_analysis +from app.services.shipping_notice.order_schema import service as order_schema_service +from app.models import ShippingInventoryField + + +def _part_number_inventory_field_id() -> str: + """返回测试用户创建的匹配字段 ID。""" + return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id) + + +def _upload(*, qty: int, extra_column: bool = False) -> FileStorage: + """构造结构相同但库存数据不同的样本,可选增加无关栏位。""" + stream = BytesIO() + workbook = Workbook() + sheet = workbook.active + headers = ['Supplier Sku', 'Reservation ID', 'Qty Available'] + if extra_column: + headers.append('Last Export Time') + sheet.append(headers) + row = ['PN-001', '1000140351', qty] + if extra_column: + row.append('2026-07-17 10:00') + sheet.append(row) + workbook.save(stream) + stream.seek(0) + return FileStorage(stream=stream, filename=f'inventory-{qty}.xlsx') + + +def _field_id() -> str: + """创建当前已发布订单契约中的内部料号字段。""" + order_schema_service.initialize_schema({'display_name': 'Matching'}, actor_id=None) + field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + draft = order_schema_service.create_draft({}, actor_id=None) + saved = order_schema_service.save_draft(draft['id'], {'fields': [{ + 'field_id': field['id'], 'display_name': '内部料号', 'required': True, 'aliases': [], + 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, + 'relation_role': None, 'comparator_key': 'normalized_text', 'extraction_instruction': '提取内部料号', + }], 'expected_lock_version': draft['lock_version']}) + order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + return field['id'] + + +def _published_profile(field_id: str) -> dict: + """通过一次真实分析创建并发布含结构指纹的库存文件解析方案。""" + analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=9), actor_id=None) + draft = inventory_structure_analysis.create_profile_draft(analysis['id'], { + 'profile_code': 'SHARED_INVENTORY', 'display_name': '共享库存文件', 'sheet_name': 'Sheet', 'header_row_index': 1, + 'field_mapping': { + _part_number_inventory_field_id(): 'Supplier Sku', + str(ShippingInventoryField.query.filter_by(field_code='reservation_id').one().id): 'Reservation ID', + str(ShippingInventoryField.query.filter_by(field_code='available_qty').one().id): 'Qty Available', + }, + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_inventory_field_id()}], + }, actor_id=None) + return inventory_parsing_profile.publish(draft['id'], actor_id=None) + + +def test_same_structure_with_different_data_recommends_exact_profile(app, tmp_path): + """库存数量变化不影响模板判断,同表头结构必须推荐同一已发布方案。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + profile = _published_profile(_field_id()) + analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=999), actor_id=None) + result = analysis['match_result'] + assert result['status'] == 'exact' + assert result['candidates'][0]['profile_id'] == profile['id'] + + +def test_added_non_critical_column_recommends_compatible_profile(app, tmp_path): + """新增无关栏位可推荐已有方案,但不伪装为完全相同结构。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + profile = _published_profile(_field_id()) + analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=12, extra_column=True), actor_id=None) + candidate = analysis['match_result']['candidates'][0] + assert analysis['match_result']['status'] == 'compatible' + assert candidate['profile_id'] == profile['id'] + assert 'last export time' in candidate['difference']['added_columns'] + + +def test_adopting_recommendation_does_not_bind_inventory_source(app, tmp_path): + """管理员采用推荐方案只留下分析审计,不能在样本上传阶段修改任何库存站点。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + profile = _published_profile(_field_id()) + analysis = inventory_structure_analysis.create_sample_upload(_upload(qty=10), actor_id=None) + adopted = inventory_structure_analysis.adopt_published_profile(analysis['id'], profile['id']) + assert adopted['match_result']['adopted_profile_id'] == profile['id'] + assert profile['source_count'] == 0 diff --git a/backend/tests/test_inventory_structure_analysis.py b/backend/tests/test_inventory_structure_analysis.py new file mode 100644 index 00000000..3b1a09f1 --- /dev/null +++ b/backend/tests/test_inventory_structure_analysis.py @@ -0,0 +1,170 @@ +""" +tests/test_inventory_structure_analysis.py + +用途:验证库存样本的后端结构分析、真实表头约束和解析方案草稿创建。 +依赖:openpyxl、inventory_structure_analysis、订单字段 Schema 服务。 +逻辑:管理端上传样本后必须由后端决定工作表和来源栏位;草稿创建只能引用分析出的真实栏位。 +""" + +from __future__ import annotations + +from io import BytesIO +from pathlib import Path + +from openpyxl import Workbook +from werkzeug.datastructures import FileStorage +import pytest + +from app.core.errors import ValidationError +from app.services.shipping_notice import inventory_structure_analysis +from app.services.shipping_notice.order_schema import service as order_schema_service +from app.models import ShippingInventoryField + + +def _field_id(field_code: str) -> str: + """返回测试显式创建的用户库存字段 ID。""" + return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id) + + +def _mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]: + """使用字段目录 ID 构造样本解析映射。""" + return { + _field_id('part_number'): part, + _field_id('reservation_id'): reservation, + _field_id('available_qty'): quantity, + } + + +def _inventory_upload() -> FileStorage: + """构造带标题行和库存表头的 xlsx 样本,覆盖候选表头识别。""" + stream = BytesIO() + workbook = Workbook() + cover = workbook.active + cover.title = 'Cover' + cover['A1'] = 'Inventory report' + sheet = workbook.create_sheet('Inventory') + sheet.append(['AWS Inventory Report']) + sheet.append([]) + sheet.append(['Supplier Sku', 'Reservation ID', 'Qty Available', 'Warehouse ID', 'ODM ID']) + sheet.append(['PN-001', '1000140351', 9, 'AWSDU', '0000000574']) + sheet.append(['PN-002', '1000140352', 11, 'AWSDU', '0000000574']) + workbook.save(stream) + stream.seek(0) + return FileStorage(stream=stream, filename='inventory-sample.xlsx') + + +def _published_part_number() -> str: + """建立草稿创建所需的已发布订单明细字段并返回稳定字段 ID。""" + order_schema_service.initialize_schema({'display_name': 'Inventory Analysis'}, actor_id=None) + field = order_schema_service.save_field({ + 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + draft = order_schema_service.create_draft({}, actor_id=None) + saved = order_schema_service.save_draft(draft['id'], {'fields': [{ + 'field_id': field['id'], 'display_name': '内部料号', 'required': True, 'aliases': [], + 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': 'normalized_text', + 'extraction_instruction': '提取内部料号', + }], 'expected_lock_version': draft['lock_version']}) + order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + return field['id'] + + +def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path): + """上传样本必须定位真实库存表头,并仅返回少量样例和值类型统计。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None) + assert result['file_format'] == 'xlsx' + assert result['structure']['selected_sheet_name'] == 'Inventory' + assert result['structure']['selected_header_row_index'] == 3 + # 用户字段名称与来源表头不同,后端不得通过内置业务词典擅自猜测。 + assert result['suggested_mapping'] == {} + columns = result['structure']['selected_columns'] + qty = next(column for column in columns if column['header'] == 'Qty Available') + assert qty['inferred_type'] == 'number' + assert qty['sample_values'] == ['9', '11'] + + +def test_sample_analysis_reads_legacy_xls(app, tmp_path): + """旧 xls 样本必须走 xlrd 分析并保留其真实文件格式,不能要求用户先转换。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + template = Path(__file__).resolve().parents[1] / 'templates' / 'maintenance_record_history_template.xls' + with app.app_context(): + upload = FileStorage(stream=BytesIO(template.read_bytes()), filename='legacy-inventory.xls') + result = inventory_structure_analysis.create_sample_upload(upload, actor_id=None) + + assert result['file_format'] == 'xls' + assert result['structure']['selected_headers'] + + +def test_profile_draft_rejects_source_header_not_present_in_analysis(app, tmp_path): + """草稿不能提交浏览器伪造的来源栏位,必须只使用分析结果中的真实表头。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + field_id = _published_part_number() + analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None) + with pytest.raises(ValidationError) as exc_info: + inventory_structure_analysis.create_profile_draft(analysis['id'], { + 'profile_code': 'INVALID_HEADERS', 'display_name': 'Invalid', + 'sheet_name': 'Inventory', 'header_row_index': 3, + 'field_mapping': _mapping(part='Made Up'), + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}], + }, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID' + + +def test_profile_draft_rejects_duplicate_source_header(app, tmp_path): + """同名来源栏位不能作为映射目标,避免运行期按第一列静默解析。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + field_id = _published_part_number() + stream = BytesIO() + workbook = Workbook() + sheet = workbook.active + sheet.append(['Supplier Sku', 'Supplier Sku', 'Reservation ID', 'Qty Available']) + sheet.append(['PN-1', 'PN-OTHER', '1000140351', 9]) + workbook.save(stream) + stream.seek(0) + analysis = inventory_structure_analysis.create_sample_upload( + FileStorage(stream=stream, filename='duplicate.xlsx'), actor_id=None, + ) + with pytest.raises(ValidationError) as exc_info: + inventory_structure_analysis.create_profile_draft(analysis['id'], { + 'profile_code': 'DUPLICATE_HEADERS', 'display_name': 'Duplicate', + 'sheet_name': 'Sheet', 'header_row_index': 1, + 'field_mapping': _mapping(), + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}], + }, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID' + + +def test_profile_draft_uses_analysis_header_selection(app, tmp_path): + """确认的工作表、表头和来源栏位能创建可继续编辑的库存文件解析方案草稿。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + field_id = _published_part_number() + analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None) + profile = inventory_structure_analysis.create_profile_draft(analysis['id'], { + 'profile_code': 'AWS_INVENTORY', 'display_name': 'AWS 库存文件', + 'sheet_name': 'Inventory', 'header_row_index': 3, + 'field_mapping': _mapping(), + 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}], + }, actor_id=None) + assert profile['status'] == 'draft' + assert profile['definition']['sheet_name'] == 'Inventory' + assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku' + + +def test_sample_analysis_rejects_invalid_file(app, tmp_path): + """伪装为 xlsx 的非工作簿必须被拒绝,且不留下分析记录。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + upload = FileStorage(stream=BytesIO(b'not a workbook'), filename='invalid.xlsx') + with pytest.raises(ValidationError) as exc_info: + inventory_structure_analysis.create_sample_upload(upload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID' diff --git a/backend/tests/test_inventory_structure_drift.py b/backend/tests/test_inventory_structure_drift.py new file mode 100644 index 00000000..079f4193 --- /dev/null +++ b/backend/tests/test_inventory_structure_drift.py @@ -0,0 +1,173 @@ +"""验证正式库存文件结构漂移必须在入库前受控处理。""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from openpyxl import Workbook + +from app import db +from app.core.errors import ConflictError +from app.models import ( + ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryFile, + ShippingInventoryParsingProfile, ShippingInventorySource, ShippingRpaProfile, +) +from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file +from app.services.shipping_notice.inventory_structure_analysis import _analyse_path +from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure +from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition + + +def _workbook(path: Path, headers: list[str]) -> None: + """创建可控表头的库存文件,用于模拟货代导出格式变化。""" + workbook = Workbook() + sheet = workbook.active + sheet.append(headers) + values = { + 'Supplier Sku': 'PN-1', 'Reservation ID': '1000140351', 'Qty Available': 9, + 'Custom Part': 'PN-CUSTOM', 'Custom Reservation': '1000140999', 'Custom Quantity': 7, + 'Export Time': '2026-07-17', + } + sheet.append([values.get(header, 'value') for header in headers]) + workbook.save(path) + + +def _multi_sheet_workbook(path: Path) -> None: + """创建含相似工作表的文件,验证正式校验不会选错已确认工作表。""" + workbook = Workbook() + summary = workbook.active + summary.title = 'Summary' + # Summary 表刻意缺少关键栏位,不能影响已配置 Inventory 表的正式校验。 + summary.append(['Changed Part', 'Reservation ID', 'Qty Available']) + summary.append(['SUMMARY-PN', '1000140351', 99]) + inventory = workbook.create_sheet('Inventory') + inventory.append(['Supplier Sku', 'Reservation ID', 'Qty Available']) + inventory.append(['PN-1', '1000140351', 9]) + workbook.save(path) + + +def _source_with_profile(path: Path) -> ShippingInventorySource: + """从基准文件建立已启用站点和已发布方案,模拟完成全部启用前校验后的状态。""" + structure, _suggested, _summary, _warnings = _analyse_path(path, '.xlsx') + definition = structure_definition( + file_format='xlsx', sheet_name='Sheet', header_row_index=1, + headers=structure['selected_headers'], + ) + inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.filter_by(status='active').all()} + profile = ShippingInventoryParsingProfile( + profile_code='DRIFT_PROFILE', display_name='Drift Profile', version=1, status='published', file_format='xlsx', + definition_json={'sheet_name': 'Sheet', 'header_row_index': 1, 'field_mapping': { + inventory_fields['part_number']: 'Supplier Sku', inventory_fields['reservation_id']: 'Reservation ID', + inventory_fields['available_qty']: 'Qty Available', + }, 'match_keys': []}, structure_definition_json=definition, + exact_structure_fingerprint=exact_fingerprint(definition), checksum='1' * 64, + ) + rpa = ShippingRpaProfile( + profile_code='DRIFT_LOGIN', display_name='Drift Login', connector_type='dbs', + login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True, + ) + template = ShippingExcelTemplate( + template_code='DRIFT_TEMPLATE', display_name='Drift Template', version=1, status='published', + storage_bucket='test', storage_key='drift.xlsx', original_filename='drift.xlsx', file_checksum='0' * 64, + definition_json={'mappings': [{'source_kind': 'inventory_field', 'source_key': 'part_number'}]}, + definition_checksum='2' * 64, + ) + source = ShippingInventorySource( + source_code='DRIFT_SOURCE', display_name='Drift Source', connector_type='dbs', rpa_profile=rpa, + parsing_profile=profile, excel_template=template, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB', + report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'}, + query_parameters_json=[], match_aliases_json=[], enabled=True, + ) + db.session.add(source) + db.session.commit() + return source + + +def test_production_structure_accepts_exact_and_noncritical_column_change(app, tmp_path): + """同结构和仅新增无关栏位可入库,但结果需明确标注一致性等级。""" + with app.app_context(): + baseline = tmp_path / 'baseline.xlsx' + _workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available']) + _source_with_profile(baseline) + + exact = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=baseline) + assert exact['level'] == 'exact' + + compatible = tmp_path / 'compatible.xlsx' + _workbook(compatible, ['Supplier Sku', 'Reservation ID', 'Qty Available', 'Export Time']) + result = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=compatible) + assert result['level'] == 'compatible' + assert 'export time' in result['difference']['added_columns'] + + +def test_production_structure_blocks_core_column_drift(app, tmp_path): + """关键库存栏位改名后必须阻断,禁止运行期自动猜测新来源列。""" + with app.app_context(): + baseline = tmp_path / 'baseline.xlsx' + _workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available']) + _source_with_profile(baseline) + drifted = tmp_path / 'drifted.xlsx' + _workbook(drifted, ['Changed Part', 'Reservation ID', 'Qty Available']) + + with pytest.raises(ConflictError) as blocked: + validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=drifted) + assert blocked.value.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED' + + +def test_production_structure_uses_configured_worksheet_not_best_guess(app, tmp_path): + """多工作表文件必须依赖方案指定工作表,不能被其他错误工作表影响。""" + with app.app_context(): + baseline = tmp_path / 'baseline.xlsx' + _workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available']) + source = _source_with_profile(baseline) + source.parsing_profile.definition_json = { + **source.parsing_profile.definition_json, + 'sheet_name': 'Inventory', + } + source.parsing_profile.structure_definition_json = structure_definition( + file_format='xlsx', sheet_name='Inventory', header_row_index=1, + headers=['Supplier Sku', 'Reservation ID', 'Qty Available'], + ) + source.parsing_profile.exact_structure_fingerprint = exact_fingerprint( + source.parsing_profile.structure_definition_json, + ) + db.session.commit() + + _multi_sheet_workbook(tmp_path / 'multi-sheet.xlsx') + result = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=tmp_path / 'multi-sheet.xlsx') + assert result['level'] == 'exact' + assert result['sheet_name'] == 'Inventory' + + +def test_snapshot_reread_uses_published_profile_not_header_guess(app, tmp_path): + """正式快照丢失缓存行后仍按绑定方案重读,不能回退自动表头猜测。""" + with app.app_context(): + path = tmp_path / 'configured-only.xlsx' + _workbook(path, ['Custom Part', 'Custom Reservation', 'Custom Quantity']) + source = _source_with_profile(path) + fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} + source.parsing_profile.definition_json = { + 'sheet_name': 'Sheet', 'header_row_index': 1, + 'field_mapping': { + fields['part_number']: 'Custom Part', + fields['reservation_id']: 'Custom Reservation', + fields['available_qty']: 'Custom Quantity', + }, + 'match_keys': [], + } + snapshot = ShippingInventoryFile( + inventory_file_no='INV-REREAD-001', storage_path=str(path), source_code=source.source_code, + warehouse_id='DUB', snapshot_status='ready', inventory_lines_json=None, + ) + db.session.add(snapshot) + db.session.commit() + + lines, meta = parse_inventory_snapshot_file(snapshot) + assert lines == [{ + fields['part_number']: 'PN-CUSTOM', + fields['reservation_id']: '1000140999', + fields['available_qty']: 7.0, + }] + assert 'part_number' not in lines[0] + assert str(meta['mapping_source']).startswith('parsing_profile:DRIFT_PROFILE:v1') diff --git a/backend/tests/test_legacy_inventory_mapping_removal_migration.py b/backend/tests/test_legacy_inventory_mapping_removal_migration.py new file mode 100644 index 00000000..b6d3300b --- /dev/null +++ b/backend/tests/test_legacy_inventory_mapping_removal_migration.py @@ -0,0 +1,71 @@ +""" +用途:验证旧任务级库存映射缓存表迁移可独立升级和回滚。 +依赖:Alembic Operations、SQLAlchemy SQLite、fb1c2d3e4f5a 迁移。 +逻辑:创建旧表结构,升级后确认删除;回滚后确认仅恢复历史结构和索引。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _load_migration(): + """加载旧库存映射缓存移除迁移。""" + path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'fb1c2d3e4f5a_remove_legacy_inventory_mapping_cache.py' + spec = importlib.util.spec_from_file_location('legacy_inventory_mapping_removal', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_legacy_inventory_mapping_cache_migration_round_trip(): + """升级必须物理删除旧表,回滚只恢复可迁移的历史表结构。""" + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table( + 'shipping_inventory_mappings', + metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('customer_code', sa.String(64), nullable=False), + sa.Column('header_hash', sa.String(64), nullable=False), + sa.Column('headers_json', sa.JSON()), + sa.Column('field_mapping_json', sa.JSON(), nullable=False), + sa.Column('last_used_at', sa.DateTime()), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + ) + + with engine.begin() as connection: + metadata.create_all(connection) + context = MigrationContext.configure(connection) + operations = Operations(context) + migration = _load_migration() + migration.op = operations + + migration.upgrade() + assert 'shipping_inventory_mappings' not in sa.inspect(connection).get_table_names() + + migration.downgrade() + inspector = sa.inspect(connection) + assert 'shipping_inventory_mappings' in inspector.get_table_names() + assert {item['name'] for item in inspector.get_columns('shipping_inventory_mappings')} == { + 'id', + 'customer_code', + 'header_hash', + 'headers_json', + 'field_mapping_json', + 'last_used_at', + 'created_at', + 'updated_at', + } + assert { + 'ix_shipping_inventory_mappings_customer_code', + 'ix_shipping_inventory_mappings_created_at', + 'ix_shipping_inventory_mappings_updated_at', + }.issubset({item['name'] for item in inspector.get_indexes('shipping_inventory_mappings')}) diff --git a/backend/tests/test_rpa_worker_heartbeat.py b/backend/tests/test_rpa_worker_heartbeat.py index 1c7a5bd8..ebe366cd 100644 --- a/backend/tests/test_rpa_worker_heartbeat.py +++ b/backend/tests/test_rpa_worker_heartbeat.py @@ -63,12 +63,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d trigger_dir.mkdir() _write_shared_sentinel(trigger_dir, scope_id=scope_id) app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["FREIGHT_RPA_MOCK"] = "false" + app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" return trigger_dir @@ -128,11 +128,11 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path): trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["FREIGHT_RPA_MOCK"] = "false" + app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" with app.app_context(): record_rpa_worker_heartbeat( @@ -150,7 +150,7 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa """生产策略要求 Redis 时,写入失败应抛存储不可用。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False monkeypatch.setattr( @@ -171,11 +171,11 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path trigger_dir.mkdir() _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["FREIGHT_RPA_MOCK"] = "false" + app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" with app.app_context(): with pytest.raises(ServiceUnavailableError) as exc_info: @@ -367,7 +367,7 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path) trigger_dir.mkdir(parents=True) _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None) - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): assert shared_scope_id() == "hxops-rpa-test-data" diff --git a/backend/tests/test_rpa_worker_heartbeat_alert.py b/backend/tests/test_rpa_worker_heartbeat_alert.py index 5557850e..0a8de07e 100644 --- a/backend/tests/test_rpa_worker_heartbeat_alert.py +++ b/backend/tests/test_rpa_worker_heartbeat_alert.py @@ -32,7 +32,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True @@ -41,7 +41,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data" app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600 app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "" app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True - app.config["FREIGHT_RPA_MOCK"] = "false" + app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" return trigger_dir diff --git a/backend/tests/test_schedule_platform_tasks.py b/backend/tests/test_schedule_platform_tasks.py index 699cc0cb..c8c755c9 100644 --- a/backend/tests/test_schedule_platform_tasks.py +++ b/backend/tests/test_schedule_platform_tasks.py @@ -19,6 +19,15 @@ from app.services.schedule.job_params import ( ) +def _enabled_source_code() -> str: + """读取测试数据库的首个启用库存源,避免测试依赖已废弃 YAML 的固定编码。""" + from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources + + sources = list_database_inventory_sources() + assert sources, 'expected at least one enabled inventory source' + return str(sources[0]['source_code']) + + @pytest.fixture def admin_jwt_headers(app): """创建 admin 用户并签发 Bearer JWT。""" @@ -80,7 +89,8 @@ def test_platform_task_options_shipping_sources(client, admin_jwt_headers, app): assert options, 'expected at least one enabled inventory source' assert all('label' in item and 'value' in item for item in options) values = {item['value'] for item in options} - assert 'DSV360_AWSBI_BYAWSATL01' in values + with app.app_context(): + assert _enabled_source_code() in values def test_platform_task_options_unknown_source_rejected(client, admin_jwt_headers): @@ -112,10 +122,11 @@ def test_validate_task_params_rejects_unknown_key(app): def test_validate_task_params_rejects_wrong_type(app): """multi_select 传入非 list 应报类型错误。""" with app.app_context(): + source_code = _enabled_source_code() with pytest.raises(JobParamsValidationError, match='list of option values'): validate_task_params( 'shipping-inventory-rpa', - {'source_codes': 'DSV360_AWSBI_BYAWSATL01'}, + {'source_codes': source_code}, check_options=False, ) @@ -123,6 +134,7 @@ def test_validate_task_params_rejects_wrong_type(app): def test_validate_task_params_checks_option_range(app): """check_options=True 时,multi_select 值不在选项范围内应报错。""" with app.app_context(): + source_code = _enabled_source_code() with pytest.raises(JobParamsValidationError, match='not in options'): validate_task_params( 'shipping-inventory-rpa', @@ -132,10 +144,10 @@ def test_validate_task_params_checks_option_range(app): # 合法值应通过 result = validate_task_params( 'shipping-inventory-rpa', - {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}, + {'source_codes': [source_code]}, check_options=True, ) - assert result['source_codes'] == ['DSV360_AWSBI_BYAWSATL01'] + assert result['source_codes'] == [source_code] def test_validate_task_params_passes_advanced_through(app): @@ -186,16 +198,18 @@ def owner_id(app): def test_post_schedule_persists_valid_job_params(client, admin_jwt_headers, owner_id, app): """合法 job_params 应持久化并出现在 serialize_task 响应中。""" + with app.app_context(): + source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, - job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']}, + job_params={'source_codes': [source_code]}, ) assert res.status_code == 201 body = res.get_json() - assert body['job_params'] == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']} + assert body['job_params'] == {'source_codes': [source_code]} with app.app_context(): task = db.session.get(ScheduleTask, body['id']) - assert task.job_params == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']} + assert task.job_params == {'source_codes': [source_code]} def test_post_schedule_without_job_params_applies_schema_defaults(client, admin_jwt_headers, owner_id, app): @@ -254,9 +268,11 @@ def test_post_data_pipeline_rejects_job_params(client, admin_jwt_headers, owner_ def test_patch_schedule_updates_and_clears_job_params(client, admin_jwt_headers, owner_id, app): """PATCH 应支持更新;显式 null 对有 schema 的任务重置为默认值。""" + with app.app_context(): + source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, - job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']}, + job_params={'source_codes': [source_code]}, ) task_id = res.get_json()['id'] @@ -275,9 +291,11 @@ def test_patch_schedule_updates_and_clears_job_params(client, admin_jwt_headers, def test_patch_platform_api_path_resets_job_params_to_new_defaults(client, admin_jwt_headers, owner_id, app): """切换 platform_api_path 且未传 job_params 时,应按新任务 schema 重置,避免旧参数残留。""" + with app.app_context(): + source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, - job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']}, + job_params={'source_codes': [source_code]}, ) task_id = res.get_json()['id'] @@ -295,9 +313,11 @@ def test_patch_platform_api_path_resets_job_params_to_new_defaults(client, admin def test_patch_platform_api_path_to_schemaless_clears_job_params(client, admin_jwt_headers, owner_id, app): """切换到无 params_schema 的平台任务且未传 job_params 时应清空旧参数。""" + with app.app_context(): + source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, - job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']}, + job_params={'source_codes': [source_code]}, ) task_id = res.get_json()['id'] @@ -310,11 +330,13 @@ def test_patch_platform_api_path_to_schemaless_clears_job_params(client, admin_j assert body['job_params'] is None -def test_patch_platform_api_path_with_explicit_job_params_keeps_payload(client, admin_jwt_headers, owner_id): +def test_patch_platform_api_path_with_explicit_job_params_keeps_payload(client, admin_jwt_headers, owner_id, app): """切换 platform_api_path 同时显式传 job_params 时,应保留请求体参数(经新 schema 校验)。""" + with app.app_context(): + source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, - job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']}, + job_params={'source_codes': [source_code]}, ) task_id = res.get_json()['id'] @@ -346,9 +368,10 @@ def test_shipping_rpa_filter_prefers_job_params(app): from app.services.schedule.shipping_inventory_rpa_job import _filter_sources with app.app_context(): - task = ScheduleTask(job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']}) + source_code = _enabled_source_code() + task = ScheduleTask(job_params={'source_codes': [source_code]}) sources = _filter_sources(task) - assert [item.get('source_code') for item in sources] == ['DSV360_AWSBI_BYAWSATL01'] + assert [item.get('source_code') for item in sources] == [source_code] # job_params 为空(默认值)时不筛选 → 返回全部启用源 task_all = ScheduleTask(job_params={'source_codes': []}) assert len(_filter_sources(task_all)) >= 1 diff --git a/backend/tests/test_shipping_customer_auto_resolution.py b/backend/tests/test_shipping_customer_auto_resolution.py index 873c50a7..10d9307a 100644 --- a/backend/tests/test_shipping_customer_auto_resolution.py +++ b/backend/tests/test_shipping_customer_auto_resolution.py @@ -1,7 +1,7 @@ """ backend/tests/test_shipping_customer_auto_resolution.py -用途:验证受控自动客户确认、降级开关、强规则歧义和历史客户回填。 +用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。 依赖:客户主数据/证据、Candidate 影子结果、ShippingTask/Case、customer_auto_resolution。 逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 """ @@ -25,7 +25,6 @@ from app.models import ( ) 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, @@ -100,10 +99,17 @@ def _customer_with_identifier(*, code: str, value: str, allowed: bool = True, st return customer +def _allow_auto_confirmation(app) -> None: + """为自动确认专项用例显式放宽门禁,不改变生产默认安全阈值。""" + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 0 + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 + + def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): """开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。""" with app.app_context(): - app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + _allow_auto_confirmation(app) customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() @@ -132,7 +138,7 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): assert disabled["status"] == "disabled" assert task.shipping_case.business_no is None - app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + _allow_auto_confirmation(app) unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" assert task.customer_resolution_status == "pending" @@ -142,7 +148,7 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): """同一强证据映射多个客户时必须降级人工确认。""" with app.app_context(): - app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + _allow_auto_confirmation(app) _customer_with_identifier(code="AAA", value="buyer@wyc.example.com") _customer_with_identifier(code="BBB", value="buyer@wyc.example.com") task = _seed_candidate_task() @@ -154,29 +160,10 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): 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 + _allow_auto_confirmation(app) _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") task = _seed_candidate_task() task_id = task.id @@ -195,6 +182,48 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 +def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insufficient(app): + """总开关开启但没有足够人工真值时,必须保持人工客户复核和未编号状态。""" + with app.app_context(): + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1 + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + + result = try_auto_confirm_task_customer(task) + + assert result["status"] == "insufficient_labeled_samples" + assert result["quality_gate"]["labeled_sample_count"] == 0 + assert task.customer_resolution_status == "pending" + assert task.shipping_case.business_no is None + + +def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app): + """有足够样本但强规则与人工真值不一致时,自动确认必须安全降级。""" + with app.app_context(): + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES"] = 1 + app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 + matched = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + truth = ShippingCustomer(standard_name="真实客户", short_code="TRU", status="active") + db.session.add(truth) + db.session.flush() + task = _seed_candidate_task() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow.manual_customer_id = truth.id + db.session.commit() + + result = try_auto_confirm_task_customer(task) + + assert matched.id != truth.id + assert result["status"] == "insufficient_accuracy" + assert result["quality_gate"]["labeled_sample_count"] == 1 + assert result["quality_gate"]["accuracy"] == 0 + assert task.customer_resolution_status == "pending" + assert task.shipping_case.business_no is None + + def test_numbered_customer_correction_voids_old_number_and_replaces_case(app): """客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。""" with app.app_context(): diff --git a/backend/tests/test_shipping_customer_identity_gate.py b/backend/tests/test_shipping_customer_identity_gate.py index 13a552cc..5b82f309 100644 --- a/backend/tests/test_shipping_customer_identity_gate.py +++ b/backend/tests/test_shipping_customer_identity_gate.py @@ -3,7 +3,7 @@ backend/tests/test_shipping_customer_identity_gate.py 用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 -逻辑:构造 pending 任务逐入口断言无副作用;确认后验证业务单/修订同步和历史兼容。 +逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。 """ from __future__ import annotations @@ -26,7 +26,7 @@ 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.inventory_workflow import ensure_inventory, upload_inventory_file from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.task_workflow import retry_task @@ -71,7 +71,6 @@ def test_pending_customer_blocks_every_downstream_entry(app): 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, @@ -140,8 +139,8 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app): 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): - """已确认客户停用后重新阻断;历史无业务单任务继续兼容。""" +def test_inactive_customer_reblocks_and_missing_case_is_blocked(app): + """已确认客户停用后重新阻断;缺少业务单的任务也必须阻断。""" with app.app_context(): task, customer, user = _seed_task() confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) @@ -151,9 +150,11 @@ def test_inactive_customer_reblocks_and_legacy_task_is_compatible(app): 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 + missing_case, _other_customer, _other_user = _seed_task(with_case=False) + with pytest.raises(AppError) as missing_case_error: + assert_customer_identity_gate(missing_case, operation='match_inventory') + assert missing_case_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' + assert customer_identity_is_confirmed(missing_case) is False def test_workspace_customer_search_and_confirmation_api(app, client): diff --git a/backend/tests/test_shipping_customer_migrations.py b/backend/tests/test_shipping_customer_migrations.py index eb97e4af..883463c2 100644 --- a/backend/tests/test_shipping_customer_migrations.py +++ b/backend/tests/test_shipping_customer_migrations.py @@ -1,7 +1,7 @@ """ backend/tests/test_shipping_customer_migrations.py -用途:独立验证客户主数据、期初导入与影子识别三段迁移可升级和降级。 +用途:独立验证客户主数据、期初导入、影子识别与生命周期基础迁移可升级和降级。 依赖:Alembic MigrationContext、SQLAlchemy、f1/a2/b3 客户迁移模块。 逻辑:构造订单抽取阶段的最小历史结构,依序执行迁移并检查约束,再逆序回滚。 """ @@ -28,13 +28,15 @@ def _customer_pre_migration_schema(engine: sa.Engine) -> None: 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'), + importlib.import_module('migrations.versions.5d6e7f8a9b0c_shipping_customer_lifecycle_foundation'), + importlib.import_module('migrations.versions.6e7f8a9b0c1d_shipping_customer_merge_foundation'), ] with engine.begin() as connection: @@ -55,6 +57,9 @@ def test_shipping_customer_migrations_upgrade_and_downgrade(): 'shipping_customer_import_batches', 'shipping_customer_import_rows', 'shipping_customer_shadow_resolutions', + 'shipping_customer_shadow_matches', + 'shipping_customer_lifecycle_events', + 'shipping_customer_merges', } <= 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 @@ -82,6 +87,9 @@ def test_shipping_customer_migrations_upgrade_and_downgrade(): assert 'shipping_customers' not in remaining assert 'shipping_customer_import_batches' not in remaining assert 'shipping_customer_shadow_resolutions' not in remaining + assert 'shipping_customer_shadow_matches' not in remaining + assert 'shipping_customer_lifecycle_events' not in remaining + assert 'shipping_customer_merges' 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: diff --git a/backend/tests/test_shipping_customer_shadow_resolution.py b/backend/tests/test_shipping_customer_shadow_resolution.py index 6dc1b145..48aa320d 100644 --- a/backend/tests/test_shipping_customer_shadow_resolution.py +++ b/backend/tests/test_shipping_customer_shadow_resolution.py @@ -15,6 +15,7 @@ from app.models import ( ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerShadowResolution, + ShippingCustomerShadowMatch, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, @@ -90,6 +91,7 @@ def test_shadow_resolution_uses_strong_evidence_without_binding_case(app): assert resolution.status == 'unique_candidate' assert resolution.top_customer_id == customer.id assert resolution.top_score == 100.0 + assert db.session.query(ShippingCustomerShadowMatch).filter_by(customer_id=customer.id).count() == 1 assert case.customer_id is None assert case.business_no is None assert get_shadow_quality_report()['auto_bound_count'] == 0 @@ -107,6 +109,7 @@ def test_shadow_resolution_reports_ambiguous_and_unmatched(app): assert ambiguous.status == 'ambiguous' assert ambiguous.top_customer_id is None assert len(ambiguous.candidate_matches_json) == 2 + assert len(ambiguous.matches) == 2 assert unmatched.status == 'unmatched' assert unmatched.candidate_matches_json == [] diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py new file mode 100644 index 00000000..8ae48466 --- /dev/null +++ b/backend/tests/test_shipping_excel_template.py @@ -0,0 +1,490 @@ +""" +用途:验证版本化发货 Excel 模板发布、库存源共享绑定及动态字段导出产物审计。 +依赖:excel_template/export 服务、openpyxl、订单动态 Schema 与库存配置模型。 +逻辑:创建真实 xlsx 草稿并发布,生成任务产物后断言 Header/Line 写入及版本锁定字段。 +""" + +from __future__ import annotations + +from datetime import date +from io import BytesIO +from unittest.mock import patch + +from openpyxl import Workbook, load_workbook +from werkzeug.datastructures import FileStorage +import pytest + +from app import db +from app.models import ( + ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction, + ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, + ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask, +) +from app.services.shipping_notice import excel_template +from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel +from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export +from app.core.errors import ValidationError + + +def _inventory_field_id(field_code: str) -> str: + """返回库存字段目录 ID,使模板测试覆盖当前发布契约。""" + return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id) + + +@pytest.fixture(autouse=True) +def _template_object_storage(monkeypatch): + """使用内存私有对象存储替身,验证模板不依赖本机文件系统。""" + objects: dict[str, bytes] = {} + + def upload_bytes(*, storage_key: str, data: bytes, content_type: str) -> None: + objects[storage_key] = bytes(data) + + def get_bytes(storage_key: str) -> bytes: + if storage_key not in objects: + raise RuntimeError(f'missing test object: {storage_key}') + return objects[storage_key] + + def delete_object(storage_key: str) -> None: + objects.pop(storage_key, None) + + for module in ('app.services.shipping_notice.excel_template', 'app.services.shipping_notice.export'): + monkeypatch.setattr(f'{module}.file_asset_storage.upload_bytes', upload_bytes) + monkeypatch.setattr(f'{module}.file_asset_storage.get_bytes', get_bytes) + monkeypatch.setattr(f'{module}.file_asset_storage.delete_object', delete_object) + monkeypatch.setattr(f'{module}.file_asset_storage.bucket_name', 'test-template-bucket') + return objects + + +def _workbook_upload() -> FileStorage: + """构造含 Header/Detail 工作表的内存 xlsx 上传对象。""" + stream = BytesIO() + wb = Workbook() + wb.active.title = 'Header' + wb.create_sheet('Detail') + wb.save(stream) + stream.seek(0) + return FileStorage(stream=stream, filename='shipping.xlsx', content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') + + +def test_filename_pattern_supports_business_number_and_split_business_variables(): + """业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。""" + shipping_case = ShippingCase( + case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC', + business_date=date(2026, 6, 2), sequence_value=1, + ) + task = ShippingTask(task_no='TASK-FILENAME', inventory_source_code='DBS') + task.shipping_case = shipping_case + template = ShippingExcelTemplate( + template_code='FILENAME', display_name='Filename', + definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'}, + ) + + assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx' + + +def test_published_template_generates_dynamic_artifact(app, tmp_path): + """发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add(schema) + db.session.flush() + customer = ShippingOrderField(schema_id=schema.id, field_code='customer_code', scope='header', value_type='string') + po_number = ShippingOrderField(schema_id=schema.id, field_code='po_number', scope='header', value_type='string') + part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string') + db.session.add_all([customer, po_number, part]) + db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={ + 'fields': [{'field_id': customer.id}, {'field_id': po_number.id}, {'field_id': part.id}], + }, checksum='s' * 64) + db.session.add(version) + db.session.flush() + + definition = { + 'filename_pattern': 'shipment_{task_no}_{date}.xlsx', + 'mappings': [ + {'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': customer.id, 'formatter': 'upper'}, + {'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'warehouse_id', 'formatter': 'text'}, + {'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 3, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'}, + {'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'}, + {'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'}, + {'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 3, 'source_kind': 'order_field', 'source_key': po_number.id, 'formatter': 'text'}, + ], + } + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'COMMON_SHIPMENT', 'display_name': 'Common Shipment', 'definition': definition, + }, actor_id=None) + published = excel_template.publish(draft['id'], actor_id=None) + + parsing = ShippingInventoryParsingProfile( + profile_code='COMMON_INV', display_name='Common Inventory', version=1, status='published', + file_format='xlsx', definition_json={ + 'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, + 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}], + }, checksum='p' * 64, + ) + login = ShippingRpaProfile( + profile_code='LOGIN', display_name='Login', connector_type='dbs', login_url='https://invalid', + login_config_json={'auth_mode': 'password'}, + ) + db.session.add_all([parsing, login]) + db.session.flush() + source = ShippingInventorySource( + source_code='DUB', display_name='Dublin', connector_type='dbs', rpa_profile_id=login.id, + parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', + fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[], + ) + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + db.session.add_all([source, extraction]) + db.session.flush() + order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') + db.session.add(order_line) + db.session.flush() + header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme') + po_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=po_number.id, decision_status='accepted', resolved_value_json='16754796') + line_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, decision_status='accepted', resolved_value_json='PN-1') + db.session.add_all([header_decision, po_decision, line_decision]) + db.session.flush() + db.session.add_all([ + ShippingOrderFieldValue(extraction_id=extraction.id, field_id=customer.id, value_text='acme', decision_id=header_decision.id), + ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id), + ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id), + ]) + task = ShippingTask( + task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB', + inventory_warehouse_id='DUB', inventory_lines_json=[{ + _inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9', + }], inventory_snapshot_id=None, + ) + db.session.add(task) + db.session.flush() + + path, filename, artifact = generate_shipment_excel(task) + db.session.commit() + + wb = load_workbook(path, read_only=True) + assert wb['Header'].cell(2, 1).value == 'ACME' # Header 动态字段及 formatter 生效。 + assert wb['Header'].cell(2, 2).value == 'DUB' # 受控系统事实写入目标列。 + assert wb['Header'].cell(2, 3).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y') + assert wb['Detail'].cell(3, 1).value == 'PN-1' # Line 字段按订单行写入。 + assert wb['Detail'].cell(3, 2).value == 'ODM-9' # 标准库存字段无需 LLM 判断。 + assert wb['Detail'].cell(3, 3).value == '16754796' # Header 字段按业务要求重复到每条明细。 + wb.close() + assert filename.startswith('shipment_TASK-EXPORT-1_') + assert artifact.template_id == published['id'] + assert artifact.order_schema_version_id == version.id + assert artifact.inventory_parsing_profile_id == parsing.id + assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0 + + # Dynamic inventory sources must resolve Warehouse before any export can be created. + task.inventory_warehouse_id = None + with pytest.raises(ValueError, match='缺少已解析的 Warehouse ID'): + generate_shipment_excel(task) + + +def test_header_mapping_rejects_line_order_field(app): + """订单头区域不得引用明细字段,避免把多行值错误压缩为单个表头值。""" + with app.app_context(): + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add(schema) + db.session.flush() + part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string') + db.session.add(part) + db.session.flush() + db.session.add(ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', + definition_json={'fields': [{'field_id': part.id}]}, checksum='s' * 64, + )) + db.session.flush() + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'INVALID_HEADER_LINE', 'display_name': 'Invalid Header Line', + 'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{ + 'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, + 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text', + }]}, + }, actor_id=None) + + with pytest.raises(ValidationError) as exc_info: + excel_template.publish(draft['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID' + + +def test_export_date_system_fact_uses_business_timezone(app): + """导出日期必须返回上海业务时区的日期对象,供模板统一格式化。""" + with app.app_context(): + value = _system_fact(ShippingTask(task_no='TASK-DATE'), 'export_date') + assert isinstance(value, date) + + +def test_two_sources_can_share_one_published_excel_template(app, tmp_path): + """同结构库存源绑定同一 published 模板,避免复制维护映射规则。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'SHARED', 'display_name': 'Shared', + 'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [ + {'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1, 'source_kind': 'constant', 'source_key': 'n', 'formatter': 'text'}, + ]}, + }, actor_id=None) + published = excel_template.publish(draft['id'], actor_id=None) + parsing = ShippingInventoryParsingProfile( + profile_code='SHARED_INV', display_name='Shared Inventory', version=1, status='published', + file_format='xlsx', definition_json={}, checksum='p' * 64, + ) + login = ShippingRpaProfile( + profile_code='SHARED_LOGIN', display_name='Shared Login', connector_type='dbs', + login_url='https://invalid', login_config_json={'auth_mode': 'password'}, + ) + db.session.add_all([parsing, login]) + db.session.flush() + for code in ('DUB', 'RTM'): + db.session.add(ShippingInventorySource( + source_code=code, display_name=code, connector_type='dbs', rpa_profile_id=login.id, + parsing_profile_id=parsing.id, excel_template_id=published['id'], + warehouse_resolution_mode='fixed', fixed_warehouse_id=code, + report_path_json={}, query_parameters_json=[], match_aliases_json=[], + )) + db.session.commit() + + template = db.session.get(ShippingExcelTemplate, published['id']) + assert template is not None + assert {source.source_code for source in template.sources} == {'DUB', 'RTM'} # 一个发布版本供多个 Source 共享。 + + +def test_disabled_source_still_blocks_template_retirement(app): + """禁用库存源仍保留模板配置引用,迁移前不得退役其模板版本。""" + with app.app_context(): + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'DISABLED_REF', 'display_name': 'Disabled Ref', + 'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{ + 'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1, + 'source_kind': 'constant', 'source_key': 'x', 'formatter': 'text', + }]}, + }, actor_id=None) + published = excel_template.publish(draft['id'], actor_id=None) + login = ShippingRpaProfile( + profile_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs', + login_url='https://invalid', login_config_json={'auth_mode': 'password'}, + ) + db.session.add(login) + db.session.flush() + db.session.add(ShippingInventorySource( + source_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs', enabled=False, + rpa_profile_id=login.id, excel_template_id=published['id'], + warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB', + report_path_json={}, query_parameters_json=[], match_aliases_json=[], + )) + db.session.commit() + + with pytest.raises(Exception) as exc_info: + excel_template.retire(published['id']) + assert getattr(exc_info.value, 'code', '') == 'SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED' + + +def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path): + """库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add(schema); db.session.flush() + part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string') + db.session.add(part); db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={ + 'fields': [{'field_id': part.id}], + }) + db.session.add(version); db.session.flush() + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'KEYED', 'display_name': 'Keyed', + 'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [ + {'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'}, + {'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'}, + ]}, + }, actor_id=None) + published = excel_template.publish(draft['id'], actor_id=None) + parsing = ShippingInventoryParsingProfile( + profile_code='KEYED', display_name='Keyed', version=1, status='published', file_format='xlsx', + definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]}, + ) + login = ShippingRpaProfile( + profile_code='KEYED', display_name='Keyed', connector_type='dbs', login_url='https://invalid', + login_config_json={'auth_mode': 'password'}, + ) + db.session.add_all([parsing, login]); db.session.flush() + db.session.add(ShippingInventorySource( + source_code='KEYED', display_name='Keyed', connector_type='dbs', rpa_profile_id=login.id, + parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', + fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[], + )) + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + db.session.add(extraction); db.session.flush() + for position, value in enumerate(('PN-A', 'PN-B'), start=1): + line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_key=str(position)) + db.session.add(line); db.session.flush() + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=line.id, field_id=part.id, + decision_status='accepted', resolved_value_json=value, + ) + db.session.add(decision); db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=line.id, field_id=part.id, + value_text=value, decision_id=decision.id, + )) + task = ShippingTask( + task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED', + inventory_warehouse_id='DUB', inventory_lines_json=[ + {_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'}, + {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'}, + ], + ) + db.session.add(task); db.session.flush() + + path, _filename, _artifact = generate_shipment_excel(task) + workbook = load_workbook(path, read_only=True) + assert workbook['Detail'].cell(2, 2).value == 'ODM-A' + assert workbook['Detail'].cell(3, 2).value == 'ODM-B' + workbook.close() + + +def test_template_upload_rejects_fake_xlsx_without_leaving_file(app, tmp_path, _template_object_storage): + """扩展名伪装的无效工作簿必须在创建草稿前拒绝,模板目录不得产生孤立文件。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + fake = FileStorage(stream=BytesIO(b'not-a-workbook'), filename='fake.xlsx') + with pytest.raises(ValidationError) as exc_info: + excel_template.create_draft(fake, { + 'template_code': 'FAKE', 'display_name': 'Fake', 'definition': {}, + }, actor_id=None) + assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_INVALID' + assert not _template_object_storage + + +def test_existing_template_can_create_new_draft_version_without_reupload(app): + """新版本直接复制受管文件和映射定义,用户无需再次选择本地 Excel。""" + with app.app_context(): + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'COPY_VERSION', 'display_name': 'Copy Version', + 'definition': {'filename_pattern': '{business_no}.xlsx', 'mappings': [{ + 'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1, + 'source_kind': 'constant', 'source_key': 'x', 'formatter': 'text', + }]}, + }, actor_id=None) + published = excel_template.publish(draft['id'], actor_id=None) + copied = excel_template.create_draft_from_existing(published['id'], actor_id=None) + assert copied['version'] == 2 + assert copied['status'] == 'draft' + assert copied['definition'] == draft['definition'] + layout = excel_template.get_layout(copied['id']) + assert set(layout['sheets']) == {'Header', 'Detail'} + + +def test_template_publish_rejects_order_field_removed_from_current_schema(app): + """模板草稿不得在订单字段移出当前 published Schema 后继续发布。""" + from app.services.shipping_notice.order_schema import service as order_schema_service + + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + old_field = order_schema_service.save_field({ + 'field_code': 'old_part', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + new_field = order_schema_service.save_field({ + 'field_code': 'new_part', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + + def config(field_id: str) -> dict: + return { + 'field_id': field_id, 'display_name': '内部料号', 'required': True, 'aliases': [], + 'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_table'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': 'normalized_text', + 'extraction_instruction': '提取内部料号', + } + + first = order_schema_service.create_draft({}, actor_id=None) + saved_schema = order_schema_service.save_draft(first['id'], { + 'fields': [config(new_field['id'])], 'expected_lock_version': first['lock_version'], + }) + order_schema_service.publish( + first['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'], + ) + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'STALE_FIELD', 'display_name': 'Stale Field', + 'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{ + 'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, + 'source_kind': 'order_field', 'source_key': old_field['id'], 'formatter': 'text', + }]}, + }, actor_id=None) + with pytest.raises(ValidationError) as exc_info: + excel_template.publish(draft['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID' + + +def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path): + """同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add(schema); db.session.flush() + part = ShippingOrderField(schema_id=schema.id, field_code='part_number', scope='line', value_type='string') + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) + db.session.add_all([part, version]); db.session.flush() + draft = excel_template.create_draft(_workbook_upload(), { + 'template_code': 'AMBIGUOUS', 'display_name': 'Ambiguous', + 'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [ + {'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'}, + ]}, + }, actor_id=None) + published = excel_template.publish(draft['id'], actor_id=None) + parsing = ShippingInventoryParsingProfile( + profile_code='AMBIGUOUS', display_name='Ambiguous', version=1, status='published', file_format='xlsx', + definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]}, + ) + login = ShippingRpaProfile( + profile_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', login_url='https://invalid', + login_config_json={'auth_mode': 'password'}, + ) + db.session.add_all([parsing, login]); db.session.flush() + db.session.add(ShippingInventorySource( + source_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', rpa_profile_id=login.id, + parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed', + fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[], match_aliases_json=[], + )) + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + db.session.add(extraction); db.session.flush() + line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') + db.session.add(line); db.session.flush() + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=line.id, field_id=part.id, + decision_status='accepted', resolved_value_json='PN-A', + ) + db.session.add(decision); db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=line.id, field_id=part.id, + value_text='PN-A', decision_id=decision.id, + )) + task = ShippingTask( + task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id, + inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[ + {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'}, + {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'}, + ], + ) + db.session.add(task); db.session.flush() + + with pytest.raises(ValueError, match='值不一致'): + generate_shipment_excel(task) + export_root = tmp_path / 'shipping' / 'exports' + assert not export_root.exists() or not list(export_root.rglob('*.xlsx')) + + +def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch): + """Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。""" + path = tmp_path / 'orphan.xlsx' + path.write_bytes(b'orphan') + with app.app_context(): + monkeypatch.setattr(db.session, 'commit', lambda: (_ for _ in ()).throw(RuntimeError('commit failed'))) + with pytest.raises(RuntimeError, match='commit failed'): + _commit_generated_export(str(path)) + assert not path.exists() diff --git a/backend/tests/test_shipping_export_archive.py b/backend/tests/test_shipping_export_archive.py new file mode 100644 index 00000000..08d292cb --- /dev/null +++ b/backend/tests/test_shipping_export_archive.py @@ -0,0 +1,146 @@ +""" +用途:验证发货 Excel 批次 ZIP 的权限、最新 Artifact、重名、校验和与 manifest 契约。 +依赖:export_archive、ShippingBatch/Task/ExportArtifact、zipfile。 +逻辑:构造同批次有效、缺失及损坏产物,断言 ZIP 仅包含可信文件并完整列出排除原因。 +""" + +from __future__ import annotations + +import hashlib +import json +from zipfile import ZipFile + +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + ShippingBatch, ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile, + ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingTask, User, +) +from app.services.shipping_notice.export_archive import build_export_archive +from app.core.auth.jwt import issue_local_access_token + + +def _seed_artifact_dependencies(): + """创建 Artifact 外键所需的最小发布版本。""" + template = ShippingExcelTemplate( + template_code='ZIP', display_name='ZIP', version=1, status='published', + storage_provider='minio', storage_bucket='test', storage_key='test/zip-template.xlsx', + original_filename='template.xlsx', file_checksum='t' * 64, definition_json={}, definition_checksum='d' * 64, + ) + parsing = ShippingInventoryParsingProfile( + profile_code='ZIP', display_name='ZIP', version=1, status='published', file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add_all([template, parsing, schema]); db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) + db.session.add(version); db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted') + db.session.add(extraction); db.session.flush() + return template, parsing, version, extraction + + +def _artifact(task, path, dependencies, *, no: str, checksum: str | None = None): + """为任务新增 ready Artifact,checksum 默认按文件内容计算。""" + template, parsing, version, extraction = dependencies + content = path.read_bytes() if path.is_file() else b'' + item = ShippingExportArtifact( + artifact_no=no, task_id=task.id, batch_id=task.batch_id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=parsing.id, input_checksum='x' * 64, + file_path=str(path), file_name='shipment.xlsx', file_checksum=checksum or hashlib.sha256(content).hexdigest(), + file_size=len(content), status='ready', + ) + db.session.add(item) + task.export_file_path = str(path) + task.export_file_name = 'shipment.xlsx' + return item + + +def test_batch_archive_manifest_and_duplicate_names(app, tmp_path): + """有效同名文件均进入 ZIP,缺失/损坏任务只进入 manifest 并带明确状态。""" + with app.app_context(): + user = User(username='zip-owner', email='zip@example.com', role='user', status='approved') + batch = ShippingBatch(batch_no='SB-ZIP', user_id=None, file_count=4) + db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id + tasks = [ShippingTask(task_no=f'TASK-{index}', user_id=user.id, batch_id=batch.id, batch_index=index, batch_total=4) for index in range(1, 5)] + db.session.add_all(tasks); db.session.flush() + first = tmp_path / 'first.xlsx'; first.write_bytes(b'first') + second = tmp_path / 'second.xlsx'; second.write_bytes(b'second') + corrupt = tmp_path / 'corrupt.xlsx'; corrupt.write_bytes(b'changed') + dependencies = _seed_artifact_dependencies() + _artifact(tasks[0], first, dependencies, no='EXP-1') + _artifact(tasks[1], second, dependencies, no='EXP-2') + _artifact(tasks[2], tmp_path / 'missing.xlsx', dependencies, no='EXP-3') + _artifact(tasks[3], corrupt, dependencies, no='EXP-4', checksum='0' * 64) + db.session.commit() + + stream, filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no) + with ZipFile(stream) as archive: + names = archive.namelist() + assert 'shipment.xlsx' in names + assert 'shipment_TASK-2.xlsx' in names # 同名按任务号消歧,避免覆盖。 + archived_manifest = json.loads(archive.read('manifest.json')) + assert filename.startswith('shipping_exports_SB-ZIP_') + assert archived_manifest['included_count'] == 2 + assert [entry['status'] for entry in manifest['entries']] == [ + 'included', 'included', 'missing_file', 'checksum_mismatch', + ] + + +def test_archive_rejects_foreign_task_and_invalid_selection(app): + """任一越权任务整体拒绝,且 batch_no/task_nos 不能同时或同时不传。""" + with app.app_context(): + owner = User(username='archive-owner', email='archive-owner@example.com', role='user', status='approved') + other = User(username='archive-other', email='archive-other@example.com', role='user', status='approved') + task = ShippingTask(task_no='FOREIGN-TASK', user_id=owner.id) + db.session.add_all([owner, other]); db.session.flush(); task.user_id = owner.id; db.session.add(task); db.session.commit() + with pytest.raises(NotFoundError): + build_export_archive(user_id=other.id, task_nos=[task.task_no]) + with pytest.raises(ValidationError): + build_export_archive(user_id=owner.id) + with pytest.raises(ValidationError): + build_export_archive(user_id=owner.id, batch_no='SB', task_nos=[task.task_no]) + + +def test_archive_excludes_artifact_after_task_export_is_invalidated(app, tmp_path): + """任务纠错清空当前导出引用后,旧 ready Artifact 不得继续进入下载包。""" + with app.app_context(): + user = User(username='archive-reset', email='archive-reset@example.com', role='user', status='approved') + batch = ShippingBatch(batch_no='SB-RESET', user_id=None, file_count=1) + db.session.add_all([user, batch]); db.session.flush(); batch.user_id = user.id + task = ShippingTask(task_no='TASK-RESET', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1) + db.session.add(task); db.session.flush() + path = tmp_path / 'old.xlsx'; path.write_bytes(b'old') + _artifact(task, path, _seed_artifact_dependencies(), no='EXP-OLD') + task.export_file_path = None + task.export_file_name = None + db.session.commit() + + _stream, _filename, manifest = build_export_archive(user_id=user.id, batch_no=batch.batch_no) + assert manifest['included_count'] == 0 + assert manifest['entries'][0]['status'] == 'missing_artifact' + + +def test_workspace_archive_api_returns_zip(app, client, tmp_path): + """Workspace API 必须以当前用户权限生成 attachment ZIP,而不是暴露服务器文件路径。""" + with app.app_context(): + user = User(username='archive-api', email='archive-api@example.com', role='user', status='approved') + db.session.add(user); db.session.flush() + batch = ShippingBatch(batch_no='SB-API-ZIP', user_id=user.id, file_count=1) + db.session.add(batch); db.session.flush() + task = ShippingTask(task_no='TASK-API-ZIP', user_id=user.id, batch_id=batch.id, batch_index=1, batch_total=1) + db.session.add(task); db.session.flush() + path = tmp_path / 'api.xlsx'; path.write_bytes(b'api-content') + _artifact(task, path, _seed_artifact_dependencies(), no='EXP-API') + db.session.commit() + token = issue_local_access_token(user) + + response = client.post( + '/api/workspace/shipping-exports/archive', json={'batch_no': 'SB-API-ZIP'}, + headers={'Authorization': f'Bearer {token}'}, + ) + assert response.status_code == 200 + assert response.mimetype == 'application/zip' + assert 'attachment' in response.headers['Content-Disposition'] diff --git a/backend/tests/test_shipping_inventory_configuration.py b/backend/tests/test_shipping_inventory_configuration.py new file mode 100644 index 00000000..0e06608f --- /dev/null +++ b/backend/tests/test_shipping_inventory_configuration.py @@ -0,0 +1,337 @@ +""" +tests/test_shipping_inventory_configuration.py + +用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。 +依赖:Flask app/db、库存配置模型、credential_crypto、inventory_source_repository。 +逻辑:阶段二前锁定最小数据安全与关系约束,避免错误配置进入路由或 RPA 执行链路。 +""" + +from __future__ import annotations + +from cryptography.fernet import Fernet +import pytest +from sqlalchemy.exc import IntegrityError + +from app.core.errors import ServiceUnavailableError, ValidationError +from app.extensions import db +from app.models import ( + ShippingExcelTemplate, ShippingInventoryExternalMapping, ShippingInventoryFile, + ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource, + ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, + ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask, +) +from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential +from app.services.shipping_notice.inventory_source_repository import validate_source_profile +from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source +from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse + + +def _profile(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> ShippingRpaProfile: + """构造最小可持久化 RPA Profile,避免测试包含明文真实凭据。""" + return ShippingRpaProfile( + profile_code=code, + display_name=code, + connector_type=connector_type, + login_url='https://example.invalid/login', + login_config_json={'auth_mode': 'password'}, + ) + + +def _source(profile: ShippingRpaProfile, *, code: str = 'DBS_DUB', mode: str = 'fixed') -> ShippingInventorySource: + """构造固定或动态 Warehouse 的库存源,供约束测试复用。""" + parsing = ShippingInventoryParsingProfile( + profile_code=f'{code}_PARSING', display_name=f'{code} Parsing', version=1, + status='published', file_format='xlsx', definition_json={'match_keys': []}, + ) + template = ShippingExcelTemplate( + template_code=f'{code}_EXPORT', display_name=f'{code} Export', version=1, + status='published', storage_provider='minio', storage_bucket='test', + storage_key=f'test/{code}-export.xlsx', original_filename='template.xlsx', + file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64, + ) + return ShippingInventorySource( + source_code=code, + display_name=code, + connector_type=profile.connector_type, + rpa_profile=profile, + parsing_profile=parsing, + excel_template=template, + warehouse_resolution_mode=mode, + fixed_warehouse_id='DUB' if mode == 'fixed' else None, + ) + + +def test_encrypt_credential_round_trip_requires_runtime_key(app): + """凭据必须依赖环境主密钥加密,且可在受控运行时回读。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + with app.app_context(): + ciphertext = encrypt_credential('not-a-real-password') + assert ciphertext != 'not-a-real-password' + assert decrypt_credential(ciphertext) == 'not-a-real-password' + + +def test_encrypt_credential_rejects_missing_runtime_key(app): + """关键加密主密钥缺失时拒绝写入凭据,避免产生不可恢复密文。""" + app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = '' + with app.app_context(), pytest.raises(ServiceUnavailableError): + encrypt_credential('not-a-real-password') + + +def test_source_profile_connector_types_must_match(app): + """Source 绑定不同 Driver 的 Profile 必须被服务层拒绝。""" + with app.app_context(), pytest.raises(ValidationError) as exc_info: + validate_source_profile(_source(_profile(connector_type='dbs')), _profile(code='CRANE_01', connector_type='crane')) + assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH' + + +def test_dynamic_source_disallows_fixed_warehouse_in_database(app): + """动态仓 Source 不得保存固定 Warehouse,避免 Crane 配置被误建为单仓。""" + with app.app_context(): + profile = _profile(connector_type='crane') + source = _source(profile, code='CRANE', mode='inventory_match') + source.fixed_warehouse_id = 'TZR' + db.session.add_all([profile, source]) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_external_mapping_allows_topgp_organization_code_to_be_null(app): + """TOPGP 无公司代码概念时,映射必须允许 NULL 而非伪造占位值。""" + with app.app_context(): + profile = _profile() + source = _source(profile) + mapping = ShippingInventoryExternalMapping( + inventory_source=source, + freight_warehouse_id='DUB', + external_system_code='TOPGP', + external_organization_code=None, + external_site_code='EU01', + external_warehouse_code='DUB01', + external_warehouse_name='Dublin Warehouse', + ) + db.session.add(mapping) + db.session.commit() + assert mapping.id is not None + + +def test_database_source_snapshot_excludes_profile_credentials(app): + """运行时 Source 快照只提供操作配置,禁止泄漏 Profile 凭据字段。""" + with app.app_context(): + profile = _profile() + profile.username_ciphertext = 'ciphertext' + profile.password_ciphertext = 'ciphertext' + source = _source(profile) + db.session.add(source) + db.session.commit() + payload = get_database_inventory_source('DBS_DUB') + assert payload is not None + assert payload['source_code'] == 'DBS_DUB' + assert 'username_ciphertext' not in payload + assert 'password_ciphertext' not in payload + + +def test_database_source_snapshot_uses_source_business_report_configuration(app): + """运行时快照必须从 Source 读取报表路径和查询条件,不得从 Profile 读取旧报表配置。""" + with app.app_context(): + profile = _profile() + profile.login_config_json = {'auth_mode': 'password'} + source = _source(profile) + source.report_path_json = { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'Source Report', + } + source.query_parameters_json = [ + {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, + ] + source.match_aliases_json = ['DUB', 'Dublin'] + db.session.add(source) + db.session.commit() + + payload = get_database_inventory_source('DBS_DUB') + assert payload is not None + assert payload['navigation']['report_name'] == 'Source Report' + assert payload['parameters'][0]['name'] == 'Warehouse' + assert payload['match_aliases_json'] == ['DUB', 'Dublin'] + assert 'operation_config' not in payload + assert payload['login_config'] == {'auth_mode': 'password'} + + +def test_rpa_trigger_snapshot_keeps_profile_credentials_encrypted(app): + """RPA 专用快照可投递密文,但任何运行时普通读取不得获得该字段。""" + with app.app_context(): + profile = _profile() + profile.username_ciphertext = 'encrypted-user' + profile.password_ciphertext = 'encrypted-password' + db.session.add(_source(profile)) + db.session.commit() + payload = get_rpa_trigger_inventory_source('DBS_DUB') + assert payload is not None + assert payload['credential_envelope'] == { + 'username_ciphertext': 'encrypted-user', + 'password_ciphertext': 'encrypted-password', + } + + +def test_external_mapping_prefers_exact_warehouse_then_source_default(app): + """同一 Source 的动态仓先命中精确映射,未命中时才回退默认外部系统仓库。""" + with app.app_context(): + profile = _profile(code='CRANE_EU', connector_type='crane') + source = _source(profile, code='CRANE', mode='inventory_match') + exact = ShippingInventoryExternalMapping( + inventory_source=source, freight_warehouse_id='FRA', external_system_code='TOPGP', + external_warehouse_code='FRA01', external_warehouse_name='Frankfurt', + ) + fallback = ShippingInventoryExternalMapping( + inventory_source=source, freight_warehouse_id=None, external_system_code='TOPGP', + external_warehouse_code='CRANE_DEFAULT', external_warehouse_name='Crane Default', + ) + db.session.add_all([exact, fallback]) + db.session.commit() + + assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='FRA')['external_warehouse_code'] == 'FRA01' + assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='fra')['external_warehouse_code'] == 'FRA01' + assert resolve_external_warehouse(source_code='CRANE', freight_warehouse_id='SIN')['external_warehouse_code'] == 'CRANE_DEFAULT' + + +def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, tmp_path): + """动态 Source 只能以订单键命中的库存行确定 Warehouse,不能按库存数量挑选。""" + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version + from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context + + with app.app_context(): + source = _source(_profile(code='CRANE_PROFILE', connector_type='crane'), code='CRANE', mode='inventory_match') + inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + part_field = ShippingOrderField(id='dynamic-order-part', schema=schema, field_code='part_number', scope='line', value_type='string') + reservation_field = ShippingOrderField(id='dynamic-order-reservation', schema=schema, field_code='reservation_id', scope='line', value_type='string') + version = ShippingOrderSchemaVersion( + schema=schema, version=1, status='published', checksum='d' * 64, + definition_json={'fields': [ + {'id': part_field.id, 'field_code': part_field.field_code, 'scope': 'line', 'value_type': 'string'}, + {'id': reservation_field.id, 'field_code': reservation_field.field_code, 'scope': 'line', 'value_type': 'string'}, + ]}, + ) + source.parsing_profile.definition_json = { + 'field_mapping': { + inventory_fields['part_number']: 'Part', + inventory_fields['reservation_id']: 'Reservation', + inventory_fields['available_qty']: 'Qty', + inventory_fields['warehouse_id']: 'Warehouse', + }, + 'match_keys': [ + {'order_field_id': part_field.id, 'inventory_field_id': inventory_fields['part_number']}, + {'order_field_id': reservation_field.id, 'inventory_field_id': inventory_fields['reservation_id']}, + ], + } + db.session.add(source) + db.session.add_all([schema, part_field, reservation_field, version]) + db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='d' * 64, status='accepted') + db.session.add(extraction) + db.session.flush() + order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1') + db.session.add(order_line) + db.session.flush() + part_decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id, + decision_status='accepted', resolved_value_json='A001', + ) + reservation_decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id, + decision_status='accepted', resolved_value_json='R-1', + ) + db.session.add_all([part_decision, reservation_decision]) + db.session.flush() + db.session.add_all([ + ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=order_line.id, field_id=part_field.id, + value_text='A001', decision_id=part_decision.id, + ), + ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=order_line.id, field_id=reservation_field.id, + value_text='R-1', decision_id=reservation_decision.id, + ), + ]) + task = ShippingTask( + task_no='SN-DYNAMIC-WH', source_type='manual', inventory_source_code='CRANE', + inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule', + current_order_extraction_id=extraction.id, + ) + task.inventory_source_config_version = inventory_sources_runtime_version() + task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) + path = tmp_path / 'dynamic.xlsx' + path.write_bytes(b'not-parsed-in-this-test') + snapshot = ShippingInventoryFile( + inventory_file_no='SIF-DYNAMIC-WH', storage_path=str(path), snapshot_status='ready', + source_code='CRANE', warehouse_id='FALLBACK', share_mode='warehouse_pool', + inventory_lines_json=[ + { + inventory_fields['part_number']: 'A001', inventory_fields['reservation_id']: 'R-1', + inventory_fields['warehouse_id']: 'FRA', inventory_fields['available_qty']: 1, + }, + { + inventory_fields['part_number']: 'OTHER', inventory_fields['reservation_id']: 'R-2', + inventory_fields['warehouse_id']: 'SIN', inventory_fields['available_qty']: 999, + }, + ], + ) + db.session.add_all([task, snapshot]) + db.session.commit() + link = link_snapshot_to_task(task, snapshot, reason='dynamic_test') + assert link is not None + assert task.inventory_warehouse_id == 'FRA' + assert link.matched_warehouse_id == 'FRA' + + +def test_dynamic_source_rejects_ambiguous_warehouse_for_same_order_key(app, tmp_path): + """同一 Reservation + PN 对应多个 Warehouse 时必须拒绝关联,防止错误业务路由。""" + from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version + from app.services.shipping_notice.inventory_source_rules import compute_routing_fingerprint, extract_routing_context + + with app.app_context(): + source = _source(_profile(code='CRANE_AMBIG_PROFILE', connector_type='crane'), code='CRANE_AMBIG', mode='inventory_match') + db.session.add(source) + db.session.commit() + task = ShippingTask( + task_no='SN-DYNAMIC-AMBIG', source_type='manual', inventory_source_code='CRANE_AMBIG', + inventory_connector_type='crane', inventory_source_status='resolved', inventory_source_method='rule', + lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}], + ) + task.inventory_source_config_version = inventory_sources_runtime_version() + task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) + path = tmp_path / 'ambiguous.xlsx' + path.write_bytes(b'not-parsed-in-this-test') + snapshot = ShippingInventoryFile( + inventory_file_no='SIF-DYNAMIC-AMBIG', storage_path=str(path), snapshot_status='ready', + source_code='CRANE_AMBIG', warehouse_id='FALLBACK', share_mode='warehouse_pool', + inventory_lines_json=[ + {'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'FRA', 'available_qty': 1}, + {'part_number': 'A001', 'reservation_id': 'R-1', 'warehouse_id': 'SIN', 'available_qty': 1}, + ], + ) + db.session.add_all([task, snapshot]) + db.session.commit() + assert link_snapshot_to_task(task, snapshot, reason='dynamic_test') is None + assert task.inventory_warehouse_id is None + + +def test_dynamic_snapshot_is_idempotent_per_rpa_run(app, tmp_path): + """同一 RPA run 的动态多仓文件只能入库一次,避免回调重放产生重复快照。""" + with app.app_context(): + first = ShippingInventoryFile( + inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-1', storage_path=str(tmp_path / 'first.xlsx'), + snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1', + ) + second = ShippingInventoryFile( + inventory_file_no='SIF-DYNAMIC-IDEMPOTENT-2', storage_path=str(tmp_path / 'second.xlsx'), + snapshot_status='ready', source_code='CRANE', warehouse_id=None, rpa_run_no='RUN-DYNAMIC-1', + ) + db.session.add(first) + db.session.commit() + db.session.add(second) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() diff --git a/backend/tests/test_shipping_inventory_routing_engine.py b/backend/tests/test_shipping_inventory_routing_engine.py new file mode 100644 index 00000000..0d2c1a82 --- /dev/null +++ b/backend/tests/test_shipping_inventory_routing_engine.py @@ -0,0 +1,136 @@ +""" +tests/test_shipping_inventory_routing_engine.py + +用途:验证通用库存源路由规则的候选、优先级和冲突裁决。 +依赖:库存路由模型、inventory_routing_engine、Flask 测试数据库。 +逻辑:锁定 Reservation ID 兜底规则只是受控事实字段之一,规则引擎不会执行 RPA 或猜测 Warehouse。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app.extensions import db +from app.models import ( + ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction, + ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask, +) +from app.services.shipping_notice.order_schema import service as order_schema_service +from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules + + +def _rule(*, code: str, priority: int, action: str, sources: list[str], value: object, operator: str = 'prefix'): + """构造一个已发布的行级 Reservation ID 路由规则。""" + return ShippingInventoryRoutingRule( + rule_code=code, + rule_name=code, + scope='line', + priority=priority, + match_mode='all', + status='published', + action_type=action, + action_payload_json={'source_codes': sources}, + version=1, + conditions=[ + ShippingInventoryRoutingRuleCondition( + condition_group=1, + source_kind='system_fact', + system_fact_key='line.reservation_id', + operator=operator, + expected_value_json=value, + sequence=1, + ) + ], + ) + + +def _task() -> SimpleNamespace: + """提供最小任务事实,确保路由测试只依赖显式输入。""" + return SimpleNamespace( + customer_code=None, destination_country=None, destination_city=None, + destination_port=None, warehouse_hint=None, order_type=None, sender_email=None, + current_order_extraction_id=None, + ) + + +def test_prefix_rule_returns_ambiguous_source_candidates(app): + """前缀 1 规则只产生 DUB/RTM 候选,不在路由阶段擅自选择 Source。""" + with app.app_context(): + db.session.add(_rule(code='RSV_PREFIX_1', priority=100, action='add_source_candidates', sources=['DBS_DUB', 'DBS_RTM'], value='1')) + db.session.commit() + result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '1000123456'}) + assert result.status == 'ambiguous' + assert result.source_codes == ('DBS_DUB', 'DBS_RTM') + + +def test_higher_priority_document_rule_wins_over_reservation_fallback(app): + """高优先级规则覆盖兜底规则,体现明确业务事实优先于通用前缀。""" + with app.app_context(): + db.session.add_all([ + _rule(code='RSV_PREFIX_1', priority=100, action='add_source_candidates', sources=['DBS_DUB', 'DBS_RTM'], value='1'), + _rule(code='RSV_FIXED_DUB', priority=200, action='add_source_candidates', sources=['DBS_DUB'], value='1000123456', operator='equals'), + ]) + db.session.commit() + result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '1000123456'}) + assert result.status == 'resolved' + assert result.source_codes == ('DBS_DUB',) + + +def test_five_digit_reservation_rule_can_route_to_crane(app): + """五位纯数字经 numeric_length 规则产生 Crane Source,最终 Warehouse 仍留给库存行匹配。""" + with app.app_context(): + db.session.add(_rule(code='RSV_LENGTH_5', priority=100, action='add_source_candidates', sources=['CRANE'], value=5, operator='numeric_length')) + db.session.commit() + result = evaluate_inventory_source_rules(task=_task(), line={'reservation_id': '12345'}) + assert result.status == 'resolved' + assert result.source_codes == ('CRANE',) + + +def test_dynamic_order_field_value_routes_inventory_source(app): + """路由条件引用稳定订单 field_id,并从 Task 当前 Extraction 读取行值。""" + with app.app_context(): + order_schema_service.initialize_schema({'display_name': '路由字段'}, actor_id=None) + field = order_schema_service.save_field( + {'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None, + ) + draft = order_schema_service.create_draft({}, actor_id=None) + saved_schema = order_schema_service.save_draft(draft['id'], {'fields': [{ + 'field_id': field['id'], 'display_name': 'Reservation', 'required': True, 'aliases': [], + 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id'], 'enum_options': [], + 'evidence_policy': {'required': True, 'source_precedence': ['attachment_text'], 'conflict_policy': 'block', 'allow_single_source': True}, + 'relation_role': None, 'comparator_key': 'reservation_id', + }], 'expected_lock_version': draft['lock_version']}) + order_schema_service.publish( + draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'], + ) + task = ShippingTask(task_no='SN-DYNAMIC-ROUTE', user_id=None, source_type='manual') + db.session.add(task) + db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=draft['id'], input_snapshot_hash='d' * 64, status='accepted', task_id=task.id) + db.session.add(extraction) + db.session.flush() + line = ShippingOrderLine(extraction_id=extraction.id, position=0) + db.session.add(line) + db.session.flush() + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_status='accepted', + supporting_observation_ids_json=[], resolved_value_json='1000123456', + ) + db.session.add(decision) + db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=line.id, field_id=field['id'], decision_id=decision.id, + value_text='1000123456', value_json='1000123456', + )) + task.current_order_extraction_id = extraction.id + rule = _rule(code='DYNAMIC_RSV', priority=200, action='add_source_candidates', sources=['DBS_DUB'], value='1') + condition = rule.conditions[0] + condition.source_kind = 'order_field' + condition.system_fact_key = None + condition.order_field_id = field['id'] + db.session.add(rule) + db.session.commit() + + result = evaluate_inventory_source_rules(task=task, line={'_position': 0}) + assert result.status == 'resolved' + assert result.source_codes == ('DBS_DUB',) diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py index 32b65793..5195147a 100644 --- a/backend/tests/test_shipping_notice_batches.py +++ b/backend/tests/test_shipping_notice_batches.py @@ -21,10 +21,13 @@ from app.models import ( Job, KbJob, ShippingBatch, + ShippingCase, + ShippingCustomer, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, ShippingTaskEvent, + ShippingTemporaryInventorySession, User, ) from app.core.auth.jwt import issue_local_access_token @@ -36,6 +39,24 @@ from app.services.shipping_notice.progress_workflow import auto_progress from tests.conftest import seed_task_inventory_source +def _confirm_direct_task_customer(task: ShippingTask) -> None: + """为直接构造且聚焦客户门禁后流程的任务补齐已确认客户。""" + customer = ShippingCustomer.query.filter_by(short_code='BAT').one_or_none() + if customer is None: + customer = ShippingCustomer( + standard_name='批次流程测试客户', short_code='BAT', status='active', + ) + db.session.add(customer) + db.session.flush() + task.shipping_case = ShippingCase( + case_no=f'CASE-{task.task_no}', customer=customer, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + ) + task.customer_resolution_status = 'confirmed' + task.customer_resolution_method = 'test_fixture' + + def _tool_headers(app): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["INTEGRATION_API_KEY"] = "test-integration-key" @@ -636,8 +657,8 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path): """库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。""" app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop") - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = "" + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = "" with app.app_context(): user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com") db.session.add(user) @@ -660,6 +681,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path): } }, ) + _confirm_direct_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add(task) db.session.commit() @@ -686,7 +708,7 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 5 - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers") with app.app_context(): user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first() assert user is not None @@ -740,12 +762,12 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli assert not list((tmp_path / "inventory_triggers").glob("inventory_export_*.json")) -def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_path): - """目的地 DUB 应解析到 DSV360_AWSDU,并写入 RPA 库存导出 trigger。""" +def test_auto_progress_resolves_dub_source_without_implicitly_triggering_rpa(app, tmp_path): + """自动推进可解析 Dublin 库存源,但正式 RPA 刷新必须由用户明确触发。""" app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop") - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers") app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False with app.app_context(): user = User(username="shipping_inventory_source_user", email="shipping_inventory_source_user@example.com") @@ -759,47 +781,40 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p parse_confidence=0.95, raw_content="Ship to Dublin DUB\nA001 x 10", ship_to="Dublin", + destination_code="DUB", lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}], step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}}, ) + _confirm_direct_task_customer(task) db.session.add(task) db.session.commit() result = auto_progress({"task_id": task.task_no, "mode": "auto"}) db.session.refresh(task) - assert result["status"] == "running" - source = task.step_payload_json["rpa_inventory_source"] - assert source["source_code"] == "DSV360_AWSDU" + assert result["status"] == "needs_human" + assert result["checkpoint"] == "upload_req" + assert task.inventory_source_code == "DSV360_AWSDU" trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json" - assert trigger_path.exists() - trigger_text = trigger_path.read_text(encoding="utf-8") - assert '"source_code": "DSV360_AWSDU"' in trigger_text - assert '"connector_type": "dsv360"' in trigger_text + assert not trigger_path.exists() -def test_inventory_source_rules_cover_dsv360_programs(app): - """截图中的 DSV 360 Program 均应能通过别名解析到对应库存源。""" +def test_inventory_source_rules_resolve_configured_dublin_source(app): + """数据库中已发布的 Dublin 规则应解析到已启用库存站点。""" from app.services.shipping_notice.inventory_source_rules import resolve_inventory_source - cases = [ - ("BYAWSATL01", "DSV360_AWSBI_BYAWSATL01"), - ("Cincinnati", "DSV360_AWSCV"), - ("Moerdijk", "DSV360_AWSAMS"), - ] with app.app_context(): - for ship_to, expected_code in cases: - task = ShippingTask( - task_no=f"SN-INVENTORY-SOURCE-{expected_code}", - source_type="pdf", - process_status="parsed", - ship_to=ship_to, - lines_json=[{"sku": "A001", "qty": 10}], - ) - resolution = resolve_inventory_source(task) + task = ShippingTask( + task_no="SN-INVENTORY-SOURCE-DSV360-AWSDU", + source_type="pdf", + process_status="parsed", + destination_code="DUB", + lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 10}], + ) + resolution = resolve_inventory_source(task) - assert resolution.status == "resolved" - assert resolution.source_code == expected_code + assert resolution.status == "resolved" + assert resolution.source_code == "DSV360_AWSDU" def test_auto_progress_unknown_destination_requires_inventory_source_review(app): @@ -820,6 +835,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app) ship_to="Mystery Port", lines_json=[{"sku": "A001", "qty": 10}], ) + _confirm_direct_task_customer(task) db.session.add(task) db.session.commit() @@ -831,7 +847,7 @@ def test_auto_progress_unknown_destination_requires_inventory_source_review(app) assert task.process_status == "pending_review" assert task.pending_human_reason == "inventory_source_unresolved" assert task.step_payload_json["inventory_source_resolution"]["status"] == "unresolved" - assert len(result["data"]["inventory_source_candidates"]) >= 4 + assert len(result["data"]["inventory_source_candidates"]) == 1 def test_inventory_source_review_chat_actions_return_source_buttons(app): @@ -904,12 +920,11 @@ def test_inventory_source_review_chat_actions_do_not_list_all_sources(app): assert [item["id"] for item in ui_state["action_buttons"]] == [ "confirm_inventory_source", "retry_resolve_inventory_source", - "upload_inventory_file", ] def test_parse_stage_ui_state_lists_all_issues(app): - """文件解析阶段 UI State 应一次列出库存源问题、解析 warnings(含存量延后低置信度提示)。""" + """库存源检查点应列出当前库存源问题和解析警告,不生成旧顺序延后复核提示。""" from app.services.shipping_notice.ui_state import build_task_ui_state with app.app_context(): @@ -921,7 +936,6 @@ def test_parse_stage_ui_state_lists_all_issues(app): error_message="无法根据发货通知唯一确定库存查询来源", parse_confidence=0.4, step_payload_json={ - "pending_parse_review_after_source": True, "inventory_source_resolution": {"status": "unresolved", "candidates": []}, "parse_validation": { "status": "needs_review", @@ -955,8 +969,7 @@ def test_parse_stage_ui_state_lists_all_issues(app): assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues assert "解析引擎回退到启发式规则,请人工核对字段。" in issues assert "第 1 行料号 A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues - assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues - assert len(issues) == 5 + assert len(issues) == 4 def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client): @@ -1001,7 +1014,7 @@ def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client) assert task_state["checkpoint"] == "shortage_review" assert [item["id"] for item in task_state["action_buttons"]] == [ - "reparse_inventory", + "retry_rpa", "rematch", "reject", ] @@ -1933,6 +1946,120 @@ def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explici assert runtime_context["refs"] == {"run_purpose": "chat_turn"} +def test_build_dify_chat_inputs_restores_pending_temporary_inventory_session(app): + """临时库存确认跨回合时应从 HXOPS 数据库恢复会话号,而不是依赖 Dify 隐式记忆。""" + with app.app_context(): + conversation_id = 'conv-temp-inventory-resume-001' + user = User(username='temp_resume_user', email='temp-resume@example.com', role='user', status='active') + user.set_password('password') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no='FA-TEMP-RESUME-001', owner_user_id=user.id, original_filename='inventory.xls', + storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.xls', + content_hash='a' * 64, file_size=16, extension='.xls', upload_status='ready', + ) + db.session.add(asset) + db.session.flush() + pending = ShippingTemporaryInventorySession( + session_no='TIS-RESUME-001', user_id=user.id, conversation_id=conversation_id, + asset_id=asset.id, declared_intent='inventory_candidate', + file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation', + expires_at=datetime.utcnow() + timedelta(hours=1), + ) + db.session.add(pending) + db.session.commit() + + inputs = dify_inputs.build_dify_chat_inputs(conversation_id) + runtime_context = json.loads(inputs['agent_runtime_context']) + + assert runtime_context['refs']['temporary_inventory_session_no'] == pending.session_no + assert runtime_context['refs']['run_purpose'] == 'chat_turn' + assert 'capability' not in runtime_context['refs'] + + +def test_build_dify_chat_inputs_ignores_expired_or_terminal_temporary_inventory_session(app): + """过期或已确认会话不得继续污染后续聊天运行态。""" + with app.app_context(): + conversation_id = 'conv-temp-inventory-terminal-001' + user = User(username='temp_terminal_user', email='temp-terminal@example.com', role='user', status='active') + user.set_password('password') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no='FA-TEMP-TERMINAL-001', owner_user_id=user.id, original_filename='inventory.csv', + storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.csv', + content_hash='b' * 64, file_size=16, extension='.csv', upload_status='ready', + ) + db.session.add(asset) + db.session.flush() + db.session.add_all([ + ShippingTemporaryInventorySession( + session_no='TIS-EXPIRED-001', user_id=user.id, conversation_id=conversation_id, + asset_id=asset.id, declared_intent='inventory_candidate', + file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation', + expires_at=datetime.utcnow() - timedelta(minutes=1), + ), + ShippingTemporaryInventorySession( + session_no='TIS-CONFIRMED-001', user_id=user.id, conversation_id=conversation_id, + asset_id=asset.id, declared_intent='inventory_candidate', + file_classification_status='inventory_candidate', status='confirmed_for_temporary_use', + expires_at=datetime.utcnow() + timedelta(hours=1), + ), + ]) + db.session.commit() + + inputs = dify_inputs.build_dify_chat_inputs(conversation_id) + runtime_context = json.loads(inputs['agent_runtime_context']) + + assert 'temporary_inventory_session_no' not in runtime_context['refs'] + + +def test_build_dify_chat_inputs_prefers_explicit_temporary_inventory_session(app): + """显式锚点必须优先,便于 UI 精确续办指定的临时库存会话。""" + with app.app_context(): + inputs = dify_inputs.build_dify_chat_inputs( + 'conv-temp-explicit-001', + temporary_inventory_session_no='tis-explicit-001', + ) + runtime_context = json.loads(inputs['agent_runtime_context']) + + assert runtime_context['refs']['temporary_inventory_session_no'] == 'TIS-EXPLICIT-001' + + +def test_build_dify_chat_inputs_does_not_restore_temporary_session_for_backend_orchestrator(app): + """后台订单解析不得继承聊天中的临时库存会话锚点。""" + with app.app_context(): + conversation_id = 'conv-temp-inventory-worker-001' + user = User(username='temp_worker_user', email='temp-worker@example.com', role='user', status='active') + user.set_password('password') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no='FA-TEMP-WORKER-001', owner_user_id=user.id, original_filename='inventory.xlsx', + storage_provider='minio', storage_bucket='test', storage_key='temp/inventory.xlsx', + content_hash='c' * 64, file_size=16, extension='.xlsx', upload_status='ready', + ) + db.session.add(asset) + db.session.flush() + db.session.add(ShippingTemporaryInventorySession( + session_no='TIS-WORKER-001', user_id=user.id, conversation_id=conversation_id, + asset_id=asset.id, declared_intent='inventory_candidate', + file_classification_status='inventory_candidate', status='awaiting_mapping_confirmation', + expires_at=datetime.utcnow() + timedelta(hours=1), + )) + db.session.commit() + + inputs = dify_inputs.build_dify_chat_inputs( + conversation_id, + trigger_source='backend_orchestrator', + ) + runtime_context = json.loads(inputs['agent_runtime_context']) + + assert 'temporary_inventory_session_no' not in runtime_context['refs'] + assert runtime_context['refs']['run_purpose'] == 'parse_notice' + + def test_shipping_notice_agent_code_from_resolver(): """发货通知识别应基于 resolve_agent_code,不再提供 dify_inputs 名称启发式。""" from app.services.agent_registry.resolver import resolve_agent_code diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py index 0a2b5788..f38f2515 100644 --- a/backend/tests/test_shipping_notice_business_case.py +++ b/backend/tests/test_shipping_notice_business_case.py @@ -6,7 +6,10 @@ backend/tests/test_shipping_notice_business_case.py 逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。 """ +import pytest + from app import db +from app.core.errors import ConflictError 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 @@ -52,20 +55,20 @@ def test_revision_inherits_existing_parent_case(app): assert ShippingCase.query.count() == 1 -def test_revision_backfills_case_for_legacy_parent(app): - """历史父任务没有业务单时,首次修订应补建并复用同一业务单。""" +def test_revision_rejects_parent_without_business_case(app): + """修订父任务缺少业务单时必须阻断,禁止隐式补建。""" with app.app_context(): parent = _task('SN-CASE-LEGACY-1') db.session.add(parent) db.session.flush() - 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 + with pytest.raises(ConflictError) as exc_info: + resolve_shipping_case_for_new_task( + supersedes_task_id=parent.id, + duplicate_resolution_type='revision', + ) + assert exc_info.value.code == 'SHIPPING_NOTICE.REVISION_CASE_MISSING' + assert ShippingCase.query.count() == 0 def test_revision_chain_reuses_root_case(app): diff --git a/backend/tests/test_shipping_notice_inventory_aws.py b/backend/tests/test_shipping_notice_inventory_aws.py index 1359f5e5..2b344b39 100644 --- a/backend/tests/test_shipping_notice_inventory_aws.py +++ b/backend/tests/test_shipping_notice_inventory_aws.py @@ -3,6 +3,7 @@ from pathlib import Path from openpyxl import Workbook +import pytest from app.services.shipping_notice.inventory_snapshot import ( parse_inventory_excel_with_meta, @@ -104,18 +105,26 @@ def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app): "aws_part_number": "AWS Sku", "reservation_id": "COM ID", "available_qty": "Qty Available", + "odm_id": "ODM ID", }, ) assert lines[0]["odm_id"] == "16754796" def test_match_aggregates_same_part_number_reservation(): - notice = [{"part_number": "D4-A", "reservation_id": "AWS-311", "qty": 3}] + notice = [{"order-sku": "D4-A", "order-ref": "AWS-311", "__required_qty": 3}] inventory = [ - {"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1}, - {"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2}, + {"501": "D4-A", "502": "AWS-311", "503": 1}, + {"501": "D4-A", "502": "AWS-311", "503": 2}, ] - status, results, _ = match_notice_lines(notice, inventory) + status, results, _ = match_notice_lines( + notice, inventory, + match_keys=[ + {'order_field_id': 'order-sku', 'inventory_field_id': '501'}, + {'order_field_id': 'order-ref', 'inventory_field_id': '502'}, + ], + quantity_field_id='503', + ) assert status == "fulfillable" assert results[0]["available_qty"] == 3.0 @@ -163,9 +172,45 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path): assert any(line["part_number"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed) +def test_inventory_parser_uses_configured_worksheet_and_rejects_missing_sheet(tmp_path): + """多 Sheet 库存文件必须读取 Profile 指定工作表,错误名称不得静默回退 active sheet。""" + from openpyxl import Workbook + from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta + + path = tmp_path / 'multi-sheet.xlsx' + workbook = Workbook() + workbook.active.title = 'Instructions' + workbook.active.append(['Do not parse this sheet']) + data = workbook.create_sheet('Inventory') + data.append(['Supplier Sku', 'Reservation ID', 'Qty Available']) + data.append(['PN-1', 'RSV-1', 5]) + workbook.save(path) + + mapping = { + 'part_number': 'Supplier Sku', 'reservation_id': 'Reservation ID', + 'available_qty': 'Qty Available', + } + lines, meta = parse_inventory_excel_with_meta( + path, field_mapping=mapping, header_row_index=1, sheet_name='Inventory', + ) + assert lines[0]['part_number'] == 'PN-1' + assert meta['sheet_name'] == 'Inventory' + + with pytest.raises(ValueError, match='Inventory worksheet not found'): + parse_inventory_excel_with_meta( + path, field_mapping=mapping, header_row_index=1, sheet_name='Missing', + ) def test_match_extracts_reservation_id_suffix(): - notice = [{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}] - inventory = [{"part_number": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}] - status, results, _ = match_notice_lines(notice, inventory) - assert status == "fulfillable" - assert results[0]["available_qty"] == 1.0 + """通用库存匹配不再对某个字段名称执行隐藏的 Reservation 特殊截取。""" + notice = [{"order-part": "A001", "order-ref": "1000140351", "__required_qty": 1}] + inventory = [{"601": "A001", "602": "ADU_S-ENCWIW260528126265@1000140351", "603": 1}] + status, results, _ = match_notice_lines( + notice, inventory, + match_keys=[ + {'order_field_id': 'order-part', 'inventory_field_id': '601'}, + {'order_field_id': 'order-ref', 'inventory_field_id': '602'}, + ], + quantity_field_id='603', + ) + assert status == "unfulfillable" + assert results[0]["available_qty"] == 0.0 diff --git a/backend/tests/test_shipping_notice_inventory_rpa_archive.py b/backend/tests/test_shipping_notice_inventory_rpa_archive.py index 22704a7e..93ab9f2f 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_archive.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_archive.py @@ -125,7 +125,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app): def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path): """finalize 预生成应落盘 ZIP 并返回 summary 字段。""" archive_dir = tmp_path / "inventory_archives" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" xlsx.write_bytes(b"fake-xlsx-content") @@ -169,7 +169,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path): """无可读快照时不生成 ZIP。""" archive_dir = tmp_path / "inventory_archives" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) with app.app_context(): run = _make_inventory_run_with_created( @@ -186,7 +186,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path): """created 有记录但磁盘文件缺失时不应生成 ZIP。""" archive_dir = tmp_path / "inventory_archives" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) with app.app_context(): run = _make_inventory_run_with_created( @@ -212,7 +212,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path): """下载解析应返回归档路径与建议文件名。""" archive_dir = tmp_path / "inventory_archives" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" xlsx.write_bytes(b"fake-xlsx-content") @@ -253,7 +253,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app): def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path): """summary 指向归档目录外的真实文件时必须 404。""" archive_dir = tmp_path / "inventory_archives" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) outside_zip = tmp_path / "outside.zip" outside_zip.write_bytes(b"fake-zip") @@ -277,7 +277,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path """summary 指向非 .zip 后缀文件时必须 404。""" archive_dir = tmp_path / "inventory_archives" archive_dir.mkdir(parents=True) - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt" fake_file.write_bytes(b"not-a-zip") @@ -405,7 +405,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke app.config["WECOM_NOTIFY_ENABLED"] = True app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com" app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives") + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives") user = User( username="wecom_jump_user", @@ -473,7 +473,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename( ): """admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。""" archive_dir = tmp_path / "inventory_archives" - app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" xlsx.write_bytes(b"fake-xlsx-content") diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index c25e4a21..7947fdcb 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -1,7 +1,7 @@ """shipping_notice inventory_rpa_workflow 单测。 覆盖 RPA 库存子模块与 inventory_workflow 的委托边界: -1. ensure_inventory(mode=auto) 触发 running 并写入 trigger 事件。 +1. ensure_inventory(mode=auto) 仅复用已有快照,绝不触发 RPA。 2. rpa_report_inventory 回调会把文件正式落到 inventory_uploads,并进入字段映射确认。 """ @@ -11,7 +11,10 @@ from pathlib import Path import pytest from app import db -from app.models import ShippingCustomer, ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink +from app.models import ( + ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, + ShippingRpaProfile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink, +) from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source @@ -19,6 +22,30 @@ def _tool_headers(): return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"} +def _confirm_direct_rpa_task_customer(task: ShippingTask) -> None: + """为直接构造的 RPA 回调任务补齐已确认客户。 + + 核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户, + 使回调测试只验证 RPA 契约,而不绕过客户身份门禁。 + """ + customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none() + if customer is None: + customer = ShippingCustomer( + standard_name='RPA 直接回调测试客户', short_code='RPC', status='active', + ) + db.session.add(customer) + db.session.flush() + case = ShippingCase( + case_no=f'CASE-{task.task_no}', customer=customer, + customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code, + ) + task.shipping_case = case + task.customer_resolution_status = 'confirmed' + task.customer_resolution_method = 'test_fixture' + db.session.add_all([case, task]) + db.session.flush() + + @pytest.fixture(autouse=True) def _confirmed_customer_for_rpa_flows(app, monkeypatch): """为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。""" @@ -69,15 +96,15 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction(): ) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。" -def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monkeypatch): - """mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。""" +def test_ensure_inventory_auto_does_not_trigger_rpa_when_snapshot_is_missing(app, client, tmp_path, monkeypatch): + """正常 auto 未命中库存快照时应转缺库存,且不得写入 RPA trigger。""" monkeypatch.setattr( "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", lambda *args, **kwargs: None, ) trigger = tmp_path / "triggers" trigger.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False @@ -112,34 +139,155 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monke json={"task_id": task_id, "mode": "auto"}, ) body = inv_res.get_json() - assert body["status"] == "running" - assert body.get("data", {}).get("rpa", {}).get("attempts") == 1 - assert "1/1" not in body.get("message", "") - assert "360s" not in body.get("message", "") - assert "长时间无结果" in body.get("message", "") + assert body["status"] == "needs_human" + assert "暂无可用库存数据" in body.get("message", "") with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None - assert task.pending_human_reason == "rpa_pending" - progress = (task.step_payload_json or {}).get("current_step_progress") or {} - assert progress.get("detail") == "当前配置为单次自动尝试" events = ( ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered") .all() ) - assert len(events) == 1 + assert len(events) == 0 + assert not list(trigger.glob("inventory_export_*.json")) -def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path, monkeypatch): - """RPA 回调成功落盘后应进入字段映射确认(align_review / map_infer)。""" +def test_ensure_inventory_auto_reuses_snapshot_without_rpa(app, client, monkeypatch): + """正常 auto 命中已有快照时应直接返回复用结果,不得进入 RPA 编排。""" + captured: dict[str, object] = {} + + def _reuse(task, source, *, mode): + captured.update({"task_no": task.task_no, "source": source, "mode": mode}) + return {"status": "ok", "message": "已复用库存快照", "data": {"reused": True}} + + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", + _reuse, + ) + monkeypatch.setattr( + "app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa", + lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("auto must not invoke RPA")), + ) + app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" + app.config["INTEGRATION_API_KEY"] = "test-integration-key" + + headers = _tool_headers() + create_res = client.post( + "/api/shipping-notice/tools/create_task", + headers=headers, + json={"source_type": "manual"}, + ) + task_id = create_res.get_json()["task_id"] + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "ACME", + "destination": {"port_code": "DUB", "city": "Dublin"}, + "lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + result = client.post( + "/api/shipping-notice/tools/ensure_inventory", + headers=headers, + json={"task_id": task_id, "mode": "auto"}, + ).get_json() + + assert result["status"] == "ok" + assert result["data"]["reused"] is True + assert captured["task_no"] == task_id + assert captured["mode"] == "auto" + + +def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path): + """多个 Source 候选仅按 Reservation + PN 的唯一快照命中确定,数量为零也不改选其他 Source。""" + from app.services.shipping_notice.inventory_source_rules import ( + InventorySourceAdjudication, + resolve_ambiguous_source_from_ready_snapshots, + ) + + source_file = tmp_path / 'source-a.xlsx' + other_file = tmp_path / 'source-b.xlsx' + source_file.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + other_file.write_bytes(inventory_xlsx_with_warehouse('AWSRTM').getvalue()) + + with app.app_context(): + profile = ShippingRpaProfile( + profile_code='DBS_RTM_MATCH_TEST', display_name='DBS RTM', connector_type='dbs', + login_url='https://test.invalid/rtm', login_config_json={'auth_mode': 'password'}, + ) + from app.models import ShippingExcelTemplate, ShippingInventoryParsingProfile + parsing_profile = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first() + excel_template = ShippingExcelTemplate.query.filter_by(template_code='TEST_RUNTIME').first() + rtm_source = ShippingInventorySource( + source_code='DSV360_AWSRTM', display_name='DBS Rotterdam AWSRTM', connector_type='dbs', + rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSRTM', + report_path_json={ + 'program_group': 'Bison', 'program_label': 'AWSRTM', + 'report_group': 'Inventory', 'report_name': 'On Hand', + }, + ) + task = ShippingTask( + task_no='SN-SNAPSHOT-SOURCE-UNIQUE', source_type='manual', + lines_json=[{'part_number': 'A001', 'reservation_id': '1000123456', 'qty': 1}], + ) + source_snapshot = ShippingInventoryFile( + inventory_file_no='SIF-SOURCE-UNIQUE', storage_path=str(source_file), snapshot_status='ready', + source_code='DSV360_AWSDU', warehouse_id='AWSDU', exported_at=datetime.utcnow(), + inventory_lines_json=[{ + 'part_number': 'A001', 'reservation_id': '1000123456', + 'available_qty': 0, 'warehouse_id': 'AWSDU', + }], schema_preview_json={}, + ) + other_snapshot = ShippingInventoryFile( + inventory_file_no='SIF-OTHER-UNIQUE', storage_path=str(other_file), snapshot_status='ready', + source_code='DSV360_AWSRTM', warehouse_id='AWSRTM', exported_at=datetime.utcnow(), + inventory_lines_json=[{ + 'part_number': 'OTHER', 'reservation_id': '1000123456', + 'available_qty': 999, 'warehouse_id': 'AWSRTM', + }], schema_preview_json={}, + ) + db.session.add_all([profile, rtm_source, task, source_snapshot, other_snapshot]) + db.session.commit() + + result = resolve_ambiguous_source_from_ready_snapshots( + task, + InventorySourceAdjudication( + status='ambiguous', + candidates=[ + {'source_code': 'DSV360_AWSDU'}, + {'source_code': 'DSV360_AWSRTM'}, + ], + ), + ) + + assert result.status == 'resolved' + assert result.method == 'snapshot_match' + assert result.source_code == 'DSV360_AWSDU' + assert result.warehouse_id == 'AWSDU' + evidence = result.evidence[-1]['snapshot_candidate_check'] + assert {item['source_code']: item['matched'] for item in evidence} == { + 'DSV360_AWSDU': True, + 'DSV360_AWSRTM': False, + } + + +def test_rpa_report_inventory_callback_uses_published_profile(app, client, tmp_path, monkeypatch): + """RPA 回调必须按库存站点已发布方案解析,不再进入任务级字段映射确认。""" monkeypatch.setattr( "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", lambda *args, **kwargs: None, ) drop = tmp_path / "drop" drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["INTEGRATION_API_KEY"] = "test-integration-key" @@ -166,15 +314,8 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat }, ) - from openpyxl import Workbook - inv_file = drop / "stock.xlsx" - wb = Workbook() - ws = wb.active - ws.append(["Warehouse ID", "料号", "Reservation ID", "可用数量"]) - ws.append(["AWSDU", "A001", "R-1", 20]) - wb.save(inv_file) - wb.close() + inv_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU", qty=20).getvalue()) with app.app_context(): from app import db @@ -195,15 +336,14 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat "file_path": str(inv_file), "run_no": run_no, "source_code": "DSV360_AWSDU", - "site_id": "AWSDU", "warehouse_id": "AWSDU", "rpa_mode": "browser", }, ) data = cb_res.get_json() - assert data["status"] == "needs_human" - assert data.get("checkpoint") in {"align_review", "map_infer"} - assert "confirm_inventory_mapping" in (data.get("human_options") or []) + assert data["status"] == "ok" + assert data.get("checkpoint") == "ready_to_match" + assert "confirm_inventory_mapping" not in (data.get("human_options") or []) assert data.get("data", {}).get("rpa_runtime", {}).get("mode") == "browser" assert data.get("data", {}).get("rpa_runtime", {}).get("label") == "真实 RPA" @@ -227,6 +367,91 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat assert task.inventory_snapshot_id == inv_file.id +def test_manual_task_inventory_upload_uses_published_profile_without_mapping_review(app, tmp_path): + """任务级人工上传必须复用库存站点发布方案,并直接进入待匹配状态。""" + from io import BytesIO + + from werkzeug.datastructures import FileStorage + + from app.services.shipping_notice.inventory_workflow import upload_inventory_file + + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + with app.app_context(): + task = ShippingTask( + task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory', + lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}], + ) + _confirm_direct_rpa_task_customer(task) + seed_task_inventory_source(task, source_code='DSV360_AWSDU') + db.session.add(task) + db.session.commit() + + upload = FileStorage( + stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', qty=8).getvalue()), + filename='manual-stock.xlsx', + ) + result = upload_inventory_file(task.task_no, upload) + db.session.refresh(task) + + assert result['status'] == 'ok' + assert result['checkpoint'] == 'ready_to_match' + assert task.process_status == 'inventory_ready' + assert task.review_status is None + assert task.pending_human_reason is None + snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id) + assert snapshot is not None + assert snapshot.mapping_source == 'parsing_profile' + assert snapshot.mapping_confirmed is True + fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} + assert snapshot.inventory_lines_json[0][fields['part_number']] == 'A001' + assert snapshot.inventory_lines_json[0][fields['reservation_id']] == 'R-1' + assert snapshot.inventory_lines_json[0][fields['available_qty']] == 8 + + +def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path): + """任务级人工上传表头漂移时不得留下快照、任务链接或库存投影。""" + from io import BytesIO + + from openpyxl import Workbook + from werkzeug.datastructures import FileStorage + + from app.services.shipping_notice.inventory_workflow import upload_inventory_file + + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + stream = BytesIO() + workbook = Workbook() + sheet = workbook.active + sheet.append(['Warehouse ID', 'Unexpected Part', 'Reservation ID', 'Qty']) + sheet.append(['AWSDU', 'A001', 'R-1', 8]) + workbook.save(stream) + workbook.close() + stream.seek(0) + + with app.app_context(): + task = ShippingTask( + task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory', + lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}], + ) + _confirm_direct_rpa_task_customer(task) + seed_task_inventory_source(task, source_code='DSV360_AWSDU') + db.session.add(task) + db.session.commit() + + result = upload_inventory_file( + task.task_no, + FileStorage(stream=stream, filename='drifted-stock.xlsx'), + ) + db.session.refresh(task) + + assert result['status'] == 'failed' + assert '结构' in result['message'] or '解析' in result['message'] + assert task.inventory_snapshot_id is None + assert task.inventory_lines_json in (None, []) + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0 + assert not list((tmp_path / 'storage' / 'inventory_uploads').glob('**/inventory.*')) + + def test_rpa_callback_gate_rechecks_order_drift_after_trigger(app, client): """RPA 触发后新增 Reservation 异常或字段冲突时,旧回调必须停止入库。""" app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" @@ -297,7 +522,7 @@ def test_rpa_callback_gate_rechecks_order_drift_after_trigger(app, client): def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, tmp_path): """无库存 skipped 回调应提示人工上传,且不计入 inventory_rpa_failed。""" - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "drop") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "drop") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["INTEGRATION_API_KEY"] = "test-integration-key" @@ -346,7 +571,6 @@ def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, "message": "DSV report has no inventory data", "run_no": "RUN-SKIPPED", "source_code": "DSV360_AWSDU", - "site_id": "AWSDU", "warehouse_id": "AWSDU", "rpa_mode": "browser", }, @@ -422,7 +646,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_mixed.xlsx" @@ -505,8 +729,8 @@ def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_statu assert outcome["failed_count"] == 2 -def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch): - """确认库存源后应立即进入 RPA pending,并写出库存导出 trigger。""" +def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, monkeypatch): + """确认库存源只完成路由,不得隐式进入 RPA pending 或写出 trigger。""" monkeypatch.setattr( "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", lambda *args, **kwargs: None, @@ -516,7 +740,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch trigger = tmp_path / "triggers" trigger.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False @@ -547,21 +771,14 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch result = confirm_inventory_source({"task_id": task.task_no, "source_code": "DSV360_AWSDU"}) db.session.refresh(task) - assert result["status"] == "running" - assert "已触发库存获取" in result["message"] - assert "长时间无结果" in result["message"] - assert "360s" not in result["message"] - assert task.process_status == "waiting_inventory" - assert task.pending_human_reason == "rpa_pending" + assert result["status"] == "ok" + assert "库存源已确认" in result["message"] + assert task.process_status == "parsed" + assert task.pending_human_reason is None assert task.error_message is None - assert task.step_payload_json["rpa_inventory_source"]["source_code"] == "DSV360_AWSDU" - assert task.step_payload_json["current_step_progress"]["detail"] == "当前配置为单次自动尝试" events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all() - assert len(events) == 1 - assert ( - list(trigger.glob("inventory_export_SN-CONFIRM-SOURCE-RPA*.json")) - or list(trigger.glob("inventory_export_batch_TASK-SN-CONFIRM-SOURCE-RPA*.json")) - ) + assert len(events) == 0 + assert not list(trigger.glob("inventory_export_*.json")) def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): @@ -571,7 +788,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "batch_task_success.xlsx" @@ -586,6 +803,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): pending_human_reason="rpa_pending", lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") from tests.conftest import seed_rpa_inventory_trigger @@ -600,10 +818,9 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): "task_no": task.task_no, "status": "success", "success": True, - "file_path": str(sample), - "source_code": task.inventory_source_code, - "site_id": task.inventory_site_id, - "warehouse_id": task.inventory_warehouse_id, + "file_path": str(sample), + "source_code": task.inventory_source_code, + "warehouse_id": task.inventory_warehouse_id, }], }) db.session.refresh(task) @@ -628,6 +845,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): pending_human_reason="rpa_pending", lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") from tests.conftest import seed_rpa_inventory_trigger @@ -671,6 +889,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): pending_human_reason="rpa_pending", lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT") db.session.add(task) @@ -686,6 +905,8 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): db.session.refresh(task) assert result["status"] == "needs_human" + assert result["checkpoint"] == "upload_req" + assert task.pending_human_reason == "rpa_exhausted" failed_events = ShippingTaskEvent.query.filter_by( task_id=task.id, event_type="inventory_rpa_failed", @@ -701,7 +922,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "orphan_task.xlsx" with open(sample, "wb") as handle: @@ -718,7 +939,6 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path): "success": True, "file_path": str(sample), "source_code": "DSV360_AWSDU", - "site_id": "DSV360", "warehouse_id": "AWSDU", }], }) @@ -779,7 +999,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "reuse_ingest_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -852,7 +1072,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") run_no = "RUN-REUSE-MISMATCH" @@ -940,6 +1160,8 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, pending_human_reason="rpa_pending", lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task_a) + _confirm_direct_rpa_task_customer(task_b) seed_task_inventory_source(task_a, source_code="DSV360_AWSDU") seed_task_inventory_source(task_b, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task_a, run_no=run_no) @@ -1003,6 +1225,8 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m pending_human_reason="rpa_pending", lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task_ok) + _confirm_direct_rpa_task_customer(task_fail) seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU") seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task_ok, run_no=run_no) @@ -1062,7 +1286,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "post_commit.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1083,6 +1307,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p pending_human_reason="rpa_pending", lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT") db.session.add(task) @@ -1106,7 +1331,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "promote_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1127,6 +1352,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey pending_human_reason="rpa_pending", lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], ) + _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL") db.session.add(task) @@ -1135,7 +1361,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-PROMOTE-FAIL")) attachment = resolve_task_inventory_upload_path(task.task_no) - assert result["status"] == "needs_human" + assert result["status"] == "ok" warnings = result.get("data", {}).get("post_commit_warnings") or [] assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings) assert attachment is not None and attachment.is_file() @@ -1169,10 +1395,9 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path): inv_file = ShippingInventoryFile( inventory_file_no="SIF-REPAIR-TEST", storage_path=str(snap_file), - snapshot_status="ready", - source_code="DSV360_AWSDU", - site_id="AWSDU", - warehouse_id="AWSDU", + snapshot_status="ready", + source_code="DSV360_AWSDU", + warehouse_id="AWSDU", share_mode="task_only", schema_preview_json={}, exported_at=datetime.utcnow(), @@ -1201,7 +1426,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "move_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1240,7 +1465,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "quarantine_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1330,7 +1555,6 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path): storage_path=str(active_file), snapshot_status="ready", source_code="DSV360_AWSDU", - site_id="AWSDU", warehouse_id="AWSDU", share_mode="task_only", schema_preview_json={}, @@ -1341,7 +1565,6 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path): storage_path=str(other_file), snapshot_status="ready", source_code="DSV360_AWSDU", - site_id="AWSDU", warehouse_id="AWSDU", share_mode="task_only", schema_preview_json={}, @@ -1372,7 +1595,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat processed_dir = tmp_path / "processed" drop_dir.mkdir() processed_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir) quarantine = drop_dir / ".hxops_quarantine" diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py index 89841db7..2d9c7fb0 100644 --- a/backend/tests/test_shipping_notice_inventory_schedule.py +++ b/backend/tests/test_shipping_notice_inventory_schedule.py @@ -80,7 +80,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path): """排程 executor 应写入 inventory_export_batch trigger。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): task = _make_inventory_schedule_task( @@ -112,13 +112,13 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path): """run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): task = _make_inventory_schedule_task( schedule_no="SCH-INV-DEFER", username="schedule_inv_defer_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) db.session.commit() result = run_task_now(task, trigger_type="manual", triggered_by_user_id=None) @@ -134,13 +134,13 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path): """复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): task = _make_inventory_schedule_task( schedule_no="SCH-INV-STARTED-AT", username="schedule_inv_started_at_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) run = ScheduleRun( run_no="RUN20260709080400", @@ -221,11 +221,11 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) """全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。""" drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_excel_fail.xlsx" - _write_sample_inventory(sample, "BYAWSATL01") + _write_sample_inventory(sample, "AWSDU") def _excel_boom(*_args, **_kwargs): raise RuntimeError("excel exploded") @@ -239,7 +239,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) task = _make_inventory_schedule_task( schedule_no="SCH-INV-EXCEL-FAIL", username="schedule_inv_excel_fail_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) run = ScheduleRun( run_no="RUN20260709080700", @@ -250,8 +250,8 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) response_summary_json={ "awaiting_rpa": True, "pending_details": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", "display_name": "ATL01", }], }, @@ -265,7 +265,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) "schedule_run_id": run.id, "trigger_type": "scheduled", "results": [scheduled_rpa_batch_item( - "DSV360_AWSBI_BYAWSATL01", + "DSV360_AWSDU", success=True, file_path=str(sample), )], @@ -286,11 +286,11 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp """finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。""" drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_fail_finalize.xlsx" - _write_sample_inventory(sample, "BYAWSATL01") + _write_sample_inventory(sample, "AWSDU") def _boom(*_args, **_kwargs): raise RuntimeError("finalize exploded") @@ -304,7 +304,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp task = _make_inventory_schedule_task( schedule_no="SCH-INV-FINALIZE-FAIL", username="schedule_inv_finalize_fail_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) run = ScheduleRun( run_no="RUN20260709080600", @@ -315,8 +315,8 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp response_summary_json={ "awaiting_rpa": True, "pending_details": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", "display_name": "ATL01", }], }, @@ -330,7 +330,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp "schedule_run_id": run.id, "trigger_type": "scheduled", "results": [scheduled_rpa_batch_item( - "DSV360_AWSBI_BYAWSATL01", + "DSV360_AWSDU", success=True, file_path=str(sample), )], @@ -350,17 +350,17 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path): drop_dir.mkdir() processed_dir = drop_dir / "processed" processed_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_sample.xlsx" - _write_sample_inventory(sample, "BYAWSATL01") + _write_sample_inventory(sample, "AWSDU") with app.app_context(): task = _make_inventory_schedule_task( schedule_no="SCH-INV-FINALIZE", username="schedule_inv_finalize_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) run = ScheduleRun( run_no="RUN20260709080000", @@ -371,8 +371,8 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path): response_summary_json={ "awaiting_rpa": True, "pending_details": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", "display_name": "ATL01", }], }, @@ -386,7 +386,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path): "schedule_run_id": run.id, "trigger_type": "scheduled", "results": [scheduled_rpa_batch_item( - "DSV360_AWSBI_BYAWSATL01", + "DSV360_AWSDU", success=True, file_path=str(sample), )], @@ -493,7 +493,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path): """回调结果少于触发源数时,排程应 partial_failed。""" drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_partial.xlsx" @@ -562,8 +562,8 @@ def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app): response_summary_json={ "awaiting_rpa": True, "pending_details": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", "display_name": "ATL01", }], }, @@ -577,8 +577,8 @@ def test_finalize_inventory_rpa_schedule_run_with_skipped_callback(app): "schedule_run_id": run.id, "trigger_type": "scheduled", "results": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", + "source_code": "DSV360_AWSDU", + "warehouse_id": "AWSDU", "status": "skipped", "skip_reason": "no_inventory_data", "message": "DSV report has no inventory data", @@ -644,37 +644,11 @@ def test_filter_sources_by_source_codes(app): task = _make_inventory_schedule_task( schedule_no="SCH-INV-FILTER-SRC", username="schedule_inv_filter_src", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) db.session.commit() sources = _filter_sources(task) - assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"] - - -def test_filter_sources_by_warehouse_id(app): - """兼容占位符常用的 warehouse_id(如 BYAWSATL01)。""" - with app.app_context(): - task = _make_inventory_schedule_task( - schedule_no="SCH-INV-FILTER-WH", - username="schedule_inv_filter_wh", - api_body_template='{"source_codes": ["BYAWSATL01"]}', - ) - db.session.commit() - sources = _filter_sources(task) - assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"] - - -def test_filter_sources_by_match_aliases(app): - """兼容误填 match_aliases 的历史排程参数。""" - with app.app_context(): - task = _make_inventory_schedule_task( - schedule_no="SCH-INV-FILTER-ALIAS", - username="schedule_inv_filter_alias", - api_body_template='{"match_aliases": ["ATL01"]}', - ) - db.session.commit() - sources = _filter_sources(task) - assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"] + assert [item.get("source_code") for item in sources] == ["DSV360_AWSDU"] def test_build_schedule_run_wecom_description_includes_skipped_count(): @@ -732,24 +706,23 @@ def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path): assert run.status == "running" -def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path): - """定时 batch 成功项缺少 site_id 时必须拒绝,不得仅靠 source_code 入库。""" +def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path): + """定时 batch 成功项缺少 Warehouse 时必须拒绝,不能仅凭 Source 入库。""" from app.models import ShippingInventoryFile drop_dir = tmp_path / "drop" drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - sample = drop_dir / "missing_site.xlsx" - _write_sample_inventory(sample, "BYAWSATL01") + sample = drop_dir / "missing_warehouse.xlsx" + _write_sample_inventory(sample, "AWSDU") with app.app_context(): before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() result = rpa_report_inventory_batch({ - "run_no": "RUN-MISSING-SITE", + "run_no": "RUN-MISSING-WAREHOUSE", "trigger_type": "scheduled", "results": [{ - "source_code": "DSV360_AWSBI_BYAWSATL01", - "warehouse_id": "BYAWSATL01", + "source_code": "DSV360_AWSDU", "success": True, "file_path": str(sample), }], @@ -758,7 +731,7 @@ def test_scheduled_batch_success_rejects_missing_site_id(app, tmp_path): assert result["status"] == "ok" assert result["failed_count"] == 1 - assert result["data"]["failed"][0]["error"] == "site_id_missing" + assert result["data"]["failed"][0]["error"] == "warehouse_id_missing" assert after == before @@ -768,10 +741,10 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "retry_snapshot.xlsx" - _write_sample_inventory(sample, "BYAWSATL01") + _write_sample_inventory(sample, "AWSDU") def _boom(*_args, **_kwargs): raise RuntimeError("finalize exploded") @@ -785,7 +758,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey task = _make_inventory_schedule_task( schedule_no="SCH-INV-RETRY-SNAPSHOT", username="schedule_inv_retry_snapshot_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) run = ScheduleRun( run_no="RUN20260713163000", @@ -804,7 +777,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey "schedule_run_id": run.id, "trigger_type": "scheduled", "results": [scheduled_rpa_batch_item( - "DSV360_AWSBI_BYAWSATL01", + "DSV360_AWSDU", success=True, file_path=str(sample), )], @@ -813,9 +786,8 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey second = rpa_report_inventory_batch(payload) count = ShippingInventoryFile.query.filter_by( rpa_run_no=run.run_no, - source_code="DSV360_AWSBI_BYAWSATL01", - site_id="AWSBI", - warehouse_id="BYAWSATL01", + source_code="DSV360_AWSDU", + warehouse_id="AWSDU", snapshot_status="ready", ).count() @@ -832,10 +804,10 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "retry_move.xlsx" - _write_sample_inventory(sample, "BYAWSATL01") + _write_sample_inventory(sample, "AWSDU") processed_dir = drop_dir / "processed" original_finalize = finalize_mod.finalize_shipping_inventory_schedule_run @@ -862,7 +834,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon task = _make_inventory_schedule_task( schedule_no="SCH-INV-RETRY-MOVE", username="schedule_inv_retry_move_user", - api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}', + api_body_template='{"source_codes": ["DSV360_AWSDU"]}', ) run = ScheduleRun( run_no="RUN20260713170000", @@ -881,7 +853,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon "schedule_run_id": run.id, "trigger_type": "scheduled", "results": [scheduled_rpa_batch_item( - "DSV360_AWSBI_BYAWSATL01", + "DSV360_AWSDU", success=True, file_path=str(sample), )], diff --git a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py deleted file mode 100644 index 5dedc37b..00000000 --- a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py +++ /dev/null @@ -1,233 +0,0 @@ -""" -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 - -from app import db -from app.models import ShippingTask -from app.services.shipping_notice.inventory_snapshot_store import ( - create_inventory_snapshot_from_rpa, - find_latest_ready_snapshot, - is_snapshot_fresh, - link_snapshot_to_task, - snapshot_expires_at, -) -from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source - - -from tests.conftest import inventory_xlsx_with_warehouse, seed_task_inventory_source - - -def _write_inventory_xlsx(path: Path, warehouse_id: str, *, sku: str = "A001", qty: int = 10) -> None: - with open(path, "wb") as handle: - handle.write(inventory_xlsx_with_warehouse(warehouse_id, sku=sku, qty=qty).getvalue()) - - -def _task_with_inventory_source( - task_no: str, - *, - source_code: str, - connector_type: str | None = None, - site_id: str | None = None, - warehouse_id: str = "", -) -> ShippingTask: - """构造已通过库存源门禁的任务,供快照关联测试使用。""" - task = ShippingTask( - task_no=task_no, - source_type="manual", - process_status="parsed", - ) - seed_task_inventory_source(task, source_code=source_code) - if site_id: - task.inventory_site_id = site_id - if warehouse_id: - task.inventory_warehouse_id = warehouse_id - if connector_type: - task.inventory_connector_type = connector_type - return task - - -def test_fresh_snapshot_is_reused(app, tmp_path): - """未过期 ready 快照应被 find_latest_ready_snapshot 按 source+site 命中。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 24 - - xlsx = tmp_path / "stock.xlsx" - _write_inventory_xlsx(xlsx, "AWSDU") - - source = build_rpa_inventory_source("DSV360_AWSDU") - assert source is not None - - with app.app_context(): - inv = create_inventory_snapshot_from_rpa( - source=source, - local_path=xlsx, - trigger_type="scheduled", - success=True, - ) - db.session.commit() - found = find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") - assert found is not None - assert found.inventory_file_no == inv.inventory_file_no - assert found.site_id == "AWSDU" - assert is_snapshot_fresh(found) - - -def test_snapshot_separates_site_id_and_warehouse_id(app, tmp_path): - """DSV 子仓快照应分别落库 site_id 与 warehouse_id,禁止混用。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - xlsx = tmp_path / "stock.xlsx" - _write_inventory_xlsx(xlsx, "BYAWSATL01") - - source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01") - assert source is not None - assert source["site_id"] == "AWSBI" - assert source["warehouse_id"] == "BYAWSATL01" - - with app.app_context(): - inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) - task = _task_with_inventory_source( - "SN-SNAPSHOT-SITE", - source_code="DSV360_AWSBI_BYAWSATL01", - connector_type="dsv360", - site_id="AWSBI", - warehouse_id="BYAWSATL01", - ) - db.session.add(task) - db.session.flush() - link = link_snapshot_to_task(task, inv, reason="reuse_latest") - db.session.commit() - - assert inv.site_id == "AWSBI" - assert inv.warehouse_id == "BYAWSATL01" - assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01" - assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01") is not None - assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI", "BYAWSATL01_WRONG") is None - assert link is not None - assert link.matched_site_id == "AWSBI" - assert link.matched_warehouse_id == "BYAWSATL01" - - -def test_crane_runtime_source_carries_dynamic_warehouse(app, tmp_path): - """Crane 运行时 RPA source 应携带任务动态库位 TZR2。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - from openpyxl import Workbook - - from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source - - xlsx = tmp_path / "crane_stock.xlsx" - wb = Workbook() - wb.active.append(["Warehouse ID", "sku", "qty"]) - wb.active.append(["TZR2", "A001", 10]) - wb.save(xlsx) - wb.close() - - with app.app_context(): - task = ShippingTask( - task_no="SN-SNAPSHOT-CRANE-RUNTIME", - source_type="manual", - process_status="parsed", - ship_to="TZR2 footprint", - ) - seed_task_inventory_source(task, source_code="CRANE") - runtime_source = build_task_rpa_inventory_source(task) - assert runtime_source is not None - assert runtime_source["site_id"] == "CRANE" - assert runtime_source["warehouse_id"] == "TZR2" - assert runtime_source["query"]["warehouse_code"] == "TZR2" - - inv = create_inventory_snapshot_from_rpa( - source=runtime_source, - local_path=xlsx, - trigger_type="on_demand", - success=True, - ) - db.session.add(task) - db.session.flush() - link = link_snapshot_to_task(task, inv, reason="rpa_callback") - db.session.commit() - - assert inv.warehouse_id == "TZR2" - assert (inv.source_query_json or {}).get("warehouse_id_source") == "task_identity_excel_verified" - assert (inv.source_query_json or {}).get("excel_warehouse_verified") is True - assert link is not None - assert link.matched_warehouse_id == "TZR2" - - -def test_different_inventory_source_cannot_reuse_snapshot(app, tmp_path): - """相同 SKU 但库存源不同不能复用快照。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - xlsx = tmp_path / "stock.xlsx" - _write_inventory_xlsx(xlsx, "AWSDU") - - with app.app_context(): - source = build_rpa_inventory_source("DSV360_AWSDU") - inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) - task = _task_with_inventory_source( - "SN-SNAPSHOT-MISMATCH", - source_code="DSV360_AWSAMS", - connector_type="dsv360", - site_id="AWSAMS", - ) - db.session.add(task) - db.session.flush() - link = link_snapshot_to_task(task, inv, reason="reuse_latest") - db.session.commit() - assert link is None - assert inv.identity_status == "mismatch" - - -def test_expired_snapshot_not_reused(app, tmp_path): - """过期快照不应被 find_latest_ready_snapshot 返回。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - app.config["SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS"] = 1 - - xlsx = tmp_path / "stock.xlsx" - _write_inventory_xlsx(xlsx, "AWSDU") - - source = build_rpa_inventory_source("DSV360_AWSDU") - with app.app_context(): - inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, success=True) - inv.exported_at = datetime.utcnow() - timedelta(hours=2) - inv.expires_at = snapshot_expires_at(inv.exported_at) - db.session.commit() - assert not is_snapshot_fresh(inv) - assert find_latest_ready_snapshot("DSV360_AWSDU", "AWSDU", "AWSDU") is None - - -def test_link_snapshot_writes_audit_fields(app, tmp_path): - """任务与快照 link 应写入 link_reason 与 audit_payload。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - xlsx = tmp_path / "stock.xlsx" - _write_inventory_xlsx(xlsx, "AWSDU") - - with app.app_context(): - task = _task_with_inventory_source( - "SN-SNAPSHOT-LINK", - source_code="DSV360_AWSDU", - connector_type="dsv360", - site_id="AWSDU", - ) - db.session.add(task) - db.session.commit() - - source = build_rpa_inventory_source("DSV360_AWSDU") - inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) - link = link_snapshot_to_task(task, inv, reason="reuse_latest", audit_payload={"mode": "auto"}) - db.session.commit() - - assert link is not None - assert link.link_reason == "reuse_latest" - assert link.matched_site_id == "AWSDU" - assert link.matched_source_code == "DSV360_AWSDU" - assert link.audit_payload_json["source_code"] == "DSV360_AWSDU" diff --git a/backend/tests/test_shipping_notice_inventory_source_gate.py b/backend/tests/test_shipping_notice_inventory_source_gate.py deleted file mode 100644 index 42b29cb5..00000000 --- a/backend/tests/test_shipping_notice_inventory_source_gate.py +++ /dev/null @@ -1,1214 +0,0 @@ -""" -tests/test_shipping_notice_inventory_source_gate.py - -用途:库存源门禁专项测试,覆盖 confirm_parse 绕过、RPA 回调拒绝、身份不匹配等核心分支。 -""" - -from __future__ import annotations - -from io import BytesIO - -import pytest -from openpyxl import Workbook - -from app import db -from app.models import ShippingBatch, ShippingInventoryFile, ShippingTask, ShippingTaskInventoryLink -from app.services.shipping_notice.constants import PH_INVENTORY_SOURCE_UNRESOLVED, PH_LOW_CONF -from app.services.shipping_notice.decision_workflow import submit_decision -from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source, rpa_report_inventory -from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable -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, - get_inventory_schema_preview, - parse_inventory, - upload_inventory_file, -) -from tests.conftest import ( - inventory_csv_with_warehouse, - inventory_xlsx_with_warehouse, - rpa_callback_payload, - seed_rpa_inventory_trigger, - seed_task_inventory_source, -) - - -def _minimal_inventory_xlsx(*, warehouse_id: str = "AWSDU") -> BytesIO: - return inventory_xlsx_with_warehouse(warehouse_id) - - -class _FakeUpload: - def __init__(self, buf: BytesIO, filename: str = "inventory.xlsx"): - self._buf = buf - self.filename = filename - - def save(self, path: str) -> None: - with open(path, "wb") as handle: - handle.write(self._buf.getvalue()) - - -@pytest.mark.inventory_source_gate -def test_confirm_parse_blocked_when_inventory_source_unstable(app): - """普通 confirm_parse 不得绕过库存源门禁。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-CONFIRM-PARSE", - source_type="pdf", - process_status="pending_review", - review_status="parse_review", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - db.session.add(task) - db.session.commit() - - result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) - db.session.refresh(task) - - assert result["status"] == "needs_human" - assert task.process_status == "pending_review" - assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED - - -@pytest.mark.inventory_source_gate -def test_rpa_callback_rejected_when_inventory_source_unstable(app, tmp_path): - """RPA 单任务回调在库存源未稳定时必须拒绝入库。""" - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - sample = inventory_drop / "inventory_gate.xlsx" - sample.write_bytes(b"PK\x03\x04") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-RPA-CB", - source_type="pdf", - process_status="waiting_inventory", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - db.session.add(task) - db.session.commit() - - result = rpa_report_inventory({ - "task_id": task.task_no, - "status": "success", - "file_path": str(sample), - "source_code": "DSV360_AWSDU", - "site_id": "AWSDU", - "warehouse_id": "AWSDU", - "run_no": "RUN-STALE", - }) - assert result["status"] == "failed" - assert task.inventory_lines_json is None - - -@pytest.mark.inventory_source_gate -def test_rpa_callback_rejects_mismatched_source_code(app, tmp_path): - """RPA 回调 source_code 与任务不一致时必须拒绝。""" - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - sample = inventory_drop / "inventory_mismatch.xlsx" - sample.write_bytes(b"PK\x03\x04") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-RPA-MISMATCH", - source_type="pdf", - process_status="waiting_inventory", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ship_to="Dublin", - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - seed_rpa_inventory_trigger(task, run_no="RUN-MISMATCH") - db.session.add(task) - db.session.commit() - - result = rpa_report_inventory(rpa_callback_payload( - task, - sample, - run_no="RUN-MISMATCH", - ) | {"source_code": "DSV360_AWSBI"}) - assert result["status"] == "failed" - - -def test_confirm_inventory_source_tool_route_exists(app, client): - """OpenAPI 声明的 confirm_inventory_source 路由必须可访问。""" - with app.app_context(): - app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" - app.config["INTEGRATION_API_KEY"] = "test-integration-key" - task = ShippingTask( - task_no="SN-ROUTE-CONFIRM-SRC", - source_type="pdf", - process_status="pending_review", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - db.session.add(task) - db.session.commit() - - res = client.post( - "/api/shipping-notice/tools/confirm_inventory_source", - headers={ - "Content-Type": "application/json", - "X-Integration-Key": "test-integration-key", - }, - json={"task_id": "SN-ROUTE-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, - ) - assert res.status_code == 200 - body = res.get_json() - assert body["status"] in {"ok", "needs_human", "running"} - - -@pytest.mark.inventory_source_gate -def test_crane_task_rpa_source_includes_dynamic_warehouse(app): - """Crane 任务级 RPA source 必须携带动态库位。""" - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-CRANE-RPA-SRC", - source_type="pdf", - process_status="parsed", - ship_to="TZR2", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="CRANE") - db.session.add(task) - db.session.commit() - - source = task_rpa_inventory_source(task) - assert source is not None - assert source["warehouse_id"] == "TZR2" - assert source["site_id"] == "CRANE" - assert source["query"]["warehouse_code"] == "TZR2" - - -@pytest.mark.inventory_source_gate -def test_confirm_inventory_source_records_user_id(app, tmp_path, monkeypatch): - """人工确认应记录真实 user_id,且与 RPA 触发解耦。""" - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - monkeypatch.setattr( - "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled", - lambda: False, - ) - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-USER-CONFIRM", - source_type="pdf", - process_status="pending_review", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - step_payload_json={ - "inventory_source_resolution": { - "status": "unresolved", - "candidates": [{"source_code": "DSV360_AWSDU", "display_name": "Dublin"}], - } - }, - ) - db.session.add(task) - db.session.commit() - - result = confirm_inventory_source({ - "task_id": task.task_no, - "source_code": "DSV360_AWSDU", - "_trusted_user_id": 42, - }) - db.session.refresh(task) - - assert result["status"] == "ok" - assert task.inventory_source_status == "user_confirmed" - assert task.inventory_source_confirmed_by == 42 - assert task.inventory_source_confirmed_at is not None - assert is_inventory_source_stable(task) - - -@pytest.mark.inventory_source_gate -def test_config_version_change_invalidates_stable_source(app): - """配置版本变化后,旧确认不得继续视为稳定。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-CFG-VER", - source_type="pdf", - process_status="parsed", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - task.inventory_source_config_version = "stale-version" - db.session.add(task) - db.session.commit() - - assert not is_inventory_source_stable(task) - - -@pytest.mark.inventory_source_gate -def test_inventory_tools_blocked_without_stable_source(app, tmp_path): - """upload/parse/preview/mapping 在库存源未稳定时不得推进库存阶段。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-INV-TOOLS", - source_type="pdf", - process_status="waiting_inventory", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - db.session.add(task) - db.session.commit() - - upload_result = upload_inventory_file(task.task_no, _FakeUpload(_minimal_inventory_xlsx())) - assert upload_result["status"] == "needs_human" - - parse_result = parse_inventory({"task_id": task.task_no, "use_uploaded_file": True}) - assert parse_result["status"] == "needs_human" - - preview_result = get_inventory_schema_preview({"task_id": task.task_no}) - assert preview_result["status"] == "needs_human" - - mapping_result = apply_inventory_mapping({ - "task_id": task.task_no, - "map_json": {"part_number": "SKU", "qty": "Qty"}, - }) - assert mapping_result["status"] == "needs_human" - assert ShippingInventoryFile.query.count() == 0 - - -@pytest.mark.inventory_source_gate -def test_user_can_confirm_candidate_not_in_auto_top_match(app): - """自动未命中时,用户仍可选择启用配置中的正式库存源。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-USER-PICK", - source_type="pdf", - process_status="pending_review", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - ship_to="UnknownCity", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - step_payload_json={ - "inventory_source_resolution": { - "status": "unresolved", - "candidates": [{"source_code": "DSV360_AWSDU"}], - } - }, - ) - db.session.add(task) - db.session.commit() - - adjudication = confirm_inventory_source_by_code(task, "DSV360_AWSCV") - assert adjudication.status == "user_confirmed" - assert adjudication.source_code == "DSV360_AWSCV" - - -@pytest.mark.inventory_source_gate -def test_site_level_source_requires_explicit_warehouse_id(app): - """站点级 DSV 须在配置与任务上同时具备 warehouse_id 才视为稳定。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-SITE-WH", - source_type="pdf", - process_status="parsed", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - assert task.inventory_warehouse_id == "AWSDU" - db.session.add(task) - db.session.commit() - - assert is_inventory_source_stable(task) - - task.inventory_warehouse_id = None - db.session.commit() - assert not is_inventory_source_stable(task) - - -@pytest.mark.inventory_source_gate -def test_legacy_without_routing_fingerprint_is_not_stable(app): - """无路由指纹的历史确认不得绕过门禁。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-NO-FP", - source_type="pdf", - process_status="parsed", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - task.inventory_routing_fingerprint = None - db.session.add(task) - db.session.commit() - - assert not is_inventory_source_stable(task) - - -@pytest.mark.inventory_source_gate -def test_missing_warehouse_when_config_requires_it_is_not_stable(app): - """子仓级库存源配置要求 warehouse_id 时,任务缺库位不得视为稳定。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-NO-WH", - source_type="pdf", - process_status="parsed", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSBI_BYAWSATL01") - task.inventory_warehouse_id = None - db.session.add(task) - db.session.commit() - - assert not is_inventory_source_stable(task) - - -@pytest.mark.inventory_source_gate -def test_rpa_callback_leaves_no_snapshot_when_identity_rejected(app, tmp_path): - """身份不一致时不得遗留 ready 库存快照。""" - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - sample = inventory_drop / "inventory_orphan.xlsx" - sample.write_bytes(b"PK\x03\x04") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-RPA-ORPHAN", - source_type="pdf", - process_status="waiting_inventory", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ship_to="Dublin", - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - seed_rpa_inventory_trigger(task, run_no="RUN-ORPHAN") - db.session.add(task) - db.session.commit() - before = ShippingInventoryFile.query.count() - - result = rpa_report_inventory(rpa_callback_payload( - task, - sample, - run_no="RUN-ORPHAN", - ) | {"source_code": "DSV360_AWSBI"}) - after = ShippingInventoryFile.query.count() - - assert result["status"] == "failed" - assert after == before - - -@pytest.mark.inventory_source_gate -def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path): - """批次上传只绑定与上传票库存源一致的任务,禁止跨源共用快照。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - with app.app_context(): - batch = ShippingBatch(batch_no="SB-GATE-CROSS", file_count=2) - owner = ShippingTask( - task_no="SN-GATE-OWNER", - batch=batch, - source_type="manual", - process_status="waiting_inventory", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}], - batch_index=1, - batch_total=2, - ) - other = ShippingTask( - task_no="SN-GATE-OTHER", - batch=batch, - source_type="manual", - process_status="waiting_inventory", - lines_json=[{"part_number": "B001", "qty": 1, "reservation_id": "R-200"}], - batch_index=2, - batch_total=2, - ) - seed_task_inventory_source(owner, source_code="DSV360_AWSDU") - seed_task_inventory_source(other, source_code="DSV360_AWSAMS") - db.session.add_all([batch, owner, other]) - db.session.commit() - - result = upload_inventory_file(owner.task_no, _FakeUpload(_minimal_inventory_xlsx())) - assert result["status"] == "ok" - - owner_links = ShippingTaskInventoryLink.query.filter_by(task_id=owner.id, is_active=True).count() - other_links = ShippingTaskInventoryLink.query.filter_by(task_id=other.id, is_active=True).count() - assert owner_links == 1 - assert other_links == 0 - - -@pytest.mark.inventory_source_gate -def test_crane_auto_adjudication_resolves_warehouse_from_alias(app): - """Crane 自动裁决应解析出库位并满足四元组稳定条件。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-CRANE-AUTO", - source_type="pdf", - process_status="parsed", - ship_to="TZR2 footprint", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - db.session.add(task) - db.session.commit() - - adjudication = adjudicate_inventory_source(task) - assert adjudication.status == "resolved" - assert adjudication.source_code == "CRANE" - assert adjudication.site_id == "CRANE" - assert adjudication.warehouse_id == "TZR2" - - -@pytest.mark.inventory_source_gate -def test_line_inventory_source_hint_matches_alias_without_using_task_source_type(app): - """订单行 inventory_source_hint 应命中别名,Task.source_type 接入来源不得参与裁决。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-LINE-SOURCE-TYPE", - source_type="TZR2", - process_status="parsed", - lines_json=[ - { - "part_number": "A001", - "qty": 1, - "reservation_id": "R-100", - "inventory_source_hint": "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 人工确认后应写入完整身份并通过门禁。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-CRANE-USER", - source_type="pdf", - process_status="pending_review", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - ship_to="TZR3", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - db.session.add(task) - db.session.commit() - - adjudication = confirm_inventory_source_by_code(task, "CRANE") - assert adjudication.status == "user_confirmed" - assert adjudication.warehouse_id == "TZR3" - - from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication - - apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=7) - db.session.commit() - assert is_inventory_source_stable(task) - assert task.inventory_source_confirmed_by == 7 - - -@pytest.mark.inventory_source_gate -def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch): - """低置信度 + 未命中库存源:先确认解析,再确认库存源,最后才能进入库存准备。""" - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - monkeypatch.setattr( - "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled", - lambda: False, - ) - monkeypatch.setattr( - "app.services.shipping_notice.decision_workflow.start_task_orchestrator", - lambda task_no: False, - ) - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-LOW-CONF-SEQ", - source_type="pdf", - process_status="pending_review", - pending_human_reason=PH_LOW_CONF, - review_status="parse_review", - parse_confidence=0.4, - ship_to="UnknownCity", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}], - inventory_source_status="unresolved", - ) - db.session.add(task) - db.session.commit() - - parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) - db.session.refresh(task) - assert parse_result["status"] in {"ok", "needs_human"} - assert parse_result.get("checkpoint") == "inventory_source_review" - assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED - assert not is_inventory_source_stable(task) - option_ids = parse_result.get("human_options") or [ - item.get("id") for item in (parse_result.get("action_buttons") or []) - ] - assert "reparse" not in option_ids - assert "confirm_inventory_source" in option_ids - - source_result = confirm_inventory_source({ - "task_id": task.task_no, - "source_code": "DSV360_AWSDU", - "_trusted_user_id": 11, - }) - db.session.refresh(task) - assert source_result["status"] in {"ok", "running"} - assert is_inventory_source_stable(task) - assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED - assert task.pending_human_reason != PH_LOW_CONF - - -@pytest.mark.inventory_source_gate -def test_legacy_pending_parse_review_after_source_compat(app, monkeypatch): - """存量任务:先库存源后解析的延后标记仍可走完兼容路径。""" - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - monkeypatch.setattr( - "app.services.shipping_notice.tool_common.auto_rpa_inventory_enabled", - lambda: False, - ) - monkeypatch.setattr( - "app.services.shipping_notice.decision_workflow.start_task_orchestrator", - lambda task_no: False, - ) - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-LEGACY-PARSE-AFTER-SOURCE", - source_type="pdf", - process_status="pending_review", - pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED, - review_status="parse_review", - parse_confidence=0.4, - ship_to="UnknownCity", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}], - step_payload_json={"pending_parse_review_after_source": True}, - ) - db.session.add(task) - db.session.commit() - - blocked = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) - assert blocked["status"] == "needs_human" - - source_result = confirm_inventory_source({ - "task_id": task.task_no, - "source_code": "DSV360_AWSDU", - "_trusted_user_id": 11, - }) - db.session.refresh(task) - assert source_result["status"] == "needs_human" - assert source_result.get("checkpoint") == "parse_review" - assert task.pending_human_reason == PH_LOW_CONF - assert is_inventory_source_stable(task) - - parse_result = submit_decision({"task_id": task.task_no, "decision": "confirm_parse"}) - db.session.refresh(task) - assert parse_result["status"] in {"ok", "running"} - assert is_inventory_source_stable(task) - assert task.pending_human_reason != PH_INVENTORY_SOURCE_UNRESOLVED - - -@pytest.mark.inventory_source_gate -def test_parse_notice_high_confidence_unresolved_source_goes_to_source_review(app, client): - """高置信度解析自动通过后,库存源未命中应直接进入 inventory_source_review。""" - from tests.test_shipping_notice_tools import _tool_headers - - headers = _tool_headers(app) - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - parse_res = client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "ACME", - "ship_to": "Mystery Port", - "lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}], - "confidence": 0.95, - }, - }, - ) - parse_data = parse_res.get_json() - assert parse_data["status"] == "needs_human" - assert parse_data.get("checkpoint") == "inventory_source_review" - button_ids = [item.get("id") for item in (parse_data.get("action_buttons") or [])] - assert "confirm_inventory_source" in button_ids - assert "reparse" not in button_ids - - with app.app_context(): - task = ShippingTask.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED - assert not is_inventory_source_stable(task) - - -@pytest.mark.inventory_source_gate -def test_parse_notice_low_confidence_unresolved_source_goes_to_parse_review(app, client): - """低置信度 + 库存源未命中:应先进入 parse_review(含重新解析),而非抢先确认库存源。""" - from app.services.shipping_notice.state_machine import human_options_for_task - from tests.test_shipping_notice_tools import _tool_headers - - headers = _tool_headers(app) - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - parse_res = client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "ACME", - "ship_to": "Mystery Port", - "lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}], - "confidence": 0.4, - }, - }, - ) - parse_data = parse_res.get_json() - assert parse_data["status"] == "needs_human" - assert parse_data.get("checkpoint") == "parse_review" - assert "重新解析" in (parse_data.get("message") or "") or "置信度" in (parse_data.get("message") or "") - - with app.app_context(): - task = ShippingTask.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.pending_human_reason == PH_LOW_CONF - assert task.review_status == "parse_review" - options = human_options_for_task(task) or [] - assert "reparse" in options - assert "confirm" in options - assert "confirm_inventory_source" not in options - assert "解析确认通过后" in (parse_data.get("message") or "") - - -@pytest.mark.inventory_source_gate -def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch): - """人工上传身份绑定失败时不应遗留库存文件或数据库记录。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - monkeypatch.setattr( - "app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task", - lambda *args, **kwargs: None, - ) - - with app.app_context(): - batch = ShippingBatch(batch_no="SB-GATE-UPLOAD-FAIL", file_count=2) - owner = ShippingTask( - task_no="SN-GATE-UPLOAD-OWNER", - batch=batch, - source_type="manual", - process_status="waiting_inventory", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}], - batch_index=1, - batch_total=2, - ) - other = ShippingTask( - task_no="SN-GATE-UPLOAD-OTHER", - batch=batch, - source_type="manual", - process_status="waiting_inventory", - lines_json=[{"part_number": "B001", "qty": 1, "reservation_id": "R-200"}], - batch_index=2, - batch_total=2, - ) - seed_task_inventory_source(owner, source_code="DSV360_AWSDU") - seed_task_inventory_source(other, source_code="DSV360_AWSAMS") - db.session.add_all([batch, owner, other]) - db.session.commit() - - before_files = ShippingInventoryFile.query.count() - result = upload_inventory_file(owner.task_no, _FakeUpload(_minimal_inventory_xlsx())) - after_files = ShippingInventoryFile.query.count() - - assert result["status"] == "failed" - assert after_files == before_files - assert not list((tmp_path / "shipping").rglob("*.xlsx")) - - -def _evaluate_legacy_backfill( - *, - source_code: str, - site_id: str | None, - warehouse_id: str | None, - resolution_status: str | None = None, - routing_fingerprint: str | None = None, -) -> dict[str, str | None]: - """镜像迁移回填规则,供迁移专项测试断言。""" - status = "resolved" - method = "legacy_migrated" - code = source_code - if resolution_status == "ambiguous": - status = "ambiguous" - elif resolution_status == "user_confirmed": - status = "user_confirmed" - if not site_id and warehouse_id: - return { - "source_code": None, - "status": "unresolved", - "method": None, - "config_version": "legacy-unverified", - } - if not site_id or not warehouse_id: - return { - "source_code": None, - "status": "unresolved", - "method": None, - "config_version": "legacy-unverified", - } - if not routing_fingerprint: - return { - "source_code": code, - "status": "unresolved", - "method": None, - "config_version": "legacy-unverified", - } - return { - "source_code": code, - "status": status, - "method": "legacy_migrated", - "config_version": "legacy-unverified", - } - - -@pytest.mark.inventory_source_gate -def test_migration_backfill_dual_empty_identity_goes_unresolved(): - """历史 site/warehouse 双空记录应进入 unresolved 而非 resolved。""" - result = _evaluate_legacy_backfill( - source_code="DSV360_AWSDU", - site_id=None, - warehouse_id=None, - ) - assert result["status"] == "unresolved" - assert result["source_code"] is None - assert result["config_version"] == "legacy-unverified" - - -@pytest.mark.inventory_source_gate -def test_migration_backfill_without_fingerprint_requires_review(): - """历史无路由指纹不得标记为当前配置已验证。""" - result = _evaluate_legacy_backfill( - source_code="DSV360_AWSDU", - site_id="AWSDU", - warehouse_id="AWSDU", - routing_fingerprint=None, - ) - assert result["status"] == "unresolved" - assert result["config_version"] == "legacy-unverified" - - -@pytest.mark.inventory_source_gate -def test_rpa_callback_rejects_excel_warehouse_mismatch(app, tmp_path): - """任务库位 TZR2 但 Excel Warehouse ID=TZR3 时必须拒绝入库。""" - from openpyxl import Workbook - - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - sample = inventory_drop / "crane_wrong_wh.xlsx" - wb = Workbook() - wb.active.append(["Warehouse ID", "SKU", "Qty"]) - wb.active.append(["TZR3", "A001", 1]) - wb.save(sample) - wb.close() - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-EXCEL-WH", - source_type="pdf", - process_status="waiting_inventory", - ship_to="TZR2 footprint", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="CRANE") - seed_rpa_inventory_trigger(task, run_no="RUN-EXCEL-WH") - db.session.add(task) - db.session.commit() - before = ShippingInventoryFile.query.count() - - result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-EXCEL-WH")) - after = ShippingInventoryFile.query.count() - - assert result["status"] == "failed" - assert after == before - - -@pytest.mark.inventory_source_gate -def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path): - """人工上传错误 Warehouse ID 时必须拒绝并清理文件。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-UPLOAD-WH", - source_type="pdf", - process_status="waiting_inventory", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.add(task) - db.session.commit() - - result = upload_inventory_file( - task.task_no, - _FakeUpload(inventory_xlsx_with_warehouse("TZR3")), - ) - assert result["status"] == "failed" - assert ShippingInventoryFile.query.count() == 0 - assert not list((tmp_path / "shipping").rglob("*.xlsx")) - - -@pytest.mark.inventory_source_gate -def test_rpa_callback_rejects_mismatched_warehouse_id(app, tmp_path): - """单任务回调 warehouse_id 与任务不一致时必须拒绝。""" - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - sample = inventory_drop / "inventory_wh_mismatch.xlsx" - with open(sample, "wb") as handle: - handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-RPA-WH", - source_type="pdf", - process_status="waiting_inventory", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - seed_rpa_inventory_trigger(task, run_no="RUN-WH-MISMATCH") - db.session.add(task) - db.session.commit() - - result = rpa_report_inventory(rpa_callback_payload( - task, - sample, - run_no="RUN-WH-MISMATCH", - ) | {"warehouse_id": "TZR3"}) - assert result["status"] == "failed" - - -@pytest.mark.inventory_source_gate -def test_rpa_callback_rejects_stale_run_no(app, tmp_path): - """旧 run_no 回调不得覆盖当前任务库存轮次。""" - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - sample = inventory_drop / "inventory_stale_run.xlsx" - with open(sample, "wb") as handle: - handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-STALE-RUN", - source_type="pdf", - process_status="waiting_inventory", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT") - db.session.add(task) - db.session.commit() - - result = rpa_report_inventory(rpa_callback_payload( - task, - sample, - run_no="RUN-OLD", - )) - assert result["status"] == "failed" - assert (result.get("data") or {}).get("run_no_error") == "run_no_mismatch" - - -@pytest.mark.inventory_source_gate -def test_scheduled_batch_unknown_source_creates_no_ready_snapshot(app, tmp_path): - """未知/禁用 source 的定时批量回调不得创建 ready 快照。""" - from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch - - drop_dir = tmp_path / "drop" - drop_dir.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - sample = drop_dir / "scheduled.xlsx" - with open(sample, "wb") as handle: - handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) - - with app.app_context(): - before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() - result = rpa_report_inventory_batch({ - "run_no": "RUN-UNKNOWN-SRC", - "trigger_type": "scheduled", - "results": [{ - "source_code": "UNKNOWN_SOURCE", - "warehouse_id": "AWSDU", - "status": "success", - "success": True, - "file_path": str(sample), - }], - }) - after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() - - assert result["status"] == "ok" - assert result["result_status"] == "failed" - assert after == before - assert result["data"]["failed"][0]["error"] == "unknown_or_disabled_source" - - -@pytest.mark.inventory_source_gate -def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path): - """CSV 上传应保留 .csv 后缀并通过 Warehouse ID 身份校验。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-UPLOAD-CSV", - source_type="pdf", - process_status="waiting_inventory", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.add(task) - db.session.commit() - - result = upload_inventory_file( - task.task_no, - _FakeUpload(inventory_csv_with_warehouse("AWSDU"), filename="inventory.csv"), - ) - assert result["status"] != "failed" - csv_files = list((tmp_path / "shipping").rglob("inventory.csv")) - assert len(csv_files) == 1 - assert ShippingInventoryFile.query.count() == 1 - - -@pytest.mark.inventory_source_gate -def test_manual_upload_rejects_xls_extension(app, tmp_path): - """.xls 上传应在入口明确拒绝,而非误报 Warehouse 缺失。""" - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-UPLOAD-XLS", - source_type="pdf", - process_status="waiting_inventory", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.add(task) - db.session.commit() - - result = upload_inventory_file( - task.task_no, - _FakeUpload(_minimal_inventory_xlsx(), filename="inventory.xls"), - ) - assert result["status"] == "failed" - assert ShippingInventoryFile.query.count() == 0 - - -@pytest.mark.inventory_source_gate -def test_rpa_success_rejected_without_active_trigger(app, tmp_path): - """无 inventory_rpa_triggered 事件时,成功回调不得入库。""" - inventory_drop = tmp_path / "drop" - inventory_drop.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) - sample = inventory_drop / "no_trigger.xlsx" - with open(sample, "wb") as handle: - handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-NO-TRIGGER", - source_type="pdf", - process_status="waiting_inventory", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.add(task) - db.session.commit() - before = ShippingInventoryFile.query.count() - - result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no="RUN-FAKE")) - after = ShippingInventoryFile.query.count() - - assert result["status"] == "failed" - assert (result.get("data") or {}).get("run_no_error") == "no_active_trigger" - assert after == before - - -@pytest.mark.inventory_source_gate -def test_rpa_failed_rejected_stale_run_no(app, tmp_path): - """旧 run_no 的 failed 回调不得覆盖当前等待轮次。""" - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-STALE-FAIL", - source_type="pdf", - process_status="waiting_inventory", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], - ) - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT-FAIL") - db.session.add(task) - db.session.commit() - - result = rpa_report_inventory({ - "task_id": task.task_no, - "status": "failed", - "success": False, - "run_no": "RUN-OLD-FAIL", - "error_message": "stale callback", - }) - db.session.refresh(task) - - assert result["status"] == "failed" - assert (result.get("data") or {}).get("run_no_error") == "run_no_mismatch" - assert task.error_message is None - - -@pytest.mark.inventory_source_gate -def test_scheduled_crane_batch_accepts_dynamic_warehouse(app, tmp_path): - """CRANE 动态库位定时回调应接受 Worker 回传的 TZR/TZR2/TZR3。""" - from app.models import ShippingInventoryFile - from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch - from tests.conftest import scheduled_rpa_batch_item - - drop_dir = tmp_path / "drop" - drop_dir.mkdir() - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - sample = drop_dir / "crane_tzr2.xlsx" - with open(sample, "wb") as handle: - handle.write(inventory_xlsx_with_warehouse("TZR2").getvalue()) - - with app.app_context(): - before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() - result = rpa_report_inventory_batch({ - "run_no": "RUN-CRANE-TZR2", - "trigger_type": "scheduled", - "results": [scheduled_rpa_batch_item( - "CRANE", - warehouse_id="TZR2", - success=True, - file_path=str(sample), - )], - }) - after = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count() - - assert result["status"] == "ok" - assert result["success_count"] == 1 - created = (result.get("data") or {}).get("created") or [] - assert created and created[0].get("warehouse_id") == "TZR2" - assert after == before + 1 - snap = ShippingInventoryFile.query.filter_by( - rpa_run_no="RUN-CRANE-TZR2", - source_code="CRANE", - warehouse_id="TZR2", - ).first() - assert snap is not None - assert snap.site_id == "CRANE" - - -@pytest.mark.inventory_source_gate -def test_inventory_header_skips_single_cell_warehouse_title(app, tmp_path): - """仅含 Warehouse 标题的单单元格行不得被误判为表头。""" - from io import BytesIO - - from openpyxl import Workbook - - from app.services.shipping_notice.inventory_file_identity import ( - extract_warehouse_ids_from_inventory_excel, - ) - - buf = BytesIO() - wb = Workbook() - ws = wb.active - ws.append(["Warehouse"]) - ws.append(["Warehouse ID", "SKU", "Qty"]) - ws.append(["TZR2", "A001", 1]) - wb.save(buf) - buf.seek(0) - - path = tmp_path / "title_then_header.xlsx" - path.write_bytes(buf.getvalue()) - found = extract_warehouse_ids_from_inventory_excel(path) - assert found == {"TZR2"} - - -@pytest.mark.inventory_source_gate -def test_conflicted_inventory_source_status_persists(app): - """自动裁决 conflicted 状态须能写入数据库,不被 CHECK 约束拒绝。""" - from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication - from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication - - with app.app_context(): - task = ShippingTask( - task_no="SN-GATE-CONFLICTED", - process_status="pending_review", - customer_code="TEST", - ) - db.session.add(task) - db.session.flush() - apply_inventory_source_adjudication( - task, - InventorySourceAdjudication( - status="conflicted", - config_version="v1", - routing_fingerprint="fp-conflict", - candidates=[], - conflicts=["matched_conflicting_rules"], - reason="matched_conflicting_rules", - ), - ) - db.session.commit() - db.session.refresh(task) - assert task.inventory_source_status == "conflicted" - - -@pytest.mark.inventory_source_gate -def test_csv_inventory_parse_reads_beyond_preview_limit(app, tmp_path): - """CSV 全量解析不得静默截断为 10,000 行。""" - from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel - - path = tmp_path / "large.csv" - lines = ["Warehouse ID,SKU,Qty Available"] - lines.extend(f"AWSDU,SKU-{i},1" for i in range(10_050)) - path.write_text("\n".join(lines), encoding="utf-8") - - with app.app_context(): - rows = parse_inventory_excel(path) - assert len(rows) == 10_050 diff --git a/backend/tests/test_shipping_notice_inventory_sources_config.py b/backend/tests/test_shipping_notice_inventory_sources_config.py deleted file mode 100644 index 5839bd6d..00000000 --- a/backend/tests/test_shipping_notice_inventory_sources_config.py +++ /dev/null @@ -1,199 +0,0 @@ -""" -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 - -import pytest - -from app.services.shipping_notice.inventory_sources import ( - InventorySourceConfigError, - build_rpa_inventory_source, - get_inventory_source, - list_inventory_sources, - reload_inventory_sources_config, -) - - -def test_inventory_sources_yaml_loads(app): - """默认 YAML 配置应成功加载并包含 DSV360_AWSDU。""" - with app.app_context(): - reload_inventory_sources_config() - source = get_inventory_source("DSV360_AWSDU") - assert source is not None - assert source["connector_type"] == "dsv360" - assert source["site_id"] == "AWSDU" - assert source["warehouse_id"] == "AWSDU" - assert source["query"]["program_label"] - - -def test_build_rpa_inventory_source_keeps_legacy_query(app): - """build_rpa_inventory_source 应返回 worker 兼容 query,AWSBI 子仓仅含 Warehouse 参数。""" - with app.app_context(): - payload = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01") - assert payload is not None - assert payload["site_id"] == "AWSBI" - assert payload["warehouse_id"] == "BYAWSATL01" - assert payload["query"]["warehouse_code"] == "BYAWSATL01" - assert payload["query"]["program_label"] == "AWSBI" - assert "owner_code" not in payload["query"] - assert len(payload["parameters"]) == 1 - assert payload["parameters"][0]["name"] == "Warehouse" - - -def test_awsams_warehouse_uses_multi_select_all(app): - """AWSAMS Warehouse 是 SSRS checkbox 下拉,配置应显式走 multi_select + select_all。""" - with app.app_context(): - reload_inventory_sources_config() - payload = build_rpa_inventory_source("DSV360_AWSAMS") - assert payload is not None - warehouse_param = next(item for item in payload["parameters"] if item["name"] == "Warehouse") - assert warehouse_param["mode"] == "multi_select" - assert warehouse_param["select_all"] is True - assert warehouse_param["values"] == ["RTM"] - assert warehouse_param["selectors"] == { - "text": "#ReportViewerMain_ctl08_ctl17_txtValue", - "toggle": "#ReportViewerMain_ctl08_ctl17_ctl01", - "dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown", - } - - -def test_duplicate_source_code_raises(app, tmp_path): - """source_code 重复时加载应报错。""" - bad = tmp_path / "bad_sources.json" - bad.write_text( - """ - { - "version": 1, - "sources": [ - {"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": []} - ] - } - """, - encoding="utf-8", - ) - app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad) - with app.app_context(): - with pytest.raises(InventorySourceConfigError, match="duplicate"): - reload_inventory_sources_config() - - -def test_dsv_source_requires_site_id(app, tmp_path): - """DSV 源必须显式配置 site_id,避免把站点和仓库混用。""" - bad = tmp_path / "bad_sources.yaml" - bad.write_text( - """ -version: 1 -sources: -- source_code: DSV360_BAD - enabled: true - connector_type: dsv360 - warehouse_id: AWSBI - entry_url: http://x - navigation: {} - parameters: [] - """, - encoding="utf-8", - ) - app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad) - with app.app_context(): - with pytest.raises(InventorySourceConfigError, match="site_id is required"): - reload_inventory_sources_config() - - -def test_dsv_source_requires_warehouse_id(app, tmp_path): - """DSV 源必须显式配置 warehouse_id。""" - bad = tmp_path / "bad_sources.yaml" - bad.write_text( - """ -version: 1 -sources: -- source_code: DSV360_BAD - enabled: true - connector_type: dsv360 - site_id: AWSBI - entry_url: http://x - navigation: {} - parameters: [] - """, - encoding="utf-8", - ) - app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad) - with app.app_context(): - with pytest.raises(InventorySourceConfigError, match="warehouse_id is required"): - reload_inventory_sources_config() - - -def test_build_rpa_inventory_source_crane_has_site_and_alias_resolution(app): - """Crane 源须配置 site_id 与 match_aliases,库位由订单别名解析。""" - with app.app_context(): - reload_inventory_sources_config() - payload = build_rpa_inventory_source("CRANE") - assert payload is not None - assert payload["connector_type"] == "crane_footprint" - assert payload["site_id"] == "CRANE" - assert payload["warehouse_id"] == "" - assert payload["warehouse_resolution"] == "alias_match" - assert payload.get("allowed_warehouse_ids") == ["TZR", "TZR2", "TZR3"] - assert payload["parameters"] == [] - assert payload["navigation"]["download_mode"] == "scheduled_report" - - -def test_match_aliases_available_via_list(app): - """list_inventory_sources 应包含 match_aliases 供规则匹配。""" - with app.app_context(): - reload_inventory_sources_config() - codes = {item["source_code"] for item in list_inventory_sources()} - assert "DSV360_AWSDU" in codes - assert "DSV360_AWSBI_BYAWSATL01" in codes - assert "CRANE" in codes - awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_")) - assert awsbi_count == 25 - - -def test_inventory_sources_cache_refreshes_when_content_changes_with_same_mtime(app, tmp_path, monkeypatch): - """配置内容变化但 mtime 不变时,缓存仍须刷新。""" - import os - - from app.services.shipping_notice import inventory_sources as mod - - cfg = tmp_path / "sources.yaml" - cfg.write_text( - """ -version: 1 -sources: -- source_code: CACHE_TEST - enabled: true - connector_type: dsv360 - site_id: S1 - warehouse_id: W1 - entry_url: http://example.com - navigation: {} - parameters: [] - """, - encoding="utf-8", - ) - fixed_mtime = 1_700_000_000.0 - os.utime(cfg, (fixed_mtime, fixed_mtime)) - app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(cfg) - - with app.app_context(): - mod._CONFIG_CACHE = None - mod._CONFIG_PATH = None - mod._CONFIG_RAW_DIGEST = None - first = mod.reload_inventory_sources_config() - assert first["sources"]["CACHE_TEST"]["warehouse_id"] == "W1" - - cfg.write_text( - cfg.read_text(encoding="utf-8").replace("warehouse_id: W1", "warehouse_id: W2"), - encoding="utf-8", - ) - os.utime(cfg, (fixed_mtime, fixed_mtime)) - second = mod.reload_inventory_sources_config() - assert second["sources"]["CACHE_TEST"]["warehouse_id"] == "W2" - assert second is not first diff --git a/backend/tests/test_shipping_notice_match_rule_desc.py b/backend/tests/test_shipping_notice_match_rule_desc.py index 65326197..5056ae93 100644 --- a/backend/tests/test_shipping_notice_match_rule_desc.py +++ b/backend/tests/test_shipping_notice_match_rule_desc.py @@ -1,34 +1,20 @@ from app.services.shipping_notice.match_rule_desc import ( build_match_rule_fallback, - extract_mapping_payload_extras, resolve_match_rule, ) -def test_extract_mapping_payload_extras(): - payload = { - "part_number": "Supplier Sku", - "aws_part_number": "AWS Sku", - "reservation_id": "Reservation Order", - "available_qty": "Qty Available", - "match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。", - } - extras = extract_mapping_payload_extras(payload) - assert extras["match_rule"].startswith("以 Reservation Order") - assert "match_key" not in extras - - -def test_resolve_match_rule_prefers_llm(): +def test_resolve_match_rule_uses_configured_mapping_only(): mapping = { "part_number": "Supplier Sku", "reservation_id": "Reservation Order", "available_qty": "Qty Available", } - llm_rule = "LLM 自定义匹配说明。" - rule, keys, source = resolve_match_rule(mapping, llm_match_rule=llm_rule) - assert rule == llm_rule + rule, keys, source = resolve_match_rule(mapping) + assert "Supplier Sku" in rule + assert "Reservation Order" in rule assert keys == ["part_number", "reservation_id"] - assert source == "llm" + assert source == "configured_mapping" def test_build_match_rule_fallback_uses_column_names(): diff --git a/backend/tests/test_shipping_notice_openapi_contract.py b/backend/tests/test_shipping_notice_openapi_contract.py index 761b4bf0..16d431b7 100644 --- a/backend/tests/test_shipping_notice_openapi_contract.py +++ b/backend/tests/test_shipping_notice_openapi_contract.py @@ -1,7 +1,7 @@ """ tests/test_shipping_notice_openapi_contract.py -用途:锁定发货通知 v2 订单行、单一路由线索与库存连接器 OpenAPI 命名契约。 +用途:锁定发货通知动态订单字段、证据观察值与库存连接器 OpenAPI 命名契约。 依赖:Flask 测试 client、静态 Dify OpenAPI JSON。 逻辑:分别校验动态 builder 输出与脚本生成的静态快照,防止两者发生漂移。 """ @@ -17,7 +17,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None: """ 校验订单行与库存连接器的字段边界。 - 核心逻辑:订单行只接受 part_number 与可选外部料号/inventory_source_hint; + 核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations; 任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。 Args: @@ -31,15 +31,12 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None: ]["schema"]["properties"]["orders"]["items"] line_properties = order_schema["properties"]["lines"]["items"]["properties"] assert order_schema["properties"]["lines"]["items"]["additionalProperties"] is False - assert set(line_properties) == { - "part_number", - "customer_part_number", - "aws_part_number", - "qty", - "reservation_id", - "inventory_source_hint", - } - assert "库存来源提示" in line_properties["inventory_source_hint"]["description"] + assert set(line_properties) == {"fields"} + assert line_properties["fields"]["type"] == "array" + field_item = line_properties["fields"]["items"] + assert {"field_id", "observations"} <= set(field_item["properties"]) + observation = field_item["properties"]["observations"]["items"] + assert {"value", "document_id", "quote", "confidence"} <= set(observation["properties"]) assert not {"sku", "vendor_part_number", "source_type", "hub_code"} & set(line_properties) request_schema = spec["paths"]["/tools/submit_order_extraction"]["post"]["requestBody"]["content"][ diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index 102b3fdc..b5a94ac4 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -27,6 +27,7 @@ from app.models import ( ShippingNoticeIntake, ShippingTask, ShippingTaskEvent, + ShippingOrderSchemaVersion, User, ) from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify @@ -55,6 +56,49 @@ from app.services.shipping_notice.intake_service import get_intake_statuses, lis 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 +from app.services.shipping_notice.order_schema import service as order_schema_service + + +def _ensure_order_schema() -> dict[str, str]: + """为订单抽取集成测试发布最小动态 Schema,并返回 field_code 到稳定 ID 的映射。""" + published = ShippingOrderSchemaVersion.query.filter_by(status='published').first() + if published is not None: + return { + str(item['field_code']): str(item['field_id']) + for item in (published.definition_json or {}).get('fields') or [] + } + order_schema_service.initialize_schema({'display_name': '订单抽取测试字段'}, actor_id=None) + definitions = [ + ('po_number', 'header', 'string', False, 'trim', [], 'normalized_text'), + ('part_number', 'line', 'string', True, 'uppercase_trim', ['non_empty'], 'normalized_text'), + ('qty', 'line', 'decimal', True, 'decimal', ['positive_decimal'], 'decimal'), + ('reservation_id', 'line', 'string', False, 'reservation_id', ['reservation_id'], 'reservation_id'), + ('inventory_source_hint', 'line', 'string', False, 'trim', [], 'normalized_text'), + ] + fields = {} + configs = [] + for code, scope, value_type, required, normalizer, validators, comparator in definitions: + field = order_schema_service.save_field( + {'field_code': code, 'scope': scope, 'value_type': value_type}, actor_id=None, + ) + fields[code] = field['id'] + configs.append({ + 'field_id': field['id'], 'display_name': code, 'required': required, 'aliases': [], + 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], + 'evidence_policy': { + 'required': True, 'source_precedence': ['attachment_text', 'backend_table', 'dify_llm'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, 'comparator_key': comparator, + }) + draft = order_schema_service.create_draft({}, actor_id=None) + saved_schema = order_schema_service.save_draft(draft['id'], { + 'fields': configs, 'expected_lock_version': draft['lock_version'], + }) + order_schema_service.publish( + draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'], + ) + return fields def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it(): @@ -104,6 +148,7 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S Returns: 用户、会话、Intake、Document 与序列化 agent_runtime_context。 """ + _ensure_order_schema() user = User(username='order-extraction-user', email='order-extraction@example.com', password_hash='x') agent = Agent( name='Shipping Notice', @@ -187,34 +232,68 @@ def _order( confidence: float = 0.99, include_process_fields: bool, ) -> dict: - """构造符合 Chatflow V2 契约的单个订单结果。""" - line = {'part_number': part_number, 'qty': qty} - if include_process_fields: - line.update({'reservation_id': 'R-100', 'inventory_source_hint': 'AWS Dublin'}) - evidence = [ - {'field': 'lines[0].part_number', 'quote': f'SKU {part_number}', 'document_id': document_id}, - {'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id}, + """构造符合动态订单 Schema 契约的单个订单结果。""" + fields = _ensure_order_schema() + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + document = db.session.get(ShippingNoticeDocument, document_id) + po_quote = f'PO {po_number}' + line_fields = [ + {'field_id': fields['part_number'], 'observations': [ + {'value': part_number, 'quote': f'SKU {part_number}', 'document_id': document_id, 'confidence': confidence}, + ]}, + {'field_id': fields['qty'], 'observations': [ + {'value': qty, 'quote': f'QTY {qty}', 'document_id': document_id, 'confidence': confidence}, + ]}, ] if include_process_fields: - evidence.append({ - 'field': 'lines[0].reservation_id', - 'quote': 'R-100', - 'document_id': document_id, - }) + line_fields.extend([ + {'field_id': fields['reservation_id'], 'observations': [ + {'value': 'R-100', 'quote': 'R-100', 'document_id': document_id, 'confidence': confidence}, + ]}, + {'field_id': fields['inventory_source_hint'], 'observations': [ + {'value': 'AWS Dublin', 'quote': 'AWS Dublin', 'document_id': document_id, 'confidence': confidence}, + ]}, + ]) return { + 'schema_version_id': int(version.id), + 'schema_checksum': version.checksum, 'source_intake_no': intake_no, 'primary_document_id': document_id, 'candidate_key_hint': po_number, 'classification': 'shipping_request', 'classification_confidence': confidence, - 'field_confidence': {'part_number': confidence, 'qty': confidence}, - 'po_number': po_number, - 'lines': [line], - 'evidence': evidence, + 'header_fields': ([{'field_id': fields['po_number'], 'observations': [ + {'value': po_number, 'quote': po_quote, 'document_id': document_id, 'confidence': confidence}, + ]}] if document is not None and po_quote in str(document.extracted_text or '') else []), + 'lines': [{'fields': line_fields}], 'conflicts': [], } +def _set_dynamic_line_field(order: dict, code: str, value, *, quote: str | None = None) -> None: + """替换动态订单首行指定 field_code 的 Observation 值与原文证据。""" + field_id = _ensure_order_schema()[code] + field = next(item for item in order['lines'][0]['fields'] if item['field_id'] == field_id) + field['observations'][0]['value'] = value + if quote is not None: + field['observations'][0]['quote'] = quote + + +def _remove_dynamic_line_field(order: dict, code: str) -> None: + """从动态订单首行移除指定 field_code,模拟 LLM 缺失或无可信证据。""" + field_id = _ensure_order_schema()[code] + order['lines'][0]['fields'] = [ + item for item in order['lines'][0]['fields'] if item['field_id'] != field_id + ] + + +def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None: + """保留字段候选但使 quote 无法命中原文,验证动态证据门禁。""" + field_id = _ensure_order_schema()[code] + field = next(item for item in order['lines'][0]['fields'] if item['field_id'] == field_id) + field['observations'][0]['quote'] = 'NOT-IN-SOURCE' + + def _add_extraction_intake( *, user: User, @@ -710,6 +789,33 @@ def test_superseded_order_extraction_request_cannot_read_or_submit(app): assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0 +def test_consumed_intake_is_not_reported_as_preprocessing_pending(app): + """已完成的 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}) + submit_order_extraction({ + 'agent_runtime_context': runtime_context, + 'input_snapshot_hash': context_result['input_snapshot_hash'], + 'orders': [ + _order( + intake_no=intake.intake_no, + document_id=int(document.id), + po_number='4510000001', + part_number='SKU-A', + qty=10, + include_process_fields=True, + ), + ], + }) + + with pytest.raises(ConflictError) as error: + get_order_extraction_context({'agent_runtime_context': runtime_context}) + + assert error.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED' + assert '已完成' in error.value.message + + def test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay(app): """一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。""" with app.app_context(): @@ -913,7 +1019,7 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati assert result['created'] == [] assert result['created_count'] == 0 assert result['auto_created_count'] == 0 - assert result['opened_existing_count'] == 1 + assert result['opened_existing_count'] == 1, result assert result['pending_count'] == 0 assert result['message'] == '已打开 1 个已有任务。' assert result['opened_existing'][0]['task_no'] == existing.task_no @@ -1176,7 +1282,7 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor include_process_fields=True, )], }) - assert result['opened_existing_count'] == 1 + assert result['opened_existing_count'] == 1, result load_handlers() handler = get_handler('shipping_notice') @@ -1265,7 +1371,10 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev db.session.add(existing) db.session.commit() - document.extracted_text = f"{document.extracted_text}\nReservation ID 1000140351" + document.extracted_text = ( + f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 " + "Reservation ID 1000140351 Source DBS DUB" + ) db.session.commit() context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) order = _order( @@ -1276,9 +1385,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev qty=24, include_process_fields=True, ) - order['lines'][0]['reservation_id'] = '1000140351' - order['lines'][0]['inventory_source_hint'] = 'DBS DUB' - order['evidence'][-1]['quote'] = '1000140351' + _set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351') + _set_dynamic_line_field(order, 'inventory_source_hint', 'DBS DUB', quote='DBS DUB') result = submit_order_extraction({ 'agent_runtime_context': runtime_context, 'input_snapshot_hash': context_result['input_snapshot_hash'], @@ -1287,7 +1395,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev db.session.refresh(existing) assert result['created_count'] == 0 - assert result['opened_existing_count'] == 1 + assert not result['pending_orders'], result['pending_orders'] + assert result['opened_existing_count'] == 1, result 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] @@ -1322,11 +1431,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide qty=10, include_process_fields=True, ) - order['evidence'] = [ - item - for item in order['evidence'] - if item['field'] != 'lines[0].reservation_id' - ] + _invalidate_dynamic_line_evidence(order, 'reservation_id') result = submit_order_extraction({ 'agent_runtime_context': runtime_context, @@ -1336,7 +1441,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide assert result['created_count'] == 0 assert result['pending_count'] == 1 - assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons'] + assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons'] assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 @@ -1370,13 +1475,13 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): assert result['pending_count'] == 1 assert 'blocking_conflict' in result['pending_orders'][0]['reasons'] candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one() - assert candidate.conflicts_json[0]['reason'] == 'cross_source_conflict' + assert any(item['reason'] == 'cross_source_conflict' for item in candidate.conflicts_json) adjudication = candidate.structured_result_json['extraction']['field_adjudication'] reservation_observations = [ item for item in adjudication['observations'] - if item['field'] == 'reservation_id' + if item['field_id'] == _ensure_order_schema()['reservation_id'] ] - assert {item['source'] for item in reservation_observations} == {'backend_table', 'dify_llm'} + assert {item['source_type'] for item in reservation_observations} == {'backend_table', 'attachment_text'} assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 @@ -1574,8 +1679,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app qty=24, include_process_fields=True, ) - order['lines'][0]['reservation_id'] = '1000140351' - order['evidence'][-1]['quote'] = '1000140351' + _set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351') result = submit_order_extraction({ 'agent_runtime_context': runtime_context, @@ -1593,8 +1697,8 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe' -def test_order_extraction_requires_verified_pair_after_reservation_adjudication(app, monkeypatch): - """裁决改写 Reservation 后,必须按 (line_index, 新值) 核验证据,不能只认行号。""" +def test_order_extraction_requires_verified_dynamic_reservation_observation(app): + """动态 Reservation Observation 的 quote 不命中原文时必须阻断,不能只认字段 ID。""" with app.app_context(): user, _session, intake, document, runtime_context = _seed_extraction_input() context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) @@ -1606,21 +1710,7 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication( qty=10, include_process_fields=True, ) - order['lines'][0]['reservation_id'] = '1000140351' - order['evidence'][-1]['quote'] = '1000140351' - - def _rewrite_reservation(summary, *, documents): - rewritten = dict(summary) - lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)] - if lines: - lines[0]['reservation_id'] = '3000092917' - rewritten['lines'] = lines - return rewritten, [] - - monkeypatch.setattr( - 'app.services.shipping_notice.order_extraction.adjudicate_order_reservations', - _rewrite_reservation, - ) + _set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351') result = submit_order_extraction({ 'agent_runtime_context': runtime_context, @@ -1631,7 +1721,7 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication( assert result['created_count'] == 0 assert result['opened_existing_count'] == 0 assert result['pending_count'] == 1 - assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons'] + assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons'] candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one() assert candidate.selected is False assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 @@ -1662,6 +1752,10 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app) db.session.add(existing) db.session.commit() + document.extracted_text = ( + f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351" + ) + db.session.commit() context_result = get_order_extraction_context({'agent_runtime_context': runtime_context}) order = _order( intake_no=intake.intake_no, @@ -1671,10 +1765,8 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app) qty=24, include_process_fields=True, ) - order['lines'][0]['reservation_id'] = '1000140351' - order['evidence'] = [ - item for item in order['evidence'] if item['field'] != 'lines[0].reservation_id' - ] + _set_dynamic_line_field(order, 'reservation_id', '1000140351') + _invalidate_dynamic_line_evidence(order, 'reservation_id') result = submit_order_extraction({ 'agent_runtime_context': runtime_context, @@ -1689,7 +1781,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app) assert candidate.consumed_task_id is None assert result['opened_existing_count'] == 0 assert result['pending_count'] == 1 - assert 'unverified_reservation_evidence' in result['pending_orders'][0]['reasons'] + assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons'] assert 'reservation_id' not in (existing.lines_json[0] or {}) diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 78cc35cd..b7d35da9 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -8,6 +8,7 @@ from app.services.shipping_notice.query_service import ( extract_task_no_from_text, get_task_by_ref, get_task_in_batch, + list_tasks_for_user, list_batch_task_summaries, resolve_task_from_payload, serialize_batch, @@ -80,6 +81,33 @@ def test_get_task_in_batch_rejects_foreign_task(app): assert get_task_in_batch("SB-B", "SN-FOREIGN") is None +def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app): + """库存缺口筛选应读取复核状态,而不是要求不存在的 process_status。""" + with app.app_context(): + from app import db + + shortage = ShippingTask( + task_no="SN-FILTER-SHORTAGE", + process_status="pending_review", + review_status="shortage_review", + pending_human_reason="shortage", + source_type="manual", + ) + ordinary = ShippingTask( + task_no="SN-FILTER-PARSE", + process_status="pending_review", + review_status="parse_review", + pending_human_reason="low_confidence", + source_type="manual", + ) + db.session.add_all([shortage, ordinary]) + db.session.commit() + + rows = list_tasks_for_user(999999, process_status="shortage_review") + + assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"] + + def test_task_export_error_message_distinct_for_missing_path(app): """无导出路径与磁盘缺失应返回不同错误文案。""" with app.app_context(): @@ -92,7 +120,7 @@ def test_task_export_error_message_distinct_for_missing_path(app): source_type="manual", export_file_path="/tmp/not-a-real-shipping-export.xlsx", ) - assert task_export_error_message(missing) == "export file missing on disk" + assert task_export_error_message(missing) == "export file not found" # 未落库 Task 不具备 Artifact 身份。 def test_task_projection_tool_strips_internal_fields(app): diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index 8e45b17c..18d698c4 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -7,11 +7,17 @@ from app.services.shipping_notice.reservation_id import ( def test_match_numeric_reservation_id(): - notice = [{"part_number": "D4-A08AR12000002", "reservation_id": "1000140351", "qty": 2}] - inventory = [{"part_number": "D4-A08AR12000002", "reservation_id": 1000140351.0, "available_qty": 3}] - status, results, _ = match_notice_lines(notice, inventory) + notice = [{"order-part": "D4-A08AR12000002", "order-reservation": "1000140351", "__required_qty": 2}] + inventory = [{"101": "D4-A08AR12000002", "102": "1000140351", "103": 3}] + status, results, _ = match_notice_lines( + notice, inventory, + match_keys=[ + {'order_field_id': 'order-part', 'inventory_field_id': '101'}, + {'order_field_id': 'order-reservation', 'inventory_field_id': '102'}, + ], + quantity_field_id='103', + ) assert status == "fulfillable" - assert results[0]["reservation_id"] == "1000140351" assert results[0]["available_qty"] == 3 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 cd6d7335..054851a8 100644 --- a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py +++ b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py @@ -12,7 +12,7 @@ from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path): """batch 开启时单票按需应写 inventory_export_batch trigger。""" trigger_dir = tmp_path / "triggers" - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True source = { @@ -41,7 +41,7 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path): def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path): """batch 关闭时仍写 legacy inventory_export trigger。""" trigger_dir = tmp_path / "triggers" - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}} @@ -49,3 +49,24 @@ def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path): path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source) assert path assert list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json")) + + +def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path): + """平台 trigger 仅保留业务 connector,且明确给 worker 兼容的 driver 与登录入口。""" + import json + from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger + + trigger_dir = tmp_path / "triggers" + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + with app.app_context(): + path = write_inventory_export_batch_trigger("RUN-DBS", [{ + "source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST", + "fixed_warehouse_id": "DUB", "login_url": "https://example.invalid/dbs", + }]) + assert path + item = json.loads((trigger_dir / "inventory_export_batch_RUN-DBS.json").read_text(encoding="utf-8"))["inventory_sources"][0] + assert item["connector_type"] == "dbs" + assert item["worker_connector_type"] == "dsv360" + assert item["entry_url"] == "https://example.invalid/dbs" + assert "username" not in item + assert "password" not in item diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index ad640b2c..ffc47e67 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -12,7 +12,13 @@ from pathlib import Path import pytest from app import db -from app.models import ChatLog, ShippingCustomer, ShippingInventoryMapping, ShippingTask, ShippingTaskEvent +from app.models import ( + ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule, + ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingTask, + ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, + ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingTaskEvent, ShippingTaskInventoryLink, +) 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 @@ -54,6 +60,23 @@ def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch): monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) +@pytest.fixture(autouse=True) +def _stable_inventory_source_for_legacy_tool_flows(app): + """为遗留库存 Tool 用例提供测试专用兜底路由,避免绕过当前 Source Gate。""" + with app.app_context(): + rule = ShippingInventoryRoutingRule( + rule_code='TEST_TOOL_SOURCE_FALLBACK', rule_name='Legacy tool test source fallback', + scope='task', priority=-100, match_mode='all', status='published', + action_type='add_source_candidates', action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1, + ) + rule.conditions.append(ShippingInventoryRoutingRuleCondition( + condition_group=1, source_kind='system_fact', system_fact_key='task.customer_code', operator='is_empty', + expected_value_json=None, sequence=1, + )) + db.session.add(rule) + db.session.commit() + + def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) -> None: """测试辅助:写入 Dublin 目的地以触发稳定库存源裁决,供库存阶段 Tool 测试使用。""" client.post( @@ -121,13 +144,18 @@ def test_match_notice_lines_reports_progress(): status, line_results, shortage = match_notice_lines( [ - {"part_number": "A001", "reservation_id": "R-1", "qty": 1}, - {"part_number": "A002", "reservation_id": "R-2", "qty": 2}, + {"order-part": "A001", "order-ref": "R-1", "__required_qty": 1}, + {"order-part": "A002", "order-ref": "R-2", "__required_qty": 2}, ], [ - {"part_number": "A001", "reservation_id": "R-1", "available_qty": 1}, - {"part_number": "A002", "reservation_id": "R-2", "available_qty": 2}, + {"701": "A001", "702": "R-1", "703": 1}, + {"701": "A002", "702": "R-2", "703": 2}, ], + match_keys=[ + {'order_field_id': 'order-part', 'inventory_field_id': '701'}, + {'order_field_id': 'order-ref', 'inventory_field_id': '702'}, + ], + quantity_field_id='703', progress_callback=lambda current, total: seen.append((current, total)), ) @@ -192,16 +220,13 @@ def test_shipping_notice_tool_flow(app, client): ) assert match_res.status_code == 200 match_data = match_res.get_json() - assert match_data["status"] == "running" - assert "订单" in match_data["message"] - assert "库存" in match_data["message"] - assert "A001" in match_data["message"] + assert match_data["status"] == "failed" + assert "订单解析版本" in match_data["message"] # 旧固定字段链不得绕过动态 Extraction。 with app.app_context(): auto_exported = ShippingTask.query.filter_by(task_no=task_id).first() assert auto_exported is not None - assert auto_exported.export_file_path - assert auto_exported.process_status == "waiting_upload" - assert auto_exported.pending_human_reason == "upload_rpa_pending" + assert auto_exported.match_status is None + assert auto_exported.export_file_path is None excel_res = client.post( "/api/shipping-notice/tools/generate_shipment_excel", @@ -209,12 +234,13 @@ def test_shipping_notice_tool_flow(app, client): json={"task_id": task_id}, ) assert excel_res.status_code == 200 - assert excel_res.get_json()["status"] == "ok" + assert excel_res.get_json()["status"] == "failed" + assert "订单解析版本" in excel_res.get_json()["message"] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None - assert task.export_file_path + assert task.export_file_path is None status_res = client.post( "/api/shipping-notice/tools/get_task_status", @@ -250,7 +276,7 @@ def test_contract_get_task_status_accepts_task_no_anchor(app, client): assert "当前进度" in data["message"] -def test_shipping_notice_match_shortage_needs_human(app, client): +def test_shipping_notice_match_requires_dynamic_order_extraction(app, client): headers = _tool_headers(app) create_res = client.post( @@ -283,27 +309,16 @@ def test_shipping_notice_match_shortage_needs_human(app, client): json={"task_id": task_id}, ) data = match_res.get_json() - assert data["status"] == "needs_human" - assert "订单" in data["message"] - assert "库存" in data["message"] - assert "缺口" in data["message"] - options = data.get("human_options") or [] - assert "confirm" not in options - assert "reparse_inventory" in options - assert "rematch" in options + assert match_res.status_code == 200 + assert data["status"] == "failed" + assert "订单解析版本" in data["message"] + assert data.get("stop_agent_turn") is True + assert "match_inventory" in (data.get("forbidden_next_tools") or []) assert "generate_shipment_excel" in (data.get("forbidden_next_tools") or []) assert "upload_to_freight" in (data.get("forbidden_next_tools") or []) - confirm_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "confirm"}, - ) - assert confirm_res.get_json()["status"] == "failed" - - -def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client, monkeypatch): - """重新匹配应同步重算库存,仍有缺口时直接回到库存不足检查点。""" +def test_submit_decision_rematch_keeps_dynamic_order_extraction_gate(app, client, monkeypatch): + """旧固定字段任务即使请求重新匹配,也不能绕过动态订单解析版本门禁。""" headers = _tool_headers(app) started: list[str] = [] @@ -352,23 +367,19 @@ def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client, ) data = rematch_res.get_json() assert rematch_res.status_code == 200 - assert data["status"] == "needs_human" - assert "已重新完成库存匹配" in data["message"] - assert "缺口" in data["message"] + assert data["status"] == "failed" + assert "订单解析版本" in data["message"] assert started == [] with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).one() - assert task.process_status == "pending_review" - assert task.review_status == "shortage_review" - assert task.pending_human_reason == "shortage" - assert task.match_status is not None - assert task.shortage_json is not None - assert task.line_results_json is not None + assert task.match_status is None + assert task.shortage_json is None + assert task.line_results_json is None -def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client, monkeypatch): - """契约:重新匹配必须通过 submit_decision(rematch) 同步完成匹配,不经后台 orchestrator 二次点击。""" +def test_contract_submit_decision_rematch_cannot_bypass_dynamic_order_gate(app, client, monkeypatch): + """契约:重新匹配仍须使用已接受的动态订单解析,不得回退旧固定字段。""" headers = _tool_headers(app) started: list[str] = [] @@ -418,12 +429,172 @@ def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client, data = rematch_res.get_json() assert rematch_res.status_code == 200 - assert data["status"] == "needs_human" + assert data["status"] == "failed" assert data["task_id"] == task_id - assert "已重新完成库存匹配" in data["message"] + assert "订单解析版本" in data["message"] assert started == [] +def test_contract_dynamic_order_shortage_and_rematch_recompute_inventory(app, client): + """已接受动态订单解析必须执行真实匹配,库存更新后 rematch 应同步重算并解除缺口。""" + headers = _tool_headers(app) + app.config["SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED"] = False + app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False + + create_res = client.post( + "/api/shipping-notice/tools/create_task", + headers=headers, + json={"source_type": "manual"}, + ) + task_id = create_res.get_json()["task_id"] + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "task_id": task_id, + "structured": { + "customer_name": "AWS", + "ship_to": "Dublin", + "lines": [{"part_number": "A001", "reservation_id": "AWS-311", "qty": 10, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).one() + inventory_fields = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(["part_number", "reservation_id", "available_qty"]) + ).all() + } + schema = ShippingOrderSchema(schema_code="SHIPPING_ORDER", display_name="Match contract") + part_field = ShippingOrderField( + id="test-order-part-number", + schema=schema, + field_code="part_number", + scope="line", + value_type="string", + ) + reservation_field = ShippingOrderField( + id="test-order-reservation-id", + schema=schema, + field_code="reservation_id", + scope="line", + value_type="string", + ) + version = ShippingOrderSchemaVersion( + schema=schema, + version=1, + status="published", + checksum="m" * 64, + definition_json={ + "fields": [ + {"id": part_field.id, "field_code": part_field.field_code, "scope": "line", "value_type": "string"}, + {"id": reservation_field.id, "field_code": reservation_field.field_code, "scope": "line", "value_type": "string"}, + ] + }, + ) + db.session.add_all([schema, part_field, reservation_field, version]) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, + input_snapshot_hash="m" * 64, + status="accepted", + ) + db.session.add(extraction) + db.session.flush() + order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key="1") + db.session.add(order_line) + db.session.flush() + part_decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, + line_id=order_line.id, + field_id=part_field.id, + decision_status="accepted", + resolved_value_json="A001", + ) + reservation_decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, + line_id=order_line.id, + field_id=reservation_field.id, + decision_status="accepted", + resolved_value_json="AWS-311", + ) + db.session.add_all([part_decision, reservation_decision]) + db.session.flush() + db.session.add_all([ + ShippingOrderFieldValue( + extraction_id=extraction.id, + line_id=order_line.id, + field_id=part_field.id, + value_text="A001", + decision_id=part_decision.id, + ), + ShippingOrderFieldValue( + extraction_id=extraction.id, + line_id=order_line.id, + field_id=reservation_field.id, + value_text="AWS-311", + decision_id=reservation_decision.id, + ), + ]) + task.current_order_extraction_id = extraction.id + task.inventory_lines_json = [{ + inventory_fields["part_number"]: "A001", + inventory_fields["reservation_id"]: "AWS-311", + inventory_fields["available_qty"]: 5, + }] + task.process_status = "inventory_ready" + db.session.commit() + assert task.current_order_extraction_id == extraction.id + + with app.app_context(): + from app.services.shipping_notice.export import order_field_id_values + + persisted_task = ShippingTask.query.filter_by(task_no=task_id).one() + persisted_extraction = db.session.get(ShippingOrderExtraction, persisted_task.current_order_extraction_id) + assert persisted_extraction is not None + assert persisted_extraction.status == "accepted" + assert order_field_id_values(persisted_task)[1][0]["test-order-part-number"] == "A001" + # Flask 测试 fixture 保持外层 app_context;清除其旧 Task identity,模拟真实独立请求重读数据库。 + db.session.expire_all() + + first_match = client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"task_id": task_id}, + ).get_json() + assert first_match["status"] == "needs_human", json.dumps(first_match, ensure_ascii=False) + assert first_match["checkpoint"] == "shortage_review" + assert first_match["stop_agent_turn"] is True + assert first_match["forbidden_next_tools"] == ["generate_shipment_excel", "upload_to_freight"] + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).one() + updated_inventory = [dict(item) for item in task.inventory_lines_json] + updated_inventory[0][inventory_fields["available_qty"]] = 20 + task.inventory_lines_json = updated_inventory + db.session.commit() + db.session.expire_all() + + rematch = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"task_id": task_id, "decision": "rematch"}, + ).get_json() + assert rematch["status"] == "ok", json.dumps(rematch, ensure_ascii=False) + assert "已重新完成库存匹配" in rematch["message"] + + with app.app_context(): + task = ShippingTask.query.filter_by(task_no=task_id).one() + assert task.process_status == "matched" + assert task.match_status == "fulfillable" + assert task.shortage_json == {"lines": []} + assert task.line_results_json[0]["available_qty"] == 20.0 + + def test_openapi_spec_public(app, client): app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com" res = client.get("/api/shipping-notice/tools/openapi.json") @@ -440,15 +611,11 @@ def test_openapi_spec_public(app, client): assert "/tools/generate_shipment_excel" not in spec["paths"] assert "/tools/upload_to_freight" not in spec["paths"] assert "/tools/switch_focus_task" not in spec["paths"] - assert "/tools/get_inventory_schema_preview" in spec["paths"] - assert "/tools/apply_inventory_mapping" in spec["paths"] - # 锁定 Dify Tool 契约:OpenAPI 暴露字符串,避免 Dify 画布无法选择上游 map_json 变量。 - apply_mapping = spec["paths"]["/tools/apply_inventory_mapping"]["post"]["requestBody"]["content"][ - "application/json" - ]["schema"] - map_json_schema = apply_mapping["properties"]["map_json"] - assert map_json_schema["type"] == "string" - assert "JSON 字符串" in map_json_schema["description"] + # 正式库存站点只能走已发布解析方案,Dify 不得恢复任务级临时映射入口。 + assert "/tools/get_inventory_schema_preview" not in spec["paths"] + assert "/tools/apply_inventory_mapping" not in spec["paths"] + assert "/tools/upload_inventory_file" not in spec["paths"] + assert "/tools/submit_temporary_inventory_mapping_suggestion" in spec["paths"] assert "/tools/confirm_inventory_source" in spec["paths"] submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"] assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"] @@ -516,179 +683,135 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords(): assert "按钮由 HXOPS 前端渲染" in submit_desc -def test_parse_inventory_from_chat_text(app, client): +@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"]) +def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision): + """已启用库存站点不得通过任务决策重开旧列映射路径。""" headers = _tool_headers(app) + with app.app_context(): + task = ShippingTask(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual", process_status="waiting_inventory") + db.session.add(task) + db.session.commit() - create_res = client.post( - "/api/shipping-notice/tools/create_task", + response = client.post( + "/api/shipping-notice/tools/submit_decision", headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "ACME", - "lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}], - "confidence": 0.95, - }, - }, + json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision}, ) - inv_text = "料号\t可用数量\nA001\t10\nB002\t5" + assert response.status_code == 200 + body = response.get_json() + # These decisions must never reopen manual mapping or mutate the task. + assert body["status"] == "failed" + assert "已发布解析方案" in body["message"] + + +def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path): + """重新上传库存只重置正式库存结果,不进入任务级字段映射。""" + headers = _tool_headers(app) + with app.app_context(): + task = ShippingTask( + task_no="SN-REUPLOAD-INVENTORY", + source_type="manual", + process_status="matched", + inventory_lines_json=[{"part_number": "A001", "available_qty": 10}], + match_status="fulfillable", + line_results_json=[{"part_number": "A001"}], + shortage_json={"lines": []}, + export_file_path=str(tmp_path / "shipment.xlsx"), + export_file_name="shipment.xlsx", + ) + db.session.add(task) + db.session.flush() + inventory_file = ShippingInventoryFile( + inventory_file_no="SIF-REUPLOAD-001", + storage_path=str(tmp_path / "inventory.xlsx"), + source_file_name="inventory.xlsx", + ) + db.session.add(inventory_file) + db.session.flush() + link = ShippingTaskInventoryLink( + task_id=task.id, + inventory_file_id=inventory_file.id, + link_role="owner", + ) + db.session.add(link) + db.session.commit() + + response = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"}, + ) + + assert response.status_code == 200 + body = response.get_json() + assert body["status"] == "needs_human" + assert body["checkpoint"] == "upload_req" + assert body["human_options"] == ["upload_inventory_file", "retry_rpa"] + with app.app_context(): + task = ShippingTask.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one() + link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one() + assert link.is_active is False + assert task.process_status == "waiting_inventory" + assert task.pending_human_reason == "inv_unavail" + assert task.inventory_lines_json is None + assert task.match_status is None + assert task.line_results_json is None + assert task.shortage_json is None + assert task.export_file_path is None + assert task.export_file_name is None + + +def test_parse_inventory_from_chat_text_route_is_removed(app, client): + """正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。""" + headers = _tool_headers(app) parse_inv = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": task_id, "raw_inventory_text": inv_text}, + json={"task_id": "SN-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"}, ) - assert parse_inv.status_code == 200 - data = parse_inv.get_json() - assert data["status"] == "needs_human" - assert data.get("checkpoint") == "align_review" - assert data.get("stop_agent_turn") is True - assert "match_inventory" in (data.get("forbidden_next_tools") or []) - assert "field_alignment" in data["data"] - assert "retry_rpa" in [button["id"] for button in data.get("action_buttons") or []] - - 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"] == "needs_human" - assert confirm_data.get("checkpoint") == "align_review" - assert "Reservation ID" in (confirm_data.get("message") or "") - - match_res = client.post( - "/api/shipping-notice/tools/match_inventory", - headers=headers, - json={"task_id": task_id}, - ) - assert match_res.get_json()["status"] in {"failed", "needs_human"} + assert parse_inv.status_code == 404 + assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" -def test_parse_inventory_empty_needs_human(app, client): +def test_parse_inventory_empty_text_route_is_removed(app, client): + """即使输入为空,已移除的正式任务库存文本入口也必须保持不可访问。""" headers = _tool_headers(app) - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - _parse_notice_for_stable_inventory_source(client, headers, task_id) res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": task_id, "raw_inventory_text": " "}, + json={"task_id": "SN-REMOVED", "raw_inventory_text": " "}, ) - assert res.get_json()["status"] == "needs_human" - body = res.get_json() - assert body.get("checkpoint") in {"map_infer", "upload_req"} - assert body.get("human_options") is not None or body.get("action_buttons") + assert res.status_code == 404 + assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" def test_match_by_supplier_sku_and_reservation_id(app, client): + """旧任务级库存解析入口不得因表头看似可识别而重新启用。""" headers = _tool_headers(app) - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "AWS", - "lines": [ - {"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"}, - {"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"}, - ], - "confidence": 0.95, - }, - }, - ) - - inv_text = ( - "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n" - "D4-A08AR12000002\t10-40594-001\tAWS-311\t2\n" - "D4-A08AR12000002\t10-40594-001\tORD-3002\t0\n" - ) - client.post( - "/api/shipping-notice/tools/parse_inventory", - headers=headers, - json={"task_id": task_id, "raw_inventory_text": inv_text}, - ) - client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "confirm_inventory_mapping"}, - ) - - match_res = client.post( - "/api/shipping-notice/tools/match_inventory", - headers=headers, - json={"task_id": task_id}, - ) - data = match_res.get_json() - assert data["status"] == "needs_human" - results = {r["reservation_id"]: r for r in data["data"]["line_results"]} - assert results["AWS-311"]["line_status"] == "ok" - assert results["ORD-3002"]["line_status"] == "shortage" - - -def test_match_inventory_blocked_before_mapping_confirm(app, client): - headers = _tool_headers(app) - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "AWS", - "lines": [{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}], - "confidence": 0.95, - }, - }, - ) - client.post( + removed = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": task_id, + "task_id": "SN-REMOVED", + "raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n", + }, + ) + assert removed.status_code == 404 + + +def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, client): + """正式任务不存在待确认的任务级映射,旧解析入口必须直接不可访问。""" + headers = _tool_headers(app) + removed = client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={ + "task_id": "SN-REMOVED", "raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n", }, ) - - match_res = client.post( - "/api/shipping-notice/tools/match_inventory", - headers=headers, - json={"task_id": task_id}, - ) - blocked = match_res.get_json() - assert blocked["status"] == "needs_human" - assert blocked.get("checkpoint") == "align_review" - assert blocked.get("stop_agent_turn") is True - assert "field_alignment" in blocked["data"] - mapping = blocked["data"]["field_alignment"] - assert mapping["inventory_columns"]["mapping"]["part_number"]["source_column"] == "Supplier Sku" - assert mapping["inventory_columns"]["mapping"]["aws_part_number"]["source_column"] == "AWS Sku" - assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID" + assert removed.status_code == 404 def test_match_inventory_requires_reservation_id(app, client): @@ -719,7 +842,6 @@ def test_match_inventory_requires_reservation_id(app, client): db.session.commit() from app.services.shipping_notice.inventory_workflow import ( ensure_inventory as ensure_inventory_service, - parse_inventory as parse_inventory_service, upload_inventory_file as upload_inventory_file_service, ) from io import BytesIO @@ -733,14 +855,6 @@ def test_match_inventory_requires_reservation_id(app, client): assert direct_data.get("checkpoint") == "rsv_req" assert not task.inventory_lines_json - parse_data = parse_inventory_service({ - "task_id": task_id, - "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}], - }) - assert parse_data["status"] == "needs_human" - assert parse_data.get("checkpoint") == "rsv_req" - assert not task.inventory_lines_json - upload_data = upload_inventory_file_service( task_id, FileStorage(stream=BytesIO(b"sku,qty\nA001,1"), filename="inventory.csv"), @@ -754,65 +868,21 @@ def test_match_inventory_requires_reservation_id(app, client): assert match_data.get("checkpoint") == "rsv_req" -def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path): +def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, client, tmp_path): + """正式任务不允许通过旧入口重开任务级映射修正。""" headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "AWS", - "lines": [ - { - "part_number": "D4-A08AR12000002", - "aws_part_number": "10-40594-001", - "reservation_id": "AWS-311", - "qty": 1, - "uom": "EA", - } - ], - "confidence": 0.95, - }, - }, - ) - client.post( + removed = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": task_id, + "task_id": "SN-REMOVED", "raw_inventory_text": ( "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n" "D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n" ), }, ) - - correct_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "correct_inventory_mapping"}, - ) - data = correct_res.get_json() - assert data["status"] == "needs_human" - assert data.get("checkpoint") == "map_infer" - assert data.get("stop_agent_turn") is True - assert "schema_preview" in data["data"] - assert data["data"]["schema_preview"]["headers"] == [ - "Supplier Sku", - "AWS Sku", - "COM ID", - "Qty Available", - ] + assert removed.status_code == 404 def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): @@ -821,8 +891,8 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): trigger = tmp_path / "triggers" drop.mkdir() trigger.mkdir() - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop) - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) create_res = client.post( "/api/shipping-notice/tools/create_task", @@ -860,15 +930,8 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): seed_rpa_inventory_trigger(task, run_no="RUN-TOOLS-CB") db.session.commit() - from openpyxl import Workbook - inv_file = drop / "stock.xlsx" - wb = Workbook() - ws = wb.active - ws.append(["Warehouse ID", "Supplier Sku", "Reservation ID", "可用数量"]) - ws.append(["AWSDU", "A001", "R-1", 20]) - wb.save(inv_file) - wb.close() + inv_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU", qty=20).getvalue()) from app.services.shipping_notice import tools as shipping_tools @@ -880,13 +943,12 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): "file_path": str(inv_file), "run_no": "RUN-TOOLS-CB", "source_code": "DSV360_AWSDU", - "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 []) + assert data["status"] == "ok" + assert data.get("checkpoint") == "ready_to_match" + assert "confirm_inventory_mapping" not in (data.get("human_options") or []) with app.app_context(): task = ShippingTask.query.filter_by(task_no=task_id).first() assert task is not None @@ -899,8 +961,8 @@ def test_rpa_upload_callback(app, client, tmp_path): trigger = tmp_path / "upload_triggers" queue.mkdir() trigger.mkdir() - app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(queue) - app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(queue) + app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(trigger) create_res = client.post( "/api/shipping-notice/tools/create_task", @@ -1004,294 +1066,20 @@ def test_generate_shipment_excel_writes_part_number_and_odm_id(app, client): json={"task_id": task_id}, ) assert excel_res.status_code == 200 - assert excel_res.get_json()["status"] == "ok" - - from openpyxl import load_workbook - - with app.app_context(): - task = ShippingTask.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.export_file_path - wb = load_workbook(task.export_file_path, read_only=True) - header_ws = wb["PVMI Pull Request Header"] - detail_ws = wb["PVMI Pull Request Detail"] - assert header_ws.cell(4, 6).value == "16754796" - assert detail_ws.cell(4, 4).value == "504-010213-001" - wb.close() + assert excel_res.get_json()["status"] == "failed" + assert "订单解析版本" in excel_res.get_json()["message"] # 旧固定字段链必须在动态 Extraction 门禁处阻断。 -def test_upload_inventory_file_parses_server_side(app, client, tmp_path): +def test_legacy_task_inventory_mapping_routes_are_removed(app, client): + """任务级库存上传和列映射已下线,不能再成为正式库存解析旁路。""" headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000 - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "AWS", - "lines": [{"part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}], - "confidence": 0.95, - }, - }, - ) - - from io import BytesIO - - from openpyxl import Workbook - - buf = BytesIO() - wb = Workbook() - ws = wb.active - ws.append(["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"]) - ws.append(["AWSDU", "D4-A08AR12000002", "10-40594-001", "AWS-311", 5]) - wb.save(buf) - wb.close() - buf.seek(0) - - upload_res = client.post( + for path in ( "/api/shipping-notice/tools/upload_inventory_file", - headers={k: v for k, v in headers.items() if k.lower() != "content-type"}, - data={ - "task_id": task_id, - "file": (buf, "inventory.xlsx"), - }, - ) - assert upload_res.status_code == 200 - upload_data = upload_res.get_json() - assert upload_data["status"] == "ok" - assert upload_data.get("checkpoint") == "map_infer" - preview = upload_data["data"]["schema_preview"] - assert preview["headers"] == ["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"] - assert preview["suggested_mapping"]["part_number"] == "Supplier Sku" - assert preview["suggested_mapping"]["aws_part_number"] == "AWS Sku" - - apply_res = client.post( - "/api/shipping-notice/tools/apply_inventory_mapping", - headers=headers, - json={ - "task_id": task_id, - "map_json": { - **preview["suggested_mapping"], - "match_rule": "LLM:Reservation Order 对齐订单 reservation_id,汇总 Qty Available。", - }, - }, - ) - apply_data = apply_res.get_json() - assert apply_data["status"] == "needs_human" - assert apply_data.get("checkpoint") == "align_review" - assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1 - assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:") - assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm" - with app.app_context(): - assert ShippingInventoryMapping.query.filter_by(customer_code="GLOBAL").count() >= 1 - - -def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_path, monkeypatch): - """已手工上传完成的票不能被后续批次库存快照重新带回 RPA 上传链路。""" - from io import BytesIO - - from openpyxl import Workbook - - from app.models import ShippingBatch, ShippingTaskInventoryLink - from app.services.shipping_notice import inventory_file_store - from tests.conftest import seed_task_inventory_source - - headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(tmp_path / "freight" / "upload_queue") - app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(tmp_path / "freight" / "upload_triggers") - - started_task_nos: list[str] = [] - - def fake_start_task_orchestrator(task_no: str) -> bool: - started_task_nos.append(task_no) - return True - - monkeypatch.setattr(inventory_file_store, "start_task_orchestrator", fake_start_task_orchestrator, raising=False) - - with app.app_context(): - batch = ShippingBatch(batch_no="SB-COMPLETED-LOCK", file_count=2) - completed = ShippingTask( - task_no="SN-20260629-DONE0001", - batch=batch, - source_type="manual", - process_status="uploaded", - pending_human_reason=None, - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}], - batch_index=1, - batch_total=2, - ) - pending = ShippingTask( - task_no="SN-20260629-PEND0002", - batch=batch, - source_type="manual", - process_status="waiting_inventory", - lines_json=[{"part_number": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}], - batch_index=2, - batch_total=2, - ) - seed_task_inventory_source(pending, source_code="DSV360_AWSDU") - db.session.add_all([batch, completed, pending]) - db.session.commit() - - buf = BytesIO() - wb = Workbook() - ws = wb.active - ws.append(["Warehouse ID", "SKU", "Reservation ID", "Available Qty"]) - ws.append(["AWSDU", "A001", "R-1", 10]) - ws.append(["AWSDU", "A002", "R-2", 10]) - wb.save(buf) - wb.close() - buf.seek(0) - - upload_res = client.post( - "/api/shipping-notice/tools/upload_inventory_file", - headers={k: v for k, v in headers.items() if k.lower() != "content-type"}, - data={"task_id": "SN-20260629-PEND0002", "file": (buf, "inventory.xlsx")}, - ) - assert upload_res.status_code == 200 - - with app.app_context(): - completed = ShippingTask.query.filter_by(task_no="SN-20260629-DONE0001").one() - pending = ShippingTask.query.filter_by(task_no="SN-20260629-PEND0002").one() - completed_links = ShippingTaskInventoryLink.query.filter_by(task_id=completed.id, is_active=True).count() - pending_links = ShippingTaskInventoryLink.query.filter_by(task_id=pending.id, is_active=True).count() - - assert completed.process_status == "uploaded" - assert completed.pending_human_reason is None - assert completed_links == 0 - assert pending_links == 1 - assert "SN-20260629-DONE0001" not in started_task_nos - - -def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path): - headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - _parse_notice_for_stable_inventory_source(client, headers, task_id) - - from io import BytesIO - - from openpyxl import Workbook - - wb = Workbook() - ws = wb.active - ws.append(["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"]) - ws.append(["AWSDU", "D4-A08AR12000002", "504-010213-001", "1000140351", 5]) - buf = BytesIO() - wb.save(buf) - buf.seek(0) - - client.post( - "/api/shipping-notice/tools/upload_inventory_file", - headers={k: v for k, v in headers.items() if k.lower() != "content-type"}, - data={"task_id": task_id, "file": (buf, "inventory.xlsx")}, - ) - - apply_res = client.post( - "/api/shipping-notice/tools/apply_inventory_mapping", - headers=headers, - json={ - "task_id": task_id, - "column_mapping_json": { - "part_number": "Supplier Sku", - "reservation_id": "COM ID", - "available_qty": "Qty Available", - }, - }, - ) - apply_data = apply_res.get_json() - match_rule = apply_data["data"]["field_alignment"]["match_rule"] - assert "Supplier Sku" in match_rule - assert "COM ID" in match_rule - assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback" - - -def test_get_inventory_schema_preview(app, client, tmp_path): - headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - _parse_notice_for_stable_inventory_source(client, headers, task_id) - - missing = client.post( "/api/shipping-notice/tools/get_inventory_schema_preview", - headers=headers, - json={"task_id": task_id}, - ) - assert missing.get_json()["checkpoint"] == "upload_req" - - -def test_apply_inventory_mapping_custom_headers(app, client, tmp_path): - headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - _parse_notice_for_stable_inventory_source(client, headers, task_id) - - from io import BytesIO - - from openpyxl import Workbook - - buf = BytesIO() - wb = Workbook() - ws = wb.active - ws.append(["Warehouse ID", "Part No", "Resv", "On Hand"]) - ws.append(["AWSDU", "SKU-99", "R-1", 12]) - wb.save(buf) - wb.close() - buf.seek(0) - - client.post( - "/api/shipping-notice/tools/upload_inventory_file", - headers={k: v for k, v in headers.items() if k.lower() != "content-type"}, - data={"task_id": task_id, "file": (buf, "inv.xlsx")}, - ) - - apply_res = client.post( "/api/shipping-notice/tools/apply_inventory_mapping", - headers=headers, - json={ - "task_id": task_id, - "column_mapping_json": { - "part_number": "Part No", - "reservation_id": "Resv", - "available_qty": "On Hand", - }, - }, - ) - apply_data = apply_res.get_json() - assert apply_data["status"] == "needs_human" - assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1 - sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0] - assert sample["part_number"] == "SKU-99" - assert sample["available_qty"] == 12 + ): + response = client.post(path, headers=headers, json={"task_id": "SN-LEGACY-REMOVED"}) + assert response.status_code == 404 def test_confirm_parse_does_not_skip_inventory_match(app, client): @@ -1611,7 +1399,7 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) called: dict[str, str] = {} def fake_start_task_orchestrator(task_no: str | None) -> bool: @@ -1655,86 +1443,8 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli assert called.get("task_no") == task_id -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] = {} - - def fake_start_task_orchestrator(task_no: str | None) -> bool: - called["task_no"] = str(task_no or "") - 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", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - client.post( - "/api/shipping-notice/tools/parse_notice", - headers=headers, - json={ - "task_id": task_id, - "structured": { - "customer_name": "ACME", - "lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}], - "confidence": 0.95, - }, - }, - ) - - with app.app_context(): - task = ShippingTask.query.filter_by(task_no=task_id).first() - assert task is not None - task_db_id = task.id - task.inventory_lines_json = [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}] - task.process_status = "inventory_ready" - task.review_status = "align_review" - task.pending_human_reason = "align_review" - db.session.commit() - - with app.app_context(): - db.session.add( - ShippingTaskEvent( - task_id=task_db_id, - event_type="inventory_mapping_inferred", - detail_json={ - "column_meta": { - "headers": ["Reservation ID", "SKU", "Qty Available"], - "field_mapping": { - "reservation_id": "Reservation ID", - "part_number": "SKU", - "available_qty": "Qty Available", - }, - "mapping": { - "reservation_id": {"source_column": "Reservation ID"}, - "sku": {"source_column": "SKU"}, - "available_qty": {"source_column": "Qty Available"}, - }, - } - }, - ) - ) - db.session.commit() - 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 -def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path, monkeypatch): +def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch): monkeypatch.setattr( "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", lambda *args, **kwargs: None, @@ -1744,8 +1454,8 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp inventory_drop = tmp_path / "inventory_drop" trigger.mkdir() inventory_drop.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop) create_res = client.post( "/api/shipping-notice/tools/create_task", @@ -1759,8 +1469,8 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp assert task is not None task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}] task.process_status = "inventory_ready" - task.review_status = "align_review" - task.pending_human_reason = "align_review" + task.review_status = None + task.pending_human_reason = "inv_unavail" task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "R-1", "available_qty": 3}] task.match_status = "fulfillable" task.shortage_json = {"lines": []} @@ -1813,7 +1523,7 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp @pytest.mark.auto_rpa -def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path): +def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch): from datetime import datetime, timedelta from app.services.shipping_notice.batch_orchestrator import _run_single_task @@ -1822,8 +1532,12 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 + monkeypatch.setattr( + "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", + lambda: None, + ) create_res = client.post( "/api/shipping-notice/tools/create_task", @@ -1886,8 +1600,8 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa inventory_drop = tmp_path / "inventory_drop" trigger.mkdir() inventory_drop.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop) create_res = client.post( "/api/shipping-notice/tools/create_task", @@ -1947,7 +1661,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa @pytest.mark.auto_rpa -def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path): +def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path, monkeypatch): from datetime import datetime, timedelta from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks @@ -1956,8 +1670,12 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() - app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 + monkeypatch.setattr( + "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", + lambda: None, + ) create_res = client.post( "/api/shipping-notice/tools/create_batch", @@ -2150,27 +1868,16 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon assert captured["mode"] == "retry_rpa" -def test_parse_inventory_rejects_oversized_text(app, client): +def test_parse_inventory_oversized_text_route_is_removed(app, client): + """旧正式库存文本入口无论内容大小都不可访问。""" headers = _tool_headers(app) - app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100 - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - _parse_notice_for_stable_inventory_source(client, headers, task_id) - res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": task_id, "raw_inventory_text": "x" * 200}, + json={"task_id": "SN-REMOVED", "raw_inventory_text": "x" * 200}, ) - data = res.get_json() - assert data["status"] == "needs_human" - assert data.get("checkpoint") == "upload_req" - assert "过大" in data["message"] + assert res.status_code == 404 + assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" def test_chat_actions_empty_when_task_rejected(app): diff --git a/backend/tests/test_shipping_order_customer_matching.py b/backend/tests/test_shipping_order_customer_matching.py new file mode 100644 index 00000000..e0677376 --- /dev/null +++ b/backend/tests/test_shipping_order_customer_matching.py @@ -0,0 +1,161 @@ +""" +backend/tests/test_shipping_order_customer_matching.py + +用途:验证订单 Bill-to / Ship-to 与货代客户主数据的角色化匹配。 +依赖:订单 Schema 模型、客户主数据模型、order_customer_matching 服务。 +逻辑:覆盖标准名称、审核别名、歧义、未命中和人工确认快照。 +""" + +from app import db +from app.models import ( + ShippingCustomer, + ShippingCustomerExternalRef, + ShippingCustomerIdentifier, + ShippingCustomerSite, + ShippingCustomerSiteIdentifier, + ShippingOrderExtraction, + ShippingOrderSchema, + ShippingOrderSchemaVersion, +) +from app.services.shipping_notice.customer_normalization import normalize_customer_name +from app.services.shipping_notice.order_customer_matching import ( + confirm_order_customer_match, + refresh_order_customer_matches, +) + + +def _extraction() -> ShippingOrderExtraction: + """构造角色化客户匹配测试所需的最小订单解析记录。""" + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单字段') + db.session.add(schema) + db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='draft', definition_json={}) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + return extraction + + +def test_order_customer_matching_resolves_roles_and_short_codes(app): + """Bill-to/Ship-to 应可命中不同客户,简称必须来自主数据。""" + with app.app_context(): + bill_to = ShippingCustomer(standard_name='Amazon Web Services', short_code='AWS') + db.session.add(bill_to) + db.session.flush() + ship_to = ShippingCustomerSite( + customer_id=bill_to.id, site_name='Amazon Dublin DC', site_code='DUB01', status='active', + ) + db.session.add(ship_to) + db.session.flush() + db.session.add(ShippingCustomerSiteIdentifier( + site_id=ship_to.id, + identifier_type='name_alias', source_system='', + raw_value='AWS Dublin DC', + normalized_value=normalize_customer_name('AWS Dublin DC'), + status='approved', + )) + extraction = _extraction() + + results = refresh_order_customer_matches(extraction, { + 'bill_to_customer': 'Amazon Web Services', + 'ship_to_customer': 'AWS Dublin DC', + }) + + by_role = {item['role']: item for item in results} + assert by_role['bill_to']['customer_id'] == bill_to.id + assert by_role['bill_to']['short_code'] == 'AWS' + assert by_role['ship_to']['customer_id'] == bill_to.id + assert by_role['ship_to']['site_id'] == ship_to.id + assert by_role['ship_to']['short_code'] == 'AWS' + + +def test_order_customer_matching_keeps_ambiguous_and_manual_confirmation(app): + """同一别名对应多个客户时不得自动选择,人工确认后锁定标准名称和简称。""" + with app.app_context(): + first = ShippingCustomer(standard_name='Customer One', short_code='ONE') + second = ShippingCustomer(standard_name='Customer Two', short_code='TWO') + db.session.add_all([first, second]) + db.session.flush() + normalized = normalize_customer_name('Shared Alias') + db.session.add_all([ + ShippingCustomerIdentifier( + customer_id=first.id, identifier_type='name_alias', raw_value='Shared Alias', + normalized_value=normalized, status='approved', + ), + ShippingCustomerIdentifier( + customer_id=second.id, identifier_type='name_alias', raw_value='Shared Alias', + normalized_value=normalized, status='approved', + ), + ]) + extraction = _extraction() + results = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Shared Alias'}) + bill_to = next(item for item in results if item['role'] == 'bill_to') + assert bill_to['status'] == 'ambiguous' + assert bill_to['customer_id'] is None + assert len(bill_to['candidates']) == 2 + + confirmed = confirm_order_customer_match( + extraction.id, role='bill_to', customer_id=second.id, actor_id=None, + ) + assert confirmed['status'] == 'confirmed' + assert confirmed['standard_name'] == 'Customer Two' + assert confirmed['short_code'] == 'TWO' + + +def test_order_customer_matching_prefers_external_customer_and_site_codes(app): + """外部客户编码和 Ship-to Code 应优先于不可靠的原文名称。""" + with app.app_context(): + customer = ShippingCustomer(standard_name='Canonical Customer', short_code='CAN') + db.session.add(customer) + db.session.flush() + db.session.add(ShippingCustomerExternalRef( + customer_id=customer.id, source_system='ERP', legacy_customer_key='C001', + )) + site = ShippingCustomerSite( + customer_id=customer.id, site_name='Dublin Site', site_code='DUB01', status='active', + ) + db.session.add(site) + db.session.flush() + db.session.add(ShippingCustomerSiteIdentifier( + site_id=site.id, identifier_type='external_code', source_system='ERP', + raw_value='DUB-EXT', normalized_value='DUB-EXT', status='approved', + )) + extraction = _extraction() + + results = refresh_order_customer_matches(extraction, { + 'bill_to_customer': 'Wrong Name', 'bill_to_customer_code': 'c001', 'bill_to_source_system': 'erp', + 'ship_to_customer': 'Wrong Site', 'ship_to_code': 'dub-ext', 'ship_to_source_system': 'erp', + }) + + by_role = {item['role']: item for item in results} + assert by_role['bill_to']['customer_id'] == customer.id + assert by_role['bill_to']['resolution_method'] == 'external_customer_code' + assert by_role['ship_to']['site_id'] == site.id + assert by_role['ship_to']['resolution_method'] == 'external_site_code' + + +def test_ship_to_matching_falls_back_to_name_when_external_code_misses(app): + """Ship-to 外部编码未命中时应继续使用站点标准名称,避免有效站点被错误判为未匹配。""" + with app.app_context(): + customer = ShippingCustomer(standard_name='Fallback Customer', short_code='FBC') + db.session.add(customer) + db.session.flush() + site = ShippingCustomerSite( + customer_id=customer.id, site_name='Fallback Delivery Site', site_code='FBS01', status='active', + ) + db.session.add(site) + extraction = _extraction() + + results = refresh_order_customer_matches(extraction, { + 'ship_to_customer': 'Fallback Delivery Site', + 'ship_to_code': 'UNKNOWN-CODE', + 'ship_to_source_system': 'ERP', + }) + + ship_to = next(item for item in results if item['role'] == 'ship_to') + assert ship_to['site_id'] == site.id + assert ship_to['resolution_method'] == 'site_name' diff --git a/backend/tests/test_shipping_order_schema.py b/backend/tests/test_shipping_order_schema.py new file mode 100644 index 00000000..9943b48f --- /dev/null +++ b/backend/tests/test_shipping_order_schema.py @@ -0,0 +1,445 @@ +""" +backend/tests/test_shipping_order_schema.py + +用途:验证唯一订单 Schema、动态字段、不可变版本和管理员 API 门禁。 +依赖:Flask 测试客户端、订单 Schema service/models、测试数据库。 +逻辑:覆盖初始化、草稿发布、稳定 checksum、字段冻结、权限与动态结果唯一约束。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest +from sqlalchemy.exc import IntegrityError + +from app import db +from app.models import ( + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingOrderExtraction, + ShippingOrderField, + ShippingOrderFieldDecision, + ShippingOrderFieldValue, + ShippingOrderSchemaAuditEvent, + ShippingOrderSchemaVersion, + User, +) +from app.services.shipping_notice.order_schema import service +from tests.conftest import parse_api_data, parse_api_error + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造管理 API 测试使用的遗留 Header 身份。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +def _seed_users() -> None: + """创建订单 Schema 权限测试所需管理员和普通用户。""" + db.session.add_all([ + User(username='schema-admin', email='schema-admin@example.com', role='admin', status='active'), + User(username='schema-user', email='schema-user@example.com', role='user', status='active'), + ]) + db.session.commit() + + +def _field_config(field_id: str, *, name: str = '需求数量') -> dict: + """构造可发布的行字段配置,关键证据策略显式启用。""" + return { + 'field_id': field_id, + 'display_name': name, + 'required': True, + 'aliases': ['Qty', 'Quantity'], + 'normalizer_key': 'decimal', + 'validator_keys': ['positive_decimal'], + 'enum_options': [], + 'evidence_policy': { + 'required': True, + 'source_precedence': ['attachment_table', 'email_body_table', 'dify_llm'], + 'conflict_policy': 'block', + 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'decimal', + 'extraction_instruction': '仅提取订单行明确出现的正数数量', + } + + +def _save_draft(version_id: int, fields: list[dict], *, change_note: str | None = None) -> dict: + """使用数据库当前锁版本保存草稿,模拟正常管理端请求。""" + version = db.session.get(ShippingOrderSchemaVersion, version_id) + assert version is not None + return service.save_draft(version_id, { + 'fields': fields, + 'change_note': change_note, + 'expected_lock_version': version.lock_version, + }) + + +def _publish_draft(version_id: int) -> dict: + """使用数据库当前锁版本发布草稿,避免测试绕过乐观锁门禁。""" + version = db.session.get(ShippingOrderSchemaVersion, version_id) + assert version is not None + return service.publish(version_id, actor_id=None, expected_lock_version=version.lock_version) + + +def test_order_schema_publish_keeps_history_when_field_code_changes(app): + """发布后可重命名系统标识,但旧契约快照保持原名称且位置/类型仍锁定。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal', + }, actor_id=None) + draft = service.create_draft({'change_note': '初始字段'}, actor_id=None) + _save_draft(draft['id'], [_field_config(field['id'])]) + published = _publish_draft(draft['id']) + + assert published['status'] == 'published' + assert len(published['checksum']) == 64 + contract = service.get_published_contract() + assert contract['fields'][0]['field_code'] == 'request_qty' + assert contract['fields'][0]['scope'] == 'line' + + renamed = service.save_field({ + 'field_code': 'renamed_qty', 'scope': 'line', 'value_type': 'decimal', + }, actor_id=None, field_id=field['id']) + assert renamed['field_code'] == 'renamed_qty' + assert service.get_published_contract()['fields'][0]['field_code'] == 'request_qty' + + with pytest.raises(Exception) as exc_info: + service.save_field({ + 'field_code': 'renamed_qty', 'scope': 'header', 'value_type': 'decimal', + }, actor_id=None, field_id=field['id']) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_IMMUTABLE' + + +def test_order_schema_excluded_field_config_is_saved_but_not_published(app): + """未纳入字段仍保存版本显示名称和规则,但发布契约不得包含该字段。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + included = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + excluded = service.save_field({ + 'field_code': 'customer_note', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + included_config = _field_config(included['id'], name='采购订单号') + included_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) + excluded_config = _field_config(excluded['id'], name='下个版本客户备注') + excluded_config.update({ + 'enabled': False, + 'normalizer_key': 'trim', + 'validator_keys': [], + 'comparator_key': 'normalized_text', + }) + + saved = _save_draft(draft['id'], [included_config, excluded_config]) + saved_excluded = next(item for item in saved['definition']['fields'] if item['field_id'] == excluded['id']) + assert saved_excluded['enabled'] is False + assert saved_excluded['display_name'] == '下个版本客户备注' + assert saved['field_count'] == 1 + + published = _publish_draft(draft['id']) + assert [item['field_id'] for item in published['definition']['fields']] == [included['id'], excluded['id']] + assert service.get_published_contract()['fields'][0]['field_id'] == included['id'] + assert len(service.get_published_contract()['fields']) == 1 + + +def test_order_schema_new_publish_retires_previous_version(app): + """新版本发布后应自动退役旧版本,数据库最多只有一个 published。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + first = service.create_draft({}, actor_id=None) + config = _field_config(field['id'], name='订单号') + config.update({'normalizer_key': 'trim', 'validator_keys': ['non_empty'], 'comparator_key': 'normalized_text'}) + _save_draft(first['id'], [config]) + _publish_draft(first['id']) + + second = service.create_draft({'copy_from_version_id': first['id']}, actor_id=None) + _publish_draft(second['id']) + + rows = ShippingOrderSchemaVersion.query.order_by(ShippingOrderSchemaVersion.version).all() + assert [item.status for item in rows] == ['retired', 'published'] + + +def test_order_schema_admin_api_permissions_and_validation(app, client): + """普通用户不得访问配置;管理员可初始化并收到结构化字段错误。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _seed_users() + + forbidden = client.get('/api/admin/shipping-order-schema', headers=_headers('schema-user', 'user')) + assert forbidden.status_code == 403 + assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN' + + created = client.post( + '/api/admin/shipping-order-schema', + headers=_headers('schema-admin', 'admin'), + json={'display_name': '发货订单字段'}, + ) + assert created.status_code == 201 + assert parse_api_data(created.get_json())['schema']['schema_code'] == 'SHIPPING_ORDER' + + invalid = client.post( + '/api/admin/shipping-order-schema/fields', + headers=_headers('schema-admin', 'admin'), + json={'field_code': 'Bad Code', 'scope': 'line', 'value_type': 'string'}, + ) + assert invalid.status_code == 400 + assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.ORDER_FIELD_INVALID' + + +def test_dynamic_header_field_value_is_unique(app): + """Header 动态字段值必须按 extraction+field 唯一,避免 NULL 绕过唯一约束。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + config = _field_config(field['id'], name='订单号') + config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) + _save_draft(draft['id'], [config]) + _publish_draft(draft['id']) + extraction = ShippingOrderExtraction( + schema_version_id=draft['id'], input_snapshot_hash='a' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, field_id=field['id'], decision_status='accepted', + supporting_observation_ids_json=[], resolved_value_json='PO-1', + ) + db.session.add(decision) + db.session.flush() + db.session.add_all([ + ShippingOrderFieldValue( + extraction_id=extraction.id, field_id=field['id'], decision_id=decision.id, value_text='PO-1', + ), + ShippingOrderFieldValue( + extraction_id=extraction.id, field_id=field['id'], decision_id=decision.id, + value_text='PO-2', value_decimal=Decimal('2'), + ), + ]) + with pytest.raises(IntegrityError): + db.session.commit() + db.session.rollback() + + +def test_order_schema_rejects_non_boolean_required_and_referenced_retire(app): + """草稿字段 required 必须为布尔值,且草稿引用字段不可退役。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + invalid = _field_config(field['id']) + invalid['required'] = 'false' + with pytest.raises(Exception) as exc_info: + _save_draft(draft['id'], [invalid]) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID' + + _save_draft(draft['id'], [_field_config(field['id'])]) + with pytest.raises(Exception) as retire_exc: + service.retire_field(field['id']) + assert getattr(retire_exc.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED' + + +def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app): + """未发布且无任何引用的字段应物理删除,并在同一事务移出当前草稿。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'temporary_note', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + config = _field_config(field['id'], name='临时备注') + config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) + _save_draft(draft['id'], [config]) + + result = service.delete_field(field['id']) + + assert result == {'field_id': field['id'], 'action': 'deleted'} + assert db.session.get(ShippingOrderField, field['id']) is None + assert service.get_state()['fields'] == [] + assert service.get_state()['versions'][0]['field_count'] == 0 + + +def test_delete_historical_order_field_archives_and_hides_current_catalog(app): + """已发布字段删除时须保留历史契约,但不再返回当前配置清单。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + config = _field_config(field['id'], name='订单号') + config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) + _save_draft(draft['id'], [config]) + _publish_draft(draft['id']) + next_draft = service.create_draft({}, actor_id=None) + + result = service.delete_field(field['id']) + + assert result == {'field_id': field['id'], 'action': 'archived'} + assert db.session.get(ShippingOrderField, field['id']).status == 'retired' + assert service.get_state()['fields'] == [] + assert service.get_state()['versions'][0]['id'] == next_draft['id'] + assert service.get_state()['versions'][0]['field_count'] == 0 + + +def test_order_field_retire_is_blocked_by_active_cross_domain_config(app): + """库存解析匹配键和 Excel 映射引用稳定字段时,字段不得退役。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + match_field = service.save_field({ + 'field_code': 'odm_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + template_field = service.save_field({ + 'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal', + }, actor_id=None) + db.session.add_all([ + ShippingInventoryParsingProfile( + profile_code='shared-stock', display_name='共享库存解析', status='published', + definition_json={ + 'match_keys': [{ + 'order_field_id': match_field['id'], + 'inventory_field': 'odm', + }], + }, + ), + ShippingExcelTemplate( + template_code='forwarder-a', display_name='货代模板 A', status='draft', + storage_provider='minio', storage_bucket='test-private', + storage_key='shipping/templates/test.xlsx', original_filename='test.xlsx', + file_checksum='a' * 64, + definition_json={ + 'mappings': [{ + 'source_kind': 'order_field', + 'source_key': template_field['id'], + 'target': {'sheet': 'Sheet1', 'cell': 'A2'}, + }], + }, + ), + ]) + db.session.commit() + + for field_id in (match_field['id'], template_field['id']): + with pytest.raises(Exception) as exc_info: + service.retire_field(field_id) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED' + + +def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app): + """新 Schema 版本移除下游仍在使用的字段时,发布必须在运行前阻断。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + referenced = service.save_field({ + 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + replacement = service.save_field({ + 'field_code': 'new_part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=None) + first = service.create_draft({}, actor_id=None) + referenced_config = _field_config(referenced['id']) + referenced_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []}) + _save_draft(first['id'], [referenced_config]) + _publish_draft(first['id']) + db.session.add(ShippingInventoryParsingProfile( + profile_code='schema-gate', display_name='Schema Gate', status='published', + definition_json={'match_keys': [{ + 'order_field_id': referenced['id'], 'inventory_field': 'part_number', + }]}, + )) + db.session.commit() + + second = service.create_draft({}, actor_id=None) + replacement_config = _field_config(replacement['id']) + replacement_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []}) + _save_draft(second['id'], [replacement_config]) + with pytest.raises(Exception) as exc_info: + _publish_draft(second['id']) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED' + assert service.get_published_contract()['fields'][0]['field_id'] == referenced['id'] + + +def test_order_schema_rejects_type_incompatible_rules_and_can_delete_draft(app): + """字段规则须与类型兼容,错误草稿可删除后重新创建。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + invalid = _field_config(field['id']) + invalid['normalizer_key'] = 'uppercase_trim' + with pytest.raises(Exception) as exc_info: + _save_draft(draft['id'], [invalid]) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID' + + service.delete_draft(draft['id']) + replacement = service.create_draft({}, actor_id=None) + assert replacement['version'] == 1 + + +def test_order_schema_draft_save_replaces_previous_field_configs(app): + """重复保存草稿必须整体替换字段配置,不得残留 ORM 旧行。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + qty = service.save_field({ + 'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal', + }, actor_id=None) + po = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + draft = service.create_draft({}, actor_id=None) + _save_draft(draft['id'], [_field_config(qty['id'])]) + po_config = _field_config(po['id'], name='订单号') + po_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) + saved = _save_draft(draft['id'], [po_config]) + assert saved['field_count'] == 1 + assert saved['definition']['fields'][0]['field_id'] == po['id'] + + +def test_order_schema_draft_uses_optimistic_lock_and_writes_audit(app): + """过期锁版本必须拒绝覆盖,成功保存和发布均产生不可变审计事件。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', + }, actor_id=None, request_id='field-request') + draft = service.create_draft({}, actor_id=None, request_id='create-request') + config = _field_config(field['id'], name='订单号') + config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) + + saved = service.save_draft(draft['id'], { + 'fields': [config], 'expected_lock_version': draft['lock_version'], + }, actor_id=None, request_id='save-request') + with pytest.raises(Exception) as exc_info: + service.save_draft(draft['id'], { + 'fields': [config], 'expected_lock_version': draft['lock_version'], + }) + assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT' + + service.publish( + draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='publish-request', + ) + events = ShippingOrderSchemaAuditEvent.query.order_by(ShippingOrderSchemaAuditEvent.id).all() + assert [event.event_type for event in events][-3:] == ['draft_created', 'draft_saved', 'published'] + assert events[-2].request_id == 'save-request' + assert events[-2].before_snapshot_json != events[-2].after_snapshot_json + + +def test_order_schema_catalog_exposes_type_compatible_rules(app): + """管理端目录必须提供类型兼容矩阵,避免页面构造后端必然拒绝的规则。""" + with app.app_context(): + state = service.get_state() + + assert state['catalog']['type_normalizers']['integer'] == ['integer'] + assert state['catalog']['type_comparators']['date'] == ['date'] + assert state['catalog']['type_validators']['boolean'] == [] diff --git a/backend/tests/test_shipping_order_schema_diff.py b/backend/tests/test_shipping_order_schema_diff.py new file mode 100644 index 00000000..47ecd3d9 --- /dev/null +++ b/backend/tests/test_shipping_order_schema_diff.py @@ -0,0 +1,147 @@ +""" +backend/tests/test_shipping_order_schema_diff.py + +用途:验证订单 Schema 版本字段语义差异与审计时间线管理 API。 +依赖:纯 diff 引擎、Flask 管理 API、订单 Schema service。 +逻辑:覆盖稳定字段重命名、集合/顺序变更、版本过滤和管理员权限边界。 +""" + +from __future__ import annotations + +from app import db +from app.models import User +from app.services.shipping_notice.order_schema import service +from app.services.shipping_notice.order_schema.diff import compare_definitions +from tests.conftest import parse_api_data, parse_api_error + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造管理 API 测试使用的遗留 Header 身份。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +def _field(field_id: str, *, code: str = 'po_number', display_name: str = '采购订单号') -> dict: + """构造可发布的 Header 文本字段配置,便于聚焦版本差异断言。""" + return { + 'field_id': field_id, + 'display_name': display_name, + 'required': True, + 'aliases': ['PO', 'Order Number'], + 'normalizer_key': 'trim', + 'validator_keys': ['non_empty'], + 'enum_options': [], + 'evidence_policy': { + 'required': True, + 'source_precedence': ['attachment_table', 'dify_llm'], + 'conflict_policy': 'block', + 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'normalized_text', + 'extraction_instruction': '读取订单号', + # field_code is supplied by the service from the stable field catalog. + 'field_code': code, + } + + +def test_compare_definitions_distinguishes_rename_set_and_order_changes(): + """相同 field_id 的系统标识改名应为修改,集合项与顺序均应可审计。""" + before = {'fields': [ + { + **_field('field-1'), 'field_code': 'po_number', 'sequence': 1, + 'description': None, 'enabled': True, 'scope': 'header', 'value_type': 'string', + }, + {**_field('field-2'), 'sequence': 2, 'enabled': True, 'scope': 'header', 'value_type': 'string'}, + ]} + after = {'fields': [ + { + **_field('field-1', code='purchase_order', display_name='客户订单号'), + 'field_code': 'purchase_order', 'sequence': 2, 'description': '', 'enabled': False, + 'scope': 'header', 'value_type': 'string', 'aliases': ['Order Number', 'PO'], + 'evidence_policy': { + 'required': False, + 'source_precedence': ['dify_llm', 'attachment_table'], + 'conflict_policy': 'review', + 'allow_single_source': True, + }, + }, + {**_field('field-3'), 'sequence': 1, 'enabled': True, 'scope': 'header', 'value_type': 'string'}, + ]} + + result = compare_definitions(before, after) + + assert result['summary'] == {'added': 1, 'removed': 1, 'modified': 1, 'unchanged': 0} + renamed = next(item for item in result['fields'] if item['field_id'] == 'field-1') + assert renamed['change_type'] == 'modified' + assert next(item for item in renamed['changes'] if item['key'] == 'field_code') == { + 'key': 'field_code', 'kind': 'value', 'before': 'po_number', 'after': 'purchase_order', + } + aliases = next(item for item in renamed['changes'] if item['key'] == 'aliases') + assert aliases['added'] == [] and aliases['removed'] == [] and aliases['order_changed'] is True + sources = next(item for item in renamed['changes'] if item['key'] == 'evidence_policy.source_precedence') + assert sources['order_changed'] is True + + +def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client): + """差异和审计接口只对管理员开放,版本过滤返回指定版本的追加事件。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + db.session.add_all([ + User(id=1, username='schema-diff-admin', email='schema-diff-admin@example.com', role='admin', status='active'), + User(id=2, username='schema-diff-user', email='schema-diff-user@example.com', role='user', status='active'), + ]) + db.session.commit() + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1) + field = service.save_field({'field_code': 'po_number', 'scope': 'header', 'value_type': 'string'}, actor_id=1) + first_draft = service.create_draft({}, actor_id=1) + first_saved = service.save_draft(first_draft['id'], { + 'fields': [_field(field['id'])], 'expected_lock_version': first_draft['lock_version'], + }, actor_id=1) + first = service.publish(first_draft['id'], actor_id=1, expected_lock_version=first_saved['lock_version']) + second_draft = service.create_draft({'copy_from_version_id': first['id']}, actor_id=1) + service.save_field({ + 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', + }, actor_id=1, field_id=field['id']) + second = service.get_version_detail(second_draft['id']) + + forbidden = client.get( + f"/api/admin/shipping-order-schema/versions/{first['id']}/diff?against_version_id={second['id']}", + headers=_headers('schema-diff-user', 'user'), + ) + assert forbidden.status_code == 403 + assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN' + + forbidden_audit = client.get( + '/api/admin/shipping-order-schema/audit-events', headers=_headers('schema-diff-user', 'user'), + ) + assert forbidden_audit.status_code == 403 + assert parse_api_error(forbidden_audit.get_json())['code'] == 'AUTH.FORBIDDEN' + + diff_response = client.get( + f"/api/admin/shipping-order-schema/versions/{first['id']}/diff?against_version_id={second['id']}", + headers=_headers('schema-diff-admin', 'admin'), + ) + assert diff_response.status_code == 200 + diff = parse_api_data(diff_response.get_json()) + assert diff['summary']['modified'] == 1 + field_diff = diff['fields'][0] + assert field_diff['change_type'] == 'modified' + assert any(change['key'] == 'field_code' for change in field_diff['changes']) + + audit_response = client.get( + f"/api/admin/shipping-order-schema/audit-events?page=1&page_size=20&version_id={second['id']}", + headers=_headers('schema-diff-admin', 'admin'), + ) + assert audit_response.status_code == 200 + audit = parse_api_data(audit_response.get_json()) + assert audit['total'] >= 2 + assert all(item['version']['id'] == second['id'] for item in audit['items']) + assert all('before_snapshot_json' not in item for item in audit['items']) + + paged_audit = client.get( + '/api/admin/shipping-order-schema/audit-events?page=1&page_size=1', + headers=_headers('schema-diff-admin', 'admin'), + ) + assert paged_audit.status_code == 200 + page = parse_api_data(paged_audit.get_json()) + assert page['page'] == 1 and page['page_size'] == 1 and len(page['items']) == 1 diff --git a/backend/tests/test_shipping_order_schema_enabled_migration.py b/backend/tests/test_shipping_order_schema_enabled_migration.py new file mode 100644 index 00000000..420307a5 --- /dev/null +++ b/backend/tests/test_shipping_order_schema_enabled_migration.py @@ -0,0 +1,55 @@ +""" +backend/tests/test_shipping_order_schema_enabled_migration.py + +用途:隔离验证订单 Schema 版本字段 enabled 迁移可安全往返。 +依赖:Alembic Operations、SQLAlchemy 内存数据库、enabled 增量迁移。 +逻辑:创建迁移前最小表,验证现有行回填为 true,并确认 downgrade 可移除新增列。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _load_migration(): + """从文件加载 enabled 增量迁移模块。""" + path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'f61b7c8d9e0a_add_schema_version_field_enabled.py' + spec = importlib.util.spec_from_file_location('shipping_order_schema_enabled_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _columns(connection) -> set[str]: + """返回版本字段表的列名集合。""" + return {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_schema_version_fields')} + + +def test_shipping_order_schema_enabled_migration_round_trip(): + """迁移应把历史配置视为已纳入,并支持完整回滚。""" + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + connection.execute(sa.text( + 'CREATE TABLE shipping_order_schema_version_fields ' + '(id INTEGER PRIMARY KEY, schema_version_id INTEGER NOT NULL, field_id VARCHAR(36) NOT NULL)' + )) + connection.execute(sa.text( + "INSERT INTO shipping_order_schema_version_fields (id, schema_version_id, field_id) VALUES (1, 1, 'field-1')" + )) + migration = _load_migration() + migration.op = Operations(MigrationContext.configure(connection)) + + migration.upgrade() + assert 'enabled' in _columns(connection) + assert connection.execute(sa.text( + 'SELECT enabled FROM shipping_order_schema_version_fields WHERE id = 1' + )).scalar_one() in (True, 1) + + migration.downgrade() + assert 'enabled' not in _columns(connection) diff --git a/backend/tests/test_shipping_order_schema_migration.py b/backend/tests/test_shipping_order_schema_migration.py new file mode 100644 index 00000000..62afbbae --- /dev/null +++ b/backend/tests/test_shipping_order_schema_migration.py @@ -0,0 +1,73 @@ +""" +backend/tests/test_shipping_order_schema_migration.py + +用途:隔离验证订单 Schema 迁移在 SQLite 上可 upgrade/downgrade。 +依赖:Alembic Operations、SQLAlchemy 内存数据库、阶段 1 迁移模块。 +逻辑:先创建上一版本所需最小依赖表,再直接执行本迁移,断言新增表和 Task 引用可完整往返。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _load_migration(): + """从文件加载数字开头的 Alembic 迁移模块。""" + path = Path(__file__).parents[1] / 'migrations' / 'versions' / '9b0c1d2e3f4a_add_shipping_order_schema.py' + spec = importlib.util.spec_from_file_location('shipping_order_schema_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _create_baseline(connection) -> None: + """创建阶段 1 迁移所需的上一版本最小外键目标表。""" + 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_documents', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + metadata.create_all(connection) + + +def _table_names(connection) -> set[str]: + """返回当前连接可见的业务表集合。""" + return set(sa.inspect(connection).get_table_names()) + + +def _task_columns(connection) -> set[str]: + """返回 shipping_tasks 当前列名集合。""" + return {item['name'] for item in sa.inspect(connection).get_columns('shipping_tasks')} + + +def test_shipping_order_schema_migration_round_trip(): + """本阶段迁移必须能新增并完整移除动态订单结构。""" + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + _create_baseline(connection) + context = MigrationContext.configure(connection) + migration = _load_migration() + migration.op = Operations(context) + + # 关键断言:upgrade 创建全部核心表和 Task 当前解析引用。 + migration.upgrade() + tables = _table_names(connection) + assert { + 'shipping_order_schemas', 'shipping_order_fields', 'shipping_order_schema_versions', + 'shipping_order_extractions', 'shipping_order_field_observations', + 'shipping_order_field_decisions', 'shipping_order_field_values', + }.issubset(tables) + assert 'current_order_extraction_id' in _task_columns(connection) + + # 回滚必须只移除本阶段对象,保留上一版本业务表。 + migration.downgrade() + tables = _table_names(connection) + assert 'shipping_order_schemas' not in tables + assert 'shipping_tasks' in tables + assert 'current_order_extraction_id' not in _task_columns(connection) diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py new file mode 100644 index 00000000..33200a83 --- /dev/null +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -0,0 +1,144 @@ +""" +backend/tests/test_shipping_order_schema_runtime.py + +用途:验证已发布订单 Schema 编译、EML/PDF 动态字段交叉验证和类型化持久化。 +依赖:order_schema service/runtime、ShippingNoticeDocument、动态订单模型。 +逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影。 +""" + +from __future__ import annotations + +from app import db +from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, ShippingOrderFieldValue, User +from app.services.shipping_notice.order_schema import service +from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version + + +def _config(field_id: str, name: str, *, value_type: str) -> dict: + """构造运行期测试使用的必填行字段配置。""" + return { + 'field_id': field_id, + 'display_name': name, + 'required': True, + 'aliases': [], + 'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim', + 'validator_keys': ['positive_decimal'] if value_type == 'decimal' else ['non_empty'], + 'enum_options': [], + 'evidence_policy': { + 'required': True, + 'source_precedence': ['attachment_text', 'email_body_text', 'backend_table', 'dify_llm'], + 'conflict_policy': 'block', + 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text', + } + + +def _save_and_publish(draft: dict, fields: list[dict]) -> dict: + """按乐观锁契约保存并发布运行时测试使用的 Schema。""" + saved = service.save_draft(draft['id'], { + 'fields': fields, 'expected_lock_version': draft['lock_version'], + }) + return service.publish( + draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], + ) + + +def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]: + """创建同一 Intake 下的邮件正文和 PDF Document,供跨文档证据验证。""" + user = User(username='dynamic-runtime', email='dynamic-runtime@example.com', password_hash='x') + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no='FA-DYNAMIC-RUNTIME', owner_user_id=user.id, original_filename='order.eml', + storage_provider='minio', storage_bucket='test', storage_key='dynamic/order.eml', + content_hash='dynamic-runtime-hash', file_size=100, mime_type='message/rfc822', + upload_status='ready', lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingNoticeIntake( + intake_no='SNI-DYNAMIC-RUNTIME', asset_id=asset.id, user_id=user.id, + purpose='shipping_notice', parse_status='parsed', parser_version='v6', + ) + db.session.add(intake) + db.session.flush() + body = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='body', attachment_key='body', + filename='body.txt', content_hash='dynamic-body', classification='order_notice', + parse_status='parsed', extracted_text='Please ship PART-100 quantity 10.', + ) + pdf = ShippingNoticeDocument( + intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='order.pdf', + filename='order.pdf', content_hash='dynamic-pdf', classification='order_notice', + parse_status='parsed', extracted_text='Part Number PART-100 Qty 10', + ) + db.session.add_all([body, pdf]) + db.session.flush() + return int(intake.id), [body, pdf], int(user.id) + + +def test_dynamic_schema_contract_and_cross_document_persistence(app): + """同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [ + _config(part['id'], '内部料号', value_type='string'), + _config(qty['id'], '数量', value_type='decimal'), + ]) + intake_id, documents, actor_id = _seed_documents() + contract = dify_contract(published_version()) + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [ + {'field_id': part['id'], 'observations': [ + {'value': 'PART-100', 'document_id': documents[0].id, 'quote': 'PART-100', 'confidence': 0.9}, + {'value': 'PART-100', 'document_id': documents[1].id, 'quote': 'PART-100', 'confidence': 0.9}, + ]}, + {'field_id': qty['id'], 'observations': [ + {'value': 10, 'document_id': documents[1].id, 'quote': 'Qty 10', 'confidence': 0.9}, + ]}, + ]}], + }, + intake_id=intake_id, snapshot_hash='b' * 64, documents=documents, actor_id=actor_id, + ) + + assert contract['fields'][0]['field_id'] in {part['id'], qty['id']} + assert result['blocked_fields'] == [] + assert result['lines'] == [{'part_number': 'PART-100', 'qty': '10'}] + assert result['extraction'].input_snapshot_json['documents'][0]['extracted_text'] == 'Please ship PART-100 quantity 10.' + assert any(item['status'] == 'corroborated' for item in result['decisions']) + assert len(result['decisions']) == 2 + assert ShippingOrderFieldValue.query.filter_by(extraction_id=result['extraction'].id).count() == 2 + + +def test_dynamic_schema_blocks_conflicting_documents(app): + """EML 与 PDF 对同一字段给出不同可信值时必须保留 Observation 并阻断自动接受。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(part['id'], '内部料号', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + documents[0].extracted_text = 'Please ship PART-200.' + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [], + 'lines': [{'fields': [{'field_id': part['id'], 'observations': [ + {'value': 'PART-200', 'document_id': documents[0].id, 'quote': 'PART-200'}, + {'value': 'PART-100', 'document_id': documents[1].id, 'quote': 'PART-100'}, + ]}]}], + }, + intake_id=intake_id, snapshot_hash='c' * 64, documents=documents, actor_id=actor_id, + ) + + assert result['blocked_fields'] == ['part_number'] + assert result['decisions'][0]['status'] == 'blocked' + assert len(result['observations']) == 2 diff --git a/backend/tests/test_shipping_order_schema_runtime_audit.py b/backend/tests/test_shipping_order_schema_runtime_audit.py new file mode 100644 index 00000000..070b3db8 --- /dev/null +++ b/backend/tests/test_shipping_order_schema_runtime_audit.py @@ -0,0 +1,189 @@ +""" +backend/tests/test_shipping_order_schema_runtime_audit.py + +用途:验证订单 Schema 版本使用统计、解析审计详情和历史版本复制草稿。 +依赖:订单 Schema service、动态订单审计模型、Flask 管理 API。 +逻辑:直接构造已锁定版本和解析裁决,断言历史展示只读取快照且管理员权限、分页和复制边界正确。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from app import db +from app.models import ( + ShippingOrderExtraction, + ShippingOrderFieldDecision, + ShippingOrderFieldObservation, + ShippingOrderFieldValue, + ShippingOrderSchemaVersion, + User, +) +from app.services.shipping_notice.order_schema import service +from tests.conftest import parse_api_data, parse_api_error + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造管理 API 使用的测试身份 Header。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +def _config(field_id: str, *, name: str = '采购订单号') -> dict: + """构造可发布的 Header 文本字段版本规则。""" + return { + 'field_id': field_id, + 'display_name': name, + 'required': True, + 'aliases': ['PO'], + 'normalizer_key': 'trim', + 'validator_keys': ['non_empty'], + 'enum_options': [], + 'evidence_policy': { + 'required': True, + 'source_precedence': ['attachment_text'], + 'conflict_policy': 'block', + 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'normalized_text', + 'extraction_instruction': '读取采购订单号', + } + + +def _publish(field_id: str, *, name: str, source_version_id: int | None = None) -> dict: + """创建、保存并发布版本,返回不可变版本快照。""" + draft = service.create_draft( + {'copy_from_version_id': source_version_id} if source_version_id else {}, actor_id=1, + ) + saved = service.save_draft(draft['id'], { + 'fields': [_config(field_id, name=name)], 'expected_lock_version': draft['lock_version'], + }, actor_id=1) + return service.publish(draft['id'], actor_id=1, expected_lock_version=saved['lock_version']) + + +def _persist_extraction(version: dict, field_id: str, *, status: str) -> int: + """构造一条带 Observation/Decision/Value 的已锁定运行审计记录。""" + extraction = ShippingOrderExtraction( + schema_version_id=version['id'], input_snapshot_hash=f"{'a' if status == 'accepted' else 'b' * 64}", + input_snapshot_json={'snapshot_hash': 'a' * 64, 'documents': [{'id': 101, 'extracted_text': 'PO-001'}]}, + status=status, + raw_llm_output_json={'header_fields': [{'field_id': field_id, 'value': 'PO-001'}]}, + normalized_result_json={'header': {'po_number': 'PO-001'}, 'lines': []}, + validation_result_json={'blocked_fields': [] if status == 'accepted' else ['po_number']}, + created_at=datetime.utcnow() - timedelta(minutes=1 if status == 'accepted' else 0), + ) + db.session.add(extraction) + db.session.flush() + observation = ShippingOrderFieldObservation( + extraction_id=extraction.id, field_id=field_id, source_type='attachment_text', + extractor='dify_dynamic_schema', raw_value_json='PO-001', normalized_value_json='PO-001', + evidence_quote='PO-001', confidence='0.9000', evidence_verified=True, + ) + db.session.add(observation) + db.session.flush() + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, field_id=field_id, decision_status='accepted', + selected_observation_id=observation.id, supporting_observation_ids_json=[observation.id], + resolved_value_json='PO-001', + ) + db.session.add(decision) + db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, field_id=field_id, decision_id=decision.id, value_text='PO-001', + value_json='PO-001', + )) + db.session.commit() + return int(extraction.id) + + +def test_version_usage_and_runtime_audit_read_locked_snapshots(app, client): + """使用统计只聚合目标版本,解析详情保留输入、LLM、裁决、证据和冻结字段名称。""" + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + db.session.add_all([ + User(id=1, username='schema-audit-admin', email='schema-audit-admin@example.com', role='admin', status='active'), + User(id=2, username='schema-audit-user', email='schema-audit-user@example.com', role='user', status='active'), + ]) + db.session.commit() + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1) + field = service.save_field({'field_code': 'po_number', 'scope': 'header', 'value_type': 'string'}, actor_id=1) + first = _publish(field['id'], name='采购订单号') + second = _publish(field['id'], name='客户订单号', source_version_id=first['id']) + extraction_id = _persist_extraction(first, field['id'], status='accepted') + _persist_extraction(second, field['id'], status='needs_review') + service.save_field({ + 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', + }, actor_id=1, field_id=field['id']) + + forbidden_usage = client.get( + f"/api/admin/shipping-order-schema/versions/{first['id']}/usage", headers=_headers('schema-audit-user', 'user'), + ) + assert forbidden_usage.status_code == 403 + assert parse_api_error(forbidden_usage.get_json())['code'] == 'AUTH.FORBIDDEN' + + usage_response = client.get( + f"/api/admin/shipping-order-schema/versions/{first['id']}/usage?page=1&page_size=1", + headers=_headers('schema-audit-admin', 'admin'), + ) + assert usage_response.status_code == 200 + usage = parse_api_data(usage_response.get_json()) + assert usage['summary']['total'] == 1 + assert usage['summary']['status_counts'] == {'accepted': 1} + assert usage['page'] == 1 and usage['page_size'] == 1 and usage['items'][0]['id'] == extraction_id + + forbidden_audit = client.get( + f"/api/admin/shipping-order-schema/order-extractions/{extraction_id}", headers=_headers('schema-audit-user', 'user'), + ) + assert forbidden_audit.status_code == 403 + + audit_response = client.get( + f"/api/admin/shipping-order-schema/order-extractions/{extraction_id}", headers=_headers('schema-audit-admin', 'admin'), + ) + assert audit_response.status_code == 200 + audit = parse_api_data(audit_response.get_json()) + assert audit['schema_version']['id'] == first['id'] + assert audit['input_snapshot']['documents'][0]['extracted_text'] == 'PO-001' + assert audit['input_snapshot']['snapshot_available'] is True + assert audit['raw_llm_output']['header_fields'][0]['value'] == 'PO-001' + assert audit['observations'][0]['evidence_quote'] == 'PO-001' + assert audit['decisions'][0]['decision_status'] == 'accepted' + assert audit['field_values'][0]['value'] == 'PO-001' + assert audit['decisions'][0]['field_code'] == 'po_number' + + +def test_only_immutable_version_can_be_copied_to_new_draft(app): + """历史发布/退役版本可复制为独立草稿,草稿不能作为草稿来源以避免链式可变引用。""" + with app.app_context(): + db.session.add(User(id=1, username='schema-copy-admin', email='schema-copy-admin@example.com', role='admin', status='active')) + db.session.commit() + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=1) + field = service.save_field({'field_code': 'po_number', 'scope': 'header', 'value_type': 'string'}, actor_id=1) + published = _publish(field['id'], name='采购订单号') + copied = service.create_draft({'copy_from_version_id': published['id'], 'change_note': '回溯复制'}, actor_id=1) + assert copied['status'] == 'draft' + assert copied['source_version_id'] == published['id'] + assert copied['definition']['fields'][0]['display_name'] == '采购订单号' + + service.delete_draft(copied['id'], actor_id=1) + open_draft = service.create_draft({}, actor_id=1) + try: + service.create_draft({'copy_from_version_id': open_draft['id']}, actor_id=1) + except Exception as exc: + assert getattr(exc, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID' + else: + raise AssertionError('Draft versions must not be valid copy sources') + + service.delete_draft(open_draft['id'], actor_id=1) + try: + service.create_draft({'copy_from_version_id': 'not-a-version'}, actor_id=1) + except Exception as exc: + assert getattr(exc, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID' + else: + raise AssertionError('Malformed copy sources must be rejected instead of creating a blank draft') + + try: + service.create_draft({'copy_from_version_id': 999999}, actor_id=1) + except Exception as exc: + assert getattr(exc, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID' + else: + raise AssertionError('Unknown copy sources must be rejected instead of creating a blank draft') diff --git a/backend/tests/test_shipping_order_schema_runtime_audit_migration.py b/backend/tests/test_shipping_order_schema_runtime_audit_migration.py new file mode 100644 index 00000000..8e8b55df --- /dev/null +++ b/backend/tests/test_shipping_order_schema_runtime_audit_migration.py @@ -0,0 +1,49 @@ +"""验证订单解析运行审计快照与版本使用索引迁移可往返执行。""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _load_migration(): + """从文件加载阶段四迁移模块。""" + path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'f99e4f5a6b7c_add_shipping_order_extraction_audit_snapshot.py' + spec = importlib.util.spec_from_file_location('shipping_order_schema_runtime_audit_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_runtime_audit_migration_round_trip(): + """迁移新增输入快照列和复合索引,降级必须完整移除二者。""" + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + sa.MetaData().create_all(connection) + metadata = sa.MetaData() + sa.Table( + 'shipping_order_extractions', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_version_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + ) + metadata.create_all(connection) + migration = _load_migration() + migration.op = Operations(MigrationContext.configure(connection)) + migration.upgrade() + inspector = sa.inspect(connection) + assert 'input_snapshot_json' in {item['name'] for item in inspector.get_columns('shipping_order_extractions')} + assert 'ix_shipping_order_extractions_schema_version_created' in { + item['name'] for item in inspector.get_indexes('shipping_order_extractions') + } + migration.downgrade() + inspector = sa.inspect(connection) + assert 'input_snapshot_json' not in {item['name'] for item in inspector.get_columns('shipping_order_extractions')} + assert 'ix_shipping_order_extractions_schema_version_created' not in { + item['name'] for item in inspector.get_indexes('shipping_order_extractions') + } diff --git a/backend/tests/test_shipping_order_schema_version_governance_migration.py b/backend/tests/test_shipping_order_schema_version_governance_migration.py new file mode 100644 index 00000000..9c62bafb --- /dev/null +++ b/backend/tests/test_shipping_order_schema_version_governance_migration.py @@ -0,0 +1,97 @@ +""" +backend/tests/test_shipping_order_schema_version_governance_migration.py + +用途:验证订单 Schema 单一版本定义与审计事件迁移在 SQLite 可往返执行。 +依赖:Alembic Operations、SQLAlchemy 内存数据库、阶段一版本治理迁移。 +逻辑:构造旧版草稿/发布版本及字段关联行;升级后仅保留发布版本并建立审计结构,回滚后恢复旧关联表。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _load_migration(): + """从文件加载单一版本定义迁移模块。""" + path = Path(__file__).parents[1] / 'migrations' / 'versions' / 'f96b1c2d3e4f_unify_shipping_order_schema_versions.py' + spec = importlib.util.spec_from_file_location('shipping_order_schema_version_governance_migration', path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _create_baseline(connection) -> None: + """创建迁移前所需最小表和一条草稿/发布版本数据。""" + metadata = sa.MetaData() + users = sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + schemas = sa.Table('shipping_order_schemas', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + versions = sa.Table( + 'shipping_order_schema_versions', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_id', sa.Integer(), sa.ForeignKey('shipping_order_schemas.id'), nullable=False), + sa.Column('status', sa.String(16), nullable=False), + ) + fields = sa.Table('shipping_order_fields', metadata, sa.Column('id', sa.String(36), primary_key=True)) + version_fields = sa.Table( + 'shipping_order_schema_version_fields', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False), + sa.Column('field_id', sa.String(36), sa.ForeignKey('shipping_order_fields.id'), nullable=False), + ) + metadata.create_all(connection) + connection.execute(users.insert(), [{'id': 1}]) + connection.execute(schemas.insert(), [{'id': 1}]) + connection.execute(versions.insert(), [ + {'id': 1, 'schema_id': 1, 'status': 'draft'}, + {'id': 2, 'schema_id': 1, 'status': 'published'}, + ]) + connection.execute(fields.insert(), [{'id': 'field-1'}]) + connection.execute(version_fields.insert(), [ + {'id': 1, 'schema_version_id': 1, 'field_id': 'field-1'}, + {'id': 2, 'schema_version_id': 2, 'field_id': 'field-1'}, + ]) + + +def _table_names(connection) -> set[str]: + """返回连接中当前可见的表集合。""" + return set(sa.inspect(connection).get_table_names()) + + +def _columns(connection, table_name: str) -> set[str]: + """返回指定表的列名集合。""" + return {item['name'] for item in sa.inspect(connection).get_columns(table_name)} + + +def test_shipping_order_schema_version_governance_migration_round_trip(): + """升级清理旧草稿子记录并建立审计表,回滚恢复旧版本字段表。""" + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + _create_baseline(connection) + migration = _load_migration() + migration.op = Operations(MigrationContext.configure(connection)) + + migration.upgrade() + assert 'shipping_order_schema_version_fields' not in _table_names(connection) + assert 'shipping_order_schema_audit_events' in _table_names(connection) + assert {'lock_version', 'source_version_id', 'retired_at'}.issubset( + _columns(connection, 'shipping_order_schema_versions') + ) + assert connection.execute(sa.text( + 'SELECT COUNT(*) FROM shipping_order_schema_versions WHERE status = \'draft\'' + )).scalar_one() == 0 + assert connection.execute(sa.text( + 'SELECT COUNT(*) FROM shipping_order_schema_versions WHERE status = \'published\'' + )).scalar_one() == 1 + + migration.downgrade() + assert 'shipping_order_schema_version_fields' in _table_names(connection) + assert 'shipping_order_schema_audit_events' not in _table_names(connection) + assert not {'lock_version', 'source_version_id', 'retired_at'} & _columns( + connection, 'shipping_order_schema_versions' + ) diff --git a/backend/tests/test_shipping_template_migrations.py b/backend/tests/test_shipping_template_migrations.py new file mode 100644 index 00000000..27d6a9d7 --- /dev/null +++ b/backend/tests/test_shipping_template_migrations.py @@ -0,0 +1,78 @@ +""" +用途:隔离验证库存解析 Profile 与发货模板/Artifact 迁移可连续 upgrade/downgrade。 +依赖:Alembic Operations、SQLAlchemy SQLite、阶段四和阶段五迁移模块。 +逻辑:创建真实前序所需最小表,连续执行两阶段迁移并逆序回滚,检查表、列和索引生命周期。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + + +def _load(filename: str, module_name: str): + """加载数字开头的迁移模块。""" + path = Path(__file__).parents[1] / 'migrations' / 'versions' / filename + spec = importlib.util.spec_from_file_location(module_name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _baseline(connection) -> None: + """创建两个迁移引用的最小前序表及外键目标。""" + metadata = sa.MetaData() + for name in ( + 'users', 'shipping_tasks', 'shipping_batches', 'shipping_order_schema_versions', + 'shipping_order_extractions', 'shipping_inventory_files', + ): + sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_inventory_sources', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('source_code', sa.String(64), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.true()), + ) + metadata.create_all(connection) + + +def _columns(connection, table: str) -> set[str]: + return {item['name'] for item in sa.inspect(connection).get_columns(table)} + + +def test_inventory_profile_and_excel_template_migrations_round_trip(): + """阶段四、五迁移必须可连续升级并逆序完整回滚。""" + engine = sa.create_engine('sqlite:///:memory:') + with engine.begin() as connection: + _baseline(connection) + context = MigrationContext.configure(connection) + operations = Operations(context) + parsing = _load('b17e3d4c5a60_inventory_parsing_profiles.py', 'inventory_parsing_profile_migration') + excel = _load('c27e3d4c5a61_shipping_excel_templates.py', 'shipping_excel_template_migration') + parsing.op = operations + excel.op = operations + + parsing.upgrade() + assert 'shipping_inventory_parsing_profiles' in sa.inspect(connection).get_table_names() + assert 'parsing_profile_id' in _columns(connection, 'shipping_inventory_sources') + + excel.upgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert {'shipping_excel_templates', 'shipping_export_artifacts'}.issubset(tables) + assert 'excel_template_id' in _columns(connection, 'shipping_inventory_sources') + + excel.downgrade() + tables = set(sa.inspect(connection).get_table_names()) + assert 'shipping_excel_templates' not in tables + assert 'shipping_export_artifacts' not in tables + assert 'excel_template_id' not in _columns(connection, 'shipping_inventory_sources') + assert 'parsing_profile_id' in _columns(connection, 'shipping_inventory_sources') + + parsing.downgrade() + assert 'shipping_inventory_parsing_profiles' not in sa.inspect(connection).get_table_names() + assert 'parsing_profile_id' not in _columns(connection, 'shipping_inventory_sources') diff --git a/backend/tests/test_temporary_inventory_session.py b/backend/tests/test_temporary_inventory_session.py new file mode 100644 index 00000000..02be9221 --- /dev/null +++ b/backend/tests/test_temporary_inventory_session.py @@ -0,0 +1,371 @@ +""" +tests/test_temporary_inventory_session.py + +用途:验证对话库存候选会话的身份隔离、通用表格结构门禁和生产链路隔离。 +依赖:临时库存会话服务、FileAsset、ChatSession、openpyxl。 +逻辑:用户明确声明库存文件后只做结构门禁;覆盖同一资产幂等、跨会话不可读和能力映射确认。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from io import BytesIO +from pathlib import Path + +import pytest +from openpyxl import Workbook + +from app import db +from app.core.errors import NotFoundError +from app.models import ( + Agent, + ChatSession, + FileAsset, + ShippingInventoryFile, + ShippingInventoryField, + ShippingTaskInventoryLink, + ShippingTemporaryInventorySession, + User, +) +from app.services.agent_runtime_context.builder import build_agent_runtime_context +from app.services.shipping_notice.inventory_temporary_session import ( + create_temporary_inventory_session, + confirm_temporary_inventory_use, + create_parsing_profile_draft_from_temporary_session, + get_temporary_inventory_session, + submit_temporary_inventory_mapping_suggestion, +) + + +def _xlsx_bytes(headers: list[str], row: list[object]) -> bytes: + """生成最小 Excel 文件,覆盖后端结构分析而不依赖真实库存数据。""" + stream = BytesIO() + workbook = Workbook() + worksheet = workbook.active + worksheet.append(headers) + worksheet.append(row) + workbook.save(stream) + workbook.close() + return stream.getvalue() + + +def _seed_context(*, suffix: str = 'owner') -> tuple[User, User, ChatSession, Agent, FileAsset]: + """创建两个用户、货代 Agent、会话和私有文件资产,供访问隔离断言使用。""" + owner = User(username=f'temp-{suffix}', email=f'temp-{suffix}@example.com', role='user', status='active') + other = User(username=f'temp-other-{suffix}', email=f'temp-other-{suffix}@example.com', role='user', status='active') + agent = Agent(name=f'Temporary Inventory {suffix}', agent_code='shipping_notice', runtime_provider='dify') + db.session.add_all([owner, other, agent]) + db.session.flush() + chat_session = ChatSession(session_id=f'chat-temp-{suffix}', user_id=owner.id, agent_id=agent.id, title='temporary') + asset = FileAsset( + asset_no=f'FAS-TEMP-{suffix}'.upper(), owner_user_id=owner.id, original_filename='inventory.xlsx', + storage_provider='minio', storage_bucket='test', storage_key=f'temporary/{suffix}/inventory.xlsx', + content_hash='a' * 64, file_size=10, extension='xlsx', upload_status='ready', + lifecycle_status='temporary', reference_count=0, expires_at=datetime.utcnow() + timedelta(hours=1), + ) + db.session.add_all([chat_session, asset]) + db.session.commit() + return owner, other, chat_session, agent, asset + + +def _runtime_context(session: ChatSession) -> dict: + """构造与聊天入口一致的可信 runtime context,不伪造用户身份字段。""" + return build_agent_runtime_context( + agent_code='shipping_notice', scope='chat_turn', session_id=session.session_id, + refs={'capability': 'temporary_inventory'}, + ) + + +def test_inventory_candidate_is_idempotent_and_never_creates_production_snapshot(app, monkeypatch, tmp_path): + """同一会话同一资产复用临时结果,且不创建生产库存文件或任务链接。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='candidate') + content = _xlsx_bytes(['Supplier Sku', 'Qty Available', 'Reservation ID'], ['PN-1', 9, 'RES-1']) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + + first = create_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no, + }) + second = create_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no, + }) + + # 关键断言:初检只保存临时结构审计,绝不写入正式库存快照或任务库存关联。 + assert first['status'] == 'awaiting_mapping_suggestion' + assert first['session_no'] == second['session_no'] + # 字段目录未与来源表头同名时不生成正式映射建议;分类只证明该文件具备库存最低特征。 + assert first['analysis']['suggested_mapping'] == {} + assert first['file_classification_status'] == 'inventory_candidate' + assert 'sample_values' not in first['analysis']['structure']['selected_columns'][0] + assert ShippingTemporaryInventorySession.query.count() == 1 + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 + + +def test_legacy_xls_enters_temporary_analysis_without_format_rejection(app, monkeypatch, tmp_path): + """对话临时库存必须直接分析旧 xls,不要求用户先转换为 xlsx 或 csv。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + template = Path(__file__).resolve().parents[1] / 'templates' / 'maintenance_record_history_template.xls' + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='legacy-xls') + asset.original_filename = 'legacy-inventory.xls' + asset.extension = 'xls' + asset.storage_key = 'temporary/legacy-xls/legacy-inventory.xls' + content = template.read_bytes() + asset.file_size = len(content) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', + lambda item: content, + ) + + result = create_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no, + }) + + # 关键断言:xls 已进入真实结构分析;是否属于库存仍由字段特征决定。 + assert result['analysis']['file_format'] == 'xls' + assert result['file_classification_status'] in {'inventory_candidate', 'not_inventory'} + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 + + +def test_user_declared_inventory_with_custom_headers_enters_mapping_candidate(app, monkeypatch, tmp_path): + """任意业务表头只要结构有效即可进入候选,后端不得依赖固定库存字段词典拒绝。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='noninventory') + content = _xlsx_bytes(['PO Number', 'Customer', 'Unit Price'], ['PO-1', 'Customer A', 100]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + + result = create_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no, + }) + + assert result['status'] == 'awaiting_mapping_suggestion' + assert result['file_classification_status'] == 'inventory_candidate' + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 + + +def test_table_without_data_rows_is_rejected(app, monkeypatch, tmp_path): + """只有表头而没有数据行的文件不能进入字段候选确认。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='empty-table') + content = _xlsx_bytes(['物料', '可承诺数'], ['', '']) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + + result = create_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no, + }) + + assert result['status'] == 'rejected' + assert result['file_classification_status'] == 'not_inventory' + + +def test_temporary_session_cannot_be_read_from_another_chat_session(app, monkeypatch, tmp_path): + """临时会话必须同时绑定用户与聊天会话,避免猜中编号后跨会话读取。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + owner, other, chat_session, agent, asset = _seed_context(suffix='isolation') + content = _xlsx_bytes(['Supplier Sku', 'Qty Available'], ['PN-1', 9]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + created = create_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(chat_session), 'asset_no': asset.asset_no, + }) + other_session = ChatSession(session_id='chat-temp-other-isolation', user_id=other.id, agent_id=agent.id, title='other') + db.session.add(other_session) + db.session.commit() + + with pytest.raises(NotFoundError) as exc_info: + get_temporary_inventory_session({ + 'agent_runtime_context': _runtime_context(other_session), + 'temporary_session_no': created['session_no'], + }) + + assert exc_info.value.code == 'SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND' + + +def test_mapping_suggestion_only_accepts_catalog_fields_and_real_headers(app, monkeypatch, tmp_path): + """Dify 映射建议只能引用返回的字段目录和真实表头,且保存后仍不是正式库存。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='mapping') + content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + context = _runtime_context(chat_session) + created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no}) + field_ids = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + ).all() + } + + saved = submit_temporary_inventory_mapping_suggestion({ + 'agent_runtime_context': context, + 'temporary_session_no': created['session_no'], + 'field_mapping': { + field_ids['part_number']: 'Supplier Sku', + field_ids['reservation_id']: 'Reservation ID', + field_ids['available_qty']: 'Qty Available', + }, + }) + + assert saved['status'] == 'awaiting_mapping_confirmation' + assert saved['mapping_suggestion']['origin'] == 'dify_candidate' + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 + + +def test_mapping_confirmation_session_is_idempotent_for_the_same_asset(app, monkeypatch, tmp_path): + """映射建议已保存时重试创建必须复用会话,避免产生多条待确认记录。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='mapping-idempotent') + content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + context = _runtime_context(chat_session) + created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no}) + field_ids = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + ).all() + } + submit_temporary_inventory_mapping_suggestion({ + 'agent_runtime_context': context, 'temporary_session_no': created['session_no'], + 'field_mapping': { + field_ids['part_number']: 'Supplier Sku', + field_ids['reservation_id']: 'Reservation ID', + field_ids['available_qty']: 'Qty Available', + }, + }) + + retried = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no}) + + assert retried['session_no'] == created['session_no'] + assert retried['status'] == 'awaiting_mapping_confirmation' + assert ShippingTemporaryInventorySession.query.count() == 1 + + +def test_confirmed_temporary_use_passes_quality_without_creating_production_inventory(app, monkeypatch, tmp_path): + """用户确认后只锁定临时质量审计,不能写入正式快照、任务关联或库存行投影。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='confirm') + content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + context = _runtime_context(chat_session) + created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no}) + field_ids = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + ).all() + } + submit_temporary_inventory_mapping_suggestion({ + 'agent_runtime_context': context, 'temporary_session_no': created['session_no'], + 'field_mapping': { + field_ids['part_number']: 'Supplier Sku', + field_ids['reservation_id']: 'Reservation ID', + field_ids['available_qty']: 'Qty Available', + }, + }) + + confirmed = confirm_temporary_inventory_use({ + 'agent_runtime_context': context, 'temporary_session_no': created['session_no'], + }) + + assert confirmed['status'] == 'confirmed_for_temporary_use' + assert confirmed['confirmed_usage']['usage_scope'] == 'conversation' + assert 'task_no' not in confirmed['confirmed_usage'] + assert confirmed['confirmed_usage']['quality']['passed'] is True + assert confirmed['confirmed_usage']['quality']['valid_line_count'] == 1 + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 + + +def test_temporary_confirmation_ignores_task_anchor_and_never_links_inventory(app, monkeypatch, tmp_path): + """临时库存确认即使收到 task_no 也保持对话隔离,不能形成任务语义或任务关联。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + _owner, _other, chat_session, _agent, asset = _seed_context(suffix='ignore-task') + content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + context = _runtime_context(chat_session) + created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no}) + field_ids = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + ).all() + } + submit_temporary_inventory_mapping_suggestion({ + 'agent_runtime_context': context, 'temporary_session_no': created['session_no'], + 'field_mapping': { + field_ids['part_number']: 'Supplier Sku', + field_ids['reservation_id']: 'Reservation ID', + field_ids['available_qty']: 'Qty Available', + }, + }) + + confirmed = confirm_temporary_inventory_use({ + 'agent_runtime_context': context, + 'temporary_session_no': created['session_no'], + 'task_no': 'SN-SHOULD-NOT-BIND', + }) + row = ShippingTemporaryInventorySession.query.filter_by(session_no=created['session_no']).one() + + assert confirmed['confirmed_usage']['usage_scope'] == 'conversation' + assert 'task_no' not in confirmed['confirmed_usage'] + assert row.task_id is None + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 + + +def test_confirmed_session_promotes_only_to_parsing_profile_draft(app, monkeypatch, tmp_path): + """管理员沉淀必须复用临时会话锁定映射,且结果只能是未发布解析方案草稿。""" + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') + with app.app_context(): + owner, _other, chat_session, _agent, asset = _seed_context(suffix='promote') + content = _xlsx_bytes(['Supplier Sku', 'Reservation ID', 'Qty Available'], ['PN-1', 'RES-1', 9]) + monkeypatch.setattr('app.services.shipping_notice.inventory_temporary_session.read_asset_bytes', lambda item: content) + context = _runtime_context(chat_session) + created = create_temporary_inventory_session({'agent_runtime_context': context, 'asset_no': asset.asset_no}) + field_ids = { + item.field_code: str(item.id) + for item in ShippingInventoryField.query.filter( + ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + ).all() + } + submit_temporary_inventory_mapping_suggestion({ + 'agent_runtime_context': context, 'temporary_session_no': created['session_no'], + 'field_mapping': { + field_ids['part_number']: 'Supplier Sku', + field_ids['reservation_id']: 'Reservation ID', + field_ids['available_qty']: 'Qty Available', + }, + }) + confirm_temporary_inventory_use({'agent_runtime_context': context, 'temporary_session_no': created['session_no']}) + + from app.services.shipping_notice.order_schema import service as order_schema_service + + # 匹配键必须引用当前订单字段 Schema 中的稳定字段身份。 + order_schema_service.initialize_schema({'display_name': '临时库存测试字段'}, actor_id=owner.id) + order_field = order_schema_service.save_field({ + 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', + }, actor_id=owner.id) + draft = create_parsing_profile_draft_from_temporary_session(created['session_no'], { + 'profile_code': 'TEMP_CONVERSATION', 'display_name': '对话库存草稿', + 'match_keys': [{'order_field_id': order_field['id'], 'inventory_field_id': field_ids['part_number']}], + 'field_mapping': {'forged': 'Forged Header'}, + }, actor_id=owner.id) + + assert draft['status'] == 'draft' + assert draft['definition']['field_mapping'][field_ids['part_number']] == 'Supplier Sku' + assert 'forged' not in draft['definition']['field_mapping'] + assert ShippingInventoryFile.query.count() == 0 + assert ShippingTaskInventoryLink.query.count() == 0 diff --git a/docs/convention/env_loading_priority.md b/docs/convention/env_loading_priority.md index 22d350f1..75dc803b 100644 --- a/docs/convention/env_loading_priority.md +++ b/docs/convention/env_loading_priority.md @@ -61,3 +61,11 @@ - 生产密钥不要放 `.env.shared`。 - 新增变量同步更新对应 env 文件和本文档。 - 继续清理对 `backend/.env` 的历史依赖。 + +## 7. Shipping Notice RPA 命名空间 + +- 后端业务参数:`SHIPPING_NOTICE_RPA_<配置项>`。 +- 后端与 Windows Worker 共享目录、共享 scope、哨兵:`SHIPPING_NOTICE_RPA_SHARED_<配置项>`。 +- Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`SHIPPING_NOTICE_RPA_WORKER_<配置项>`。 +- RPA Profile 凭据 Fernet 主密钥:`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。 +- 禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史变量仅作为迁移期 fallback;新名称优先,完成所有环境迁移后删除旧名称。 diff --git a/docs/convention/环境变量规则.md b/docs/convention/环境变量规则.md index 22d350f1..75dc803b 100644 --- a/docs/convention/环境变量规则.md +++ b/docs/convention/环境变量规则.md @@ -61,3 +61,11 @@ - 生产密钥不要放 `.env.shared`。 - 新增变量同步更新对应 env 文件和本文档。 - 继续清理对 `backend/.env` 的历史依赖。 + +## 7. Shipping Notice RPA 命名空间 + +- 后端业务参数:`SHIPPING_NOTICE_RPA_<配置项>`。 +- 后端与 Windows Worker 共享目录、共享 scope、哨兵:`SHIPPING_NOTICE_RPA_SHARED_<配置项>`。 +- Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`SHIPPING_NOTICE_RPA_WORKER_<配置项>`。 +- RPA Profile 凭据 Fernet 主密钥:`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。 +- 禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史变量仅作为迁移期 fallback;新名称优先,完成所有环境迁移后删除旧名称。 diff --git a/docs/demand.md b/docs/demand.md index 3658f1c4..bc8333c0 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -47,14 +47,16 @@ - **可靠性要求**:单次同步必须设置超时;超时或短时失败后,每隔 30 分钟自动重试 1 次,累计最多重试 3 次;若全部失败,继续保留上一版快照对外服务。 - **查询要求**:用户在 `固资管理` Agent 中发起查询时,优先查询本地快照;字段级条件优先匹配,`备注` 作为模糊检索补充;极少数无法覆盖的复杂场景可再回退实时 ERP 查询。 -### 3.x 货代发货通知库存源补充需求 +### 3.x 货代发货通知库存源与库存文件补充需求 -- **核心目标**:在订单解析阶段即确定库存查询来源(`source_code`),避免 RPA 抓错库存池;用户仅需确认来源编码,站点与仓库由系统配置生成。 -- **字段隔离**:订单行仅使用 `inventory_source_hint` 保存可选路由线索;库存连接器字段统一为 `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`、`connector_type`、`site_id`、`warehouse_id` 与任务一致。 +- **核心目标**:Inventory Source(`source_code`)是库存路由、库存文件归档和匹配的业务主键;订单解析先得到一个或多个候选 Source,再匹配已导出的有效库存文件,避免选择错误库存池。 +- **库存文件优先**:正常发货流程只消费同 Source、`ready` 且未过期的最新库存文件,绝不因库存缺失自动执行 RPA;缺失或过期时提示等待排程或由用户明确刷新。 +- **RPA 旁路**:RPA Profile 只用于定时库存导出、用户手动刷新和配置测试;排程以 `source_codes` 为目标,按 Profile 分组复用登录,但每个文件必须独立记录 Source。 +- **配置归属**:连接配置只保存登录地址、加密凭据和连接级登录配置;库存源必须持久化 `report_path_json`、`query_parameters_json`和 `match_aliases_json`。DBS 路径为业务组/业务项目/报表分组/报表名;参数支持单选、文本多值、列表多选。 +- **字段隔离**:订单行仅使用 `inventory_source_hint` 保存可选路由线索;`connector_type` 仅允许 `dbs` / `crane` 并用于 Driver 分发,不得复用 `ShippingTask.source_type`;不再使用 `site_id`。 +- **Warehouse**:固定 Source 直接使用配置 Warehouse;动态 Source(Crane)以 `reservation_id + part_number` 从库存行取得 Warehouse,不维护 Crane Warehouse 清单。Warehouse 未解析或冲突时不得生成 Excel。 +- **通用路由规则**:路由规则必须可配置、版本化和可解释,Reservation ID 仅为首批事实字段;规则只产生 Source 候选,不执行 RPA 或决定最终 Warehouse。 +- **外部系统仓库映射**:HXOPS 维护 `source + freight warehouse` 到外部系统仓库的多对一映射;当前仅提供后台维护和内部查询 Service,不开发 Tool API 或调拨逻辑。TOPGP 不存在组织编码时保存 `NULL`。 - 技术方案见 [docs/features/shipping-notice/inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 ### 3.x 货代客户身份与业务编号 @@ -66,9 +68,15 @@ - **客户身份来源**:邮件/文件解析结果仅作为客户候选线索,不能直接作为稳定客户身份;系统以 HXOPS 客户主数据中的稳定 `customer_id` 和人工维护的唯一 `customer_short_code` 为准。 - **识别与人工确认**:系统可使用已审核名称别名、完整发件人邮箱、非公共且独占的邮箱域名、模板指纹等证据生成候选;未匹配、多候选或证据冲突时进入 `customer_review`,客户未稳定前不得进入库存源判定、RPA、库存匹配、Excel 生成或货代上传。 - **修订规则**:同一业务单的任务修订版本继承原业务编号;`force_create` 创建新的业务单并申请新流水。业务编号生成后不得静默修改,客户实质更正须保留原号作废与替代关系。 -- **历史兼容**:历史任务允许没有客户主数据关联和业务编号,默认不补发历史业务编号;历史客户回填仅新增稳定客户关联,不覆盖原始解析字段。 +- **新任务完整性**:所有货代任务必须关联业务单;业务单未关联标准客户或客户未确认时,所有库存与履约副作用均须阻断,不提供历史任务回填入口。 - **期初导入**:客户主数据必须通过“上传暂存 → 标准化与预检 → 冲突处理 → 审核发布 → 对账”导入,禁止 Excel 直接写正式表;以 `source_system + legacy_customer_key` 保证幂等。 - **权限边界**:普通业务用户可选择已有客户或提交新客户申请;正式客户建档、简码维护、识别证据审核和期初导入仅允许管理员执行。 +- **删除资格**:永久删除只能面向未进入业务、编号、导入或识别审计链的误建客户;识别证据可随该客户级联删除。删除时管理员必须输入当前客户简码和删除原因;服务端锁定客户并重新统计引用。业务单、业务流水、外部来源键、导入结果、影子候选及人工真值任一存在时,必须阻断删除并改用停用或客户合并。 +- **客户合并**:重复客户须通过“源客户 → 启用目标客户”的受控归并处理;历史业务单、业务编号、流水、导入结果和影子审计保持源客户与快照不变,只有识别证据和外部来源键迁移至目标客户。源客户标记为 `merged` 并永久不可作为新任务、自动识别或人工真值的客户。 +- **自动确认质量门禁**:即使开启自动确认总开关,也只能对“当前强规则会唯一命中”的人工真值样本计算质量;有效样本数低于 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES`(默认 20)或准确率低于 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY`(默认 0.98)时,任务必须保持 `customer_review`,不得绑定客户或生成业务号。 +- **生命周期治理**:创建、编辑、启停、简码变更和识别证据创建/审核/停用/自动匹配授权必须记录客户快照、操作者、原因与前后差异;简码、状态和自动匹配授权变更必须填写原因,管理员可在客户主数据页面查询时间线和门禁状态。 +- **客户角色分离**:订单解析必须分别保存 Bill-to 账款客户和 Ship-to 送货对象的原文及证据;Bill-to 决定业务归属客户,Ship-to 指向客户主数据下的送货站点。客户简称只能由已确认 Bill-to 主数据派生,禁止由 LLM 提取或人工在订单模板中重复维护。 +- **确定性优先匹配**:存在来源系统和外部编码时必须优先精确匹配;否则回退标准名称和已审核别名。未命中、多候选或站点归属不合法时进入人工复核。 ### 3.x 货代发货通知建单防重复(第一阶段) @@ -85,6 +93,34 @@ - 订单识别终态必须区分新建任务、打开已有任务、待补充/冲突、非发货忽略和已建但缺流程字段,并在刷新或重新进入会话后仍可恢复。 - Dify 错误、网络超时或成功结束但未提交 `orders[]` 时,订单识别必须离开 `extracting` 并显示可重试的失败原因。 +### 3.x 唯一订单 Schema 与动态字段 + +- 所有 EML、PDF、Word 发货订单使用同一份当前已发布订单 Schema;文件类型只决定文本/OCR 技术解析器,不决定字段集合。 +- 订单字段的“字段名称(系统标识)”与“当前版本显示名称”在草稿中始终可编辑;“纳入当前版本”只控制字段是否进入本次发布契约和订单解析,不得作为名称编辑权限开关。未纳入字段的版本显示名称和规则仍需保存,后续重新纳入时继续使用。 +- 系统标识重命名不得改变稳定字段 ID;已发布历史版本继续保留发布时的系统标识和显示名称,确保解析记录与版本审计不被后续重命名污染。 +- 草稿保存和发布必须采用乐观锁:客户端提交当前 `lock_version`,版本被其他管理员更新后必须拒绝覆盖并提示刷新。版本创建、保存、发布、删除及字段目录变更必须形成只追加审计事件,包含操作者、请求 ID、前后快照和结构化变更摘要。 +- 草稿与发布版本必须使用同一份完整版本定义作为唯一真相;未纳入字段仍保存在版本快照供审计,但后端和 Dify 运行契约只消费已纳入字段。当前阶段不要求修改 Dify 画布,只需保持按后端 contract 原样回传。 +- 管理端必须提供版本历史入口:管理员可分页查看草稿、当前发布和退役版本的版本号、状态、创建/发布人、时间、变更说明和 checksum;选择任意版本后以严格只读快照展示字段和识别规则。历史链接须可通过业务版本号恢复,后续字段重命名不得污染历史展示。 + - 管理端必须支持将任意两个 Schema 版本做服务端字段级语义比较,并提供追加式配置审计时间线。比较以稳定 `field_id` 配对,必须区分新增、移除、修改、纳入状态、系统标识重命名、显示名、规则、集合项和字段顺序;不得由前端以名称猜测字段对应关系,也不得在历史视图中提供直接回滚。 + - 管理端必须能说明每个 Schema 版本实际被哪些订单解析使用,并进入任一解析的只读审计详情,查看锁定版本、冻结输入、LLM 原始结果、归一化/校验、字段 Observation/Decision/FieldValue 与原文证据。新解析必须冻结输入快照,历史版本的字段名称不得受当前目录改名影响;仅管理员可访问。 + - 管理员可从已发布或退役的历史版本复制为新草稿后再修改和发布;不得直接恢复、编辑或回滚历史版本,草稿不得作为复制来源。 +- 管理员可维护字段稳定 ID、`field_code`、名称、Header/Line 作用域、类型、别名、规范化、校验、证据和跨文档关联策略。 +- 字段首次发布后,稳定 ID、作用域和类型不可原地修改;`field_code` 可重命名并只影响后续草稿,历史发布快照保留旧值;识别规则变更须创建新的不可变 Schema 版本。 +- 订单 Schema 必须覆盖库存源路由、库存匹配和发货 Excel 所需的订单字段;下游配置引用稳定字段 ID,不引用显示名称。 +- 管理端必须使用后端字段目录和白名单提供结构化选择器,不要求业务管理员直接编辑 Profile/模板 JSON;发布新 Schema 版本时,若移除仍被路由、库存解析 Profile 或 Excel 模板引用的字段,必须阻断并要求先迁移下游配置。 +- 发货 Excel 模板必须独立版本化管理并由库存源绑定 published 版本;多个同结构库存源共享同一模板,不得在库存源中复制映射。模板发布后文件和映射不可变。 +- 库存站点允许先以禁用状态保存基础信息,逐步通过测试导出确认库存文件解析方案并绑定 published 发货模板;首次保存不要求手工选择解析方案。正式启用是独立门禁动作,必须完成连接、测试导出与解析验证、解析方案、发货模板和仓库映射;一旦启用,各项绑定必须齐全且有效。固定仓须维护该货代仓的精确映射或库存源默认映射;动态仓还须从测试文件识别仓库栏位并覆盖测试样例中的每个仓库。系统绝不根据名称相似度自动创建外部仓库映射。 +- 库存文件解析方案支持上传 `.xls` / `.xlsx` / `.csv` 样本;后端必须分析工作表、候选表头、真实列名、少量脱敏样例、类型与空值统计,并以结构化选择器供管理员确认。浏览器端不得作为发布依据,也不得要求管理员手输来源栏位。 +- 相同库存模板按文件结构及已发布方案实际使用的“库存匹配/库存数量”栏位确定性判断,不按文件名、库存数据内容或文件内容 hash 判断。完全一致可推荐复用已发布方案;仅新增无关栏位或非关键顺序变化时提示兼容差异;方案所需栏位缺失、重复或冲突不得复用。推荐方案必须由管理员确认,样本上传不得自动绑定库存站点。 +- 停用库存站点可以发起异步测试导出。测试文件仅用于连接、文件结构和解析验证,不得进入正式库存快照、订单库存匹配、发货 Excel 或正式导出记录;管理员确认已发布解析方案后才更新该停用站点的绑定。 +- 每次正式 RPA 导出在写入库存快照前都必须复核文件结构:完全一致正常入库;仅新增非关键栏位或顺序变化可入库并记录差异;格式、工作表、表头行、关键栏位或映射变化必须阻断入库和库存匹配。正式运行只能使用已发布解析方案的工作表、表头行和字段映射,不允许自动猜列兜底。 +- 正式库存运行优先消费已配置库存站点的 RPA 正式导出;对已有发货任务保留受控的任务级人工库存上传,但必须按任务已确认库存站点绑定的 published 解析方案执行结构漂移校验和确定性解析,成功后直接进入库存匹配,不再提供任务级猜列、字段对齐确认或 LLM 映射。普通用户不能把对话临时上传文件直接变为正式库存快照。用户可在货代对话上传 `.xls` / `.xlsx` / `.csv` 并明确声明其为库存文件;系统不得根据后缀猜测用途,后端只创建用户与会话隔离的临时分析会话。临时会话仅返回脱敏结构、受控映射建议和确认质量审计,不能匹配订单、发布方案、绑定库存站点、创建仓库映射或解除正式文件结构门禁;管理员可从已确认会话沉淀解析方案草稿。对于规则词典无法解释的陌生表头,Dify 只能给出候选含义,后端必须校验真实表头、字段目录、核心字段完整性和用户确认。 +- 库存字段目录初始为空,不得预置 AWS 料号、ODM 编号、仓库编码、批次号、库位或任何其他具体字段。管理员自行维护字段名称、说明、数据格式、用途和顺序;程序只控制“库存匹配、库存数量、仓库识别、一般业务信息”四种业务用途。解析方案的 `field_mapping` 和 `match_keys`、库存运行行数据以及发货模板均直接引用库存字段目录 ID,字段名称和内部编码不得参与业务判断。发布解析方案时至少映射一个库存匹配字段,且必须且只能映射一个库存数量字段;动态仓站点还必须且只能映射一个仓库识别字段。每次生成必须形成不可变 Artifact,锁定订单 Schema、Extraction、库存解析 Profile、库存快照和输入 checksum。 +- 模板原文件必须存放在平台私有 MinIO,不依赖某台后端实例的本地磁盘;上传时校验真实 xlsx、大小与 SHA-256,数据库提交失败须补偿删除对象。 +- 订单行与库存行必须按解析 Profile 的 `match_keys(order_field_id -> inventory_field_id)` 确定性关联;库存解析结果始终以库存字段目录 ID 为键,不得转换为固定字段名称后再判断。不得按 Excel 行序或数组下标配对;零命中、多命中且模板所需库存字段不一致时必须阻断导出。 +- 用户可按批次或显式勾选任务批量下载当前有效 Artifact;有效产物必须同时满足 `status=ready` 且仍是任务当前导出引用。ZIP 必须包含 manifest,逐票列明已包含、无产物、文件缺失或 checksum 不一致,不得因同名覆盖文件或允许越权混入。 +- Dify 仅消费后端编译的已发布字段契约并返回候选与原文证据;后端负责证据验证、跨 Document 裁决和最终订单真相。 + ### 3.x 发货通知关键字段真值校验 - 规范订单行采用通用三料号领域模型:`part_number` 是内部料号且为订单必填字段;`customer_part_number` 是客户料号、`aws_part_number` 是货代/AWS 系统料号,二者可选且不单独触发流程门禁;旧 `sku / vendor_part_number / customer_sku` 不再作为当前字段模型字段。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index fc69cc1e..2491f30e 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -25,7 +25,7 @@ - [阶段 ② — 确认发货通知解析](#阶段--确认发货通知解析) - [阶段 ③ — 确认标准客户](#阶段--确认标准客户) - [阶段 ④ — 提供库存](#阶段--提供库存) - - [阶段 ⑤ — 确认字段对齐](#阶段--确认字段对齐) + - [阶段 ⑤ — 校验并解析库存](#阶段--校验并解析库存) - [阶段 ⑥ — 自动匹配库存](#阶段--自动匹配库存) - [阶段 ⑦ — 库存不足时的处理](#阶段--库存不足时的处理) - [阶段 ⑧⑨ — 生成 Excel 与上传货代](#阶段-生成-excel-与上传货代) @@ -39,7 +39,7 @@ 12. [截图位说明(给业务培训/反馈用)](#12-截图位说明给业务培训反馈用) - [12.1 入口页截图](#121-入口页截图) - [12.2 发货通知解析阶段截图](#122-发货通知解析阶段截图) - - [12.3 库存上传与字段对齐阶段截图](#123-库存上传与字段对齐阶段截图) + - [12.3 库存上传与结构校验阶段截图](#123-库存上传与结构校验阶段截图) - [12.4 匹配与缺口阻断阶段截图](#124-匹配与缺口阻断阶段截图) - [12.5 发货 Excel 与上传阶段截图](#125-发货-excel-与上传阶段截图) - [12.6 问题反馈建议截图](#126-问题反馈建议截图) @@ -55,8 +55,16 @@ 1. **解析发货通知**:上传后系统先读取邮件正文和附件;您点击“发送”后,AI 与后端解析器会分别提取候选,再由系统逐字段核验证据,识别客户、收货信息,以及每一行的内部料号、客户料号、AWS 料号、数量、金额、Reservation ID 等。 一封 EML 中可以包含多个订单,也可能一个附件里包含多个订单;系统仍保留为一个接入记录,并按实际业务订单拆分处理。 -2. **载入库存**:上传库存 Excel,或由系统自动从货代/仓库系统导出库存(若已配置自动化)。 -3. **核对库存**:按内部料号 + Reservation ID + 需求数量,与库存表比对是否可满足。 +2. **载入库存**:正式发货优先使用库存站点按排程或手动刷新导出的有效库存文件;对已有发货任务,可通过“选择库存文件”进行受控人工上传。系统按该任务库存站点已发布的解析方案校验工作表、表头和栏位,符合后直接进入匹配,不要求业务人员维护列映射。若用户在对话中临时上传 `.xls` / `.xlsx` / `.csv`,必须明确说明“这是库存文件”;系统只做隔离分析和待确认建议,绝不会直接进入正式库存匹配。 + +### 库存站点启用 + +- 管理员可先保存停用的库存站点,填写系统连接、报表路径、查询条件、仓库识别方式和快照有效期;首次保存不要求手工选择库存文件解析方案。 +- 库存文件解析方案说明 Excel 的工作表、表头、栏位对应和订单匹配键;仓库映射说明货代仓库对应哪个外部系统仓库,两者是不同配置。 +- 正式启用是单独操作。系统会显示尚未完成的系统连接、库存文件解析方案、发货模板和测试导出与解析验证。管理员必须在停用状态发起测试导出,查看结构分析结果并确认本次推荐的已发布解析方案;站点编辑后须重新测试。 +- 启用前系统还会复核:解析方案至少配置一个用于订单与库存关联的字段、且只配置一个库存数量字段;发货模板引用的库存字段均由解析方案提供。固定仓须有精确仓库映射或库存源默认映射;按库存行识别仓库的站点还须配置一个仓库识别字段,并为样例出现的每个货代仓维护外部系统仓库映射。系统只提出缺失项,不会猜测或自动建立仓库映射。 +- 站点进入正式运行后,每次 RPA 导出仍会检查文件结构。新增无关栏位会作为提示记录在库存快照中;关键栏位改名、缺失或结构不兼容时,本次文件不会进入库存匹配,管理员需修订并发布解析方案后重新测试和启用。 +3. **核对库存**:按管理员维护的订单字段与库存字段对应关系进行匹配,再用配置为“库存数量”的字段判断是否可满足需求数量。 4. **生成发货文件**:生成符合货代要求的发货 Excel。 5. **上传货代系统**:自动或手工确认上传至货代平台。 @@ -65,7 +73,7 @@ **业务人员只需要记住 4 件事**: - 先上传或粘贴**发货通知**,确认解析结果 -- 再提供**库存**,并确认字段对齐 +- 库存由已配置站点自动准备;仅在系统提示时刷新库存 - 匹配结果若有缺口,**默认无法发货**;须补库存或返回修订后重匹配 - 全部行满足后,下载/确认**发货 Excel**,并完成货代上传 @@ -73,8 +81,8 @@ - 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后由 AI 完整识别订单。只要明确属于发货需求且内部料号、数量可信,系统会自动创建任务,无需再次人工确认建单。 - Reservation ID 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;订单行 `inventory_source_hint` 是可选路由线索,可在候选编辑中补充,不作为必填门禁。 -- 上传 **库存 Excel** 后,系统会**自动识别表头**(如 `Reservation Order`、`COM ID`)并给出列映射建议;**不确定的列**可在对齐界面用下拉框修改后再确认。 -- 匹配与生成 Excel 由系统规则执行;您主要在解析结果、字段对齐、库存不足时做确认或补货修订。 +- 库存站点首次配置时,管理员可上传样本或执行测试导出,系统会识别表头并在“库存文件解析方案”中确认字段对应关系。陌生表头的 AI 建议仅供管理员参考,不能直接生效;业务用户不维护正式列映射。用户对话上传的库存文件只在明确声明后进入一次性临时分析,并由后端校验和用户确认。 +- 匹配与生成 Excel 由系统规则执行;您主要在解析结果、客户、库存不足时做确认或补货修订。正式库存字段映射由管理员在库存文件解析方案中维护。 --- @@ -88,6 +96,12 @@ | **货代发货 → 客户主数据** | 仅管理员可见;维护标准客户、简码、识别证据、期初导入和识别质量审计 | | **货代发货 → 发货任务** | 查看历史任务状态与导出文件;如需确认、修订、重试或继续处理,请从某条任务「在 Chat 中继续」回到对应对话 | +客户误建且没有任何业务、导入或识别审计引用时,管理员可在「客户主数据」中执行永久删除:系统会先展示阻断引用,再要求输入当前客户简码和删除原因。已有引用的客户不能删除,应停用或等待客户合并流程处理。 + +当两个客户实际属于同一主体时,管理员在「客户主数据」选择源客户和启用目标客户后可执行合并。界面会先展示历史保留引用和将迁移的证据/来源键;确认时必须输入源客户简码和合并原因。合并后源客户仅供历史追溯,不能再被选作新的发货客户。 + +客户主数据会记录创建、关键修改、识别证据审核、停用、合并和删除的治理时间线。修改客户简码、启停状态或识别证据自动匹配授权时,管理员必须填写原因。自动客户确认即使已开启,也必须满足人工真值样本量和准确率门禁;未达标时系统明确显示降级原因,并将任务保留在人工客户复核,不生成业务号。 + ### 2.2 内部任务编号(SN-…) 每处理一笔新的发货需求,系统会分配唯一**任务编号**,格式类似: @@ -123,10 +137,10 @@ WYC26071501 | 顺序 | 资料 | 格式 | 用途 | |------|------|------|------| | 1 | **发货通知 / 订单** | PDF、Word,或邮件/微信正文 | 解析客户、内部料号、客户料号、AWS 料号、数量、Reservation ID、单价、金额等 | -| 2 | **库存快照** | Excel(.xlsx / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 | +| 2 | **库存快照** | Excel(.xls / .xlsx / .csv) | 正式库存由库存站点导出;对话临时文件必须明确声明为库存文件,仅用于受控分析,不自动参与订单匹配 | | 3 | (可选)**货代发货模板** | 由 IT 配置 | 生成最终上传货代用的 Excel | -**顺序要求**:须先完成发货通知解析并确认,再上传库存。若尚未有任务编号就上传库存 Excel,系统会提示您先提交发货通知。 +**顺序要求**:正式订单匹配须先完成发货通知解析并确认,再使用库存站点的有效库存。对话临时库存文件可在任何时点分析,但只有用户明确确认后才会锁定本次会话的质量审计,仍不会自动参与订单匹配。 **开工前检查清单** @@ -135,7 +149,7 @@ WYC26071501 | 发货通知原件 | 能看到内部料号、数量,最好能看到 Reservation ID / COM ID / PR Number | | 库存文件 | 使用 Excel 文件上传,不把整张大表粘贴进聊天 | | 当前任务 | 已拿到任务编号 `SN-...`,且本次库存属于这一个任务 | -| 操作顺序 | 先确认解析,再传库存,再确认字段对齐 | +| 操作顺序 | 先确认解析和客户,再使用对应库存站点的库存文件 | --- @@ -171,7 +185,7 @@ WYC26071501 - 建单后工作台会持久展示订单解析结果;若新订单与旧任务同 PO 但字段冲突,系统会标出冲突并停住后续库存步骤,需您选择保留旧值、采用新值或手工修正后再继续。 - **要求交期、供应商料号、币种** 按**明细行**解析与导出;若 PDF 仅有一个文档级交期或币种,系统会回填到各行。 - **单价、金额、币种** 主要用于展示与导出,**不参与**「够不够货」的自动比对。 -- 若订单含 Reservation ID 而库存表未正确对应,系统会在「字段对齐」环节给出警告。 +- 若库存文件缺少发布方案要求的 Reservation ID、内部料号或数量栏位,系统会拒绝本次文件并提示管理员检查库存文件解析方案。 **订单行示例**(便于理解系统解析目标): @@ -180,25 +194,60 @@ WYC26071501 | 10 | D4-A08AR12000002 | TEMP-S000218929 | B0XXXXXXXX | 1000140351 | 2 | 2026-06-15 | | 20 | D4-A08AR12000003 | - | - | 1000140352 | 1 | 2026-06-18 | +### 4.1.1 管理员如何维护订单字段识别规则 + +“货代配置 → 订单解析”维护的是所有 EML 正文、邮件附件 PDF/Word 共用的一组订单字段。文件格式不同只影响原文提取,不应为 EML 和 PDF 分别建字段。 + +**字段名称是系统标识,不是中文说明。** 管理员应填写英文小写下划线,例如 `part_number`、`customer_part_number`、`reservation_id`、`request_qty`。下游配置使用稳定字段 ID 建立关联,因此系统标识可以重命名;已发布历史版本仍保留发布时的旧名称。若需面向业务展示中文,可在“当前版本显示名称”填写“内部料号”“需求数量”等文案。 + +“纳入当前版本”只决定字段是否参与本次发布和订单解析,不控制名称编辑。未纳入字段仍可修改并保存系统标识与当前草稿显示名称;后续重新纳入时继续使用已保存配置。 + +| 配置项 | 含义 | 建议维护方式 | +|---|---|---| +| 字段位置 | 字段属于整张订单,还是每条货品明细 | PO/客户名填“订单信息”;料号、数量、Reservation ID 填“货品明细” | +| 数据格式 | 后端如何校验和比较值 | 料号/订单号用文本;数量用小数或整数;交期用日期;固定选项用枚举 | +| 别名 | 原文表头或标签的常见写法 | 填 `MPN, Part No., 内部料号` 等列名,不填具体料号值 | +| 识别说明 | 对易混淆字段的额外业务提示 | 例如“优先读取订单明细表的 MPN 列,不要把客户 PO 当内部料号”;简单字段可留空 | +| 业务必填 | 缺失时能否进入后续业务 | 库存匹配必需的料号、数量、Reservation ID 通常勾选;展示字段按实际需要决定 | +| 必须提供原文证据 | 识别结果是否必须能回查到邮件/附件原文 | 核心字段建议勾选,避免把模型猜测当作事实 | +| 允许单一可信来源 | 仅邮件或仅附件有值时是否接受 | 常规订单勾选;只有业务规定邮件与附件必须一致时才取消 | +| 当前版本显示名称 | 本版本对管理员/业务人员展示的文字 | 可写“内部料号”等中文;未纳入时也可编辑保存,不影响系统标识和下游关联 | +| 纳入当前版本 | 是否进入本次发布契约并参与订单解析 | 仅控制生效范围,不控制系统标识或显示名称的编辑权限 | +| 变更说明 | 本次规则调整原因 | 保存或发布前填写,例如“新增客户 MPN 别名” | + +高级识别规则只在出现误识别、跨文档冲突或格式要求时维护: + +| 配置项 | 何时维护 | 推荐初始值 | +|---|---|---| +| 文本处理方式 | 文本比较前需要忽略大小写/空格时 | 料号通常“忽略大小写并去除空格” | +| 核对方式 | 邮件与附件的值怎样判定一致 | 文本用“忽略大小写核对”;数量、日期分别用对应核对方式 | +| 跨文档关联 | 字段可用于证明邮件与附件属于同一订单 | 订单号、客户 PO、Reservation ID 可设置;普通料号通常不设置 | +| 内容不一致时 | 多份原文取到不同值后的动作 | 料号、数量、Reservation ID 选“阻止继续处理”;非关键展示字段可人工复核 | +| 内容校验 | 值的合法性约束 | 料号至少“不为空”;数量应为正数;有固定格式时再加格式校验 | +| 可识别的内容来源 | 系统可从哪里读取该字段 | 通常允许附件表格/正文与邮件表格/正文;智能识别结果只是候选,核心字段不能只依赖它 | + +推荐先维护字段名称、位置、数据格式、别名、必填和原文证据;高级规则保持推荐默认值,只有真实订单样本出现问题时再调整。发布前应使用至少一封含 EML + 附件的脱敏订单验证字段值和原文证据。 + +#### 账款客户与送货客户 + +- 订单模板统一解析 `bill_to_customer`(账款客户)与 `ship_to_customer`(送货客户/站点)的原文;如订单明确提供外部编码及来源系统,同时解析对应 Code 和 Source System。 +- 系统先用“来源系统 + 外部编码”匹配客户主数据,再回退标准名称和已审核别名。Bill-to 决定业务归属客户;Ship-to 匹配该客户或其他标准客户下的送货站点,不重复创建一条账款客户。 +- 客户简称不是订单原文字段,不由 AI 识别,也不出现在订单模板中;它只能从已匹配并确认的标准客户主数据取得,用于业务编号和发货文件。 +- 唯一候选仍会展示给用户复核;未命中或多个候选时必须人工选择,确认前不得进入库存、导出与上传流程。 +- Reservation ID 在订单模板中按普通文本维护;管理员无需配置“预约号格式”。后端仍保留不可见的安全校验,拦截明显 UUID、内部主键或错误字段。 + ### 4.2 库存表(来自仓库/货代导出) -库存 Excel 至少需要能对应到以下列(列名因模板而异,上传后需您确认映射): +库存字段没有系统预置清单,管理员在“货代配置 → 库存映射 → 库存字段目录”自行创建。每个字段需维护名称、说明、数据格式和用途: -| 字段 | 业务含义 | 常见列名示例 | -|------|----------|--------------| -| **内部料号** | 与订单 `part_number` 一致 | Supplier Sku、Supplier SKU | -| **AWS 料号** | 可选追溯字段,不作为默认主匹配键 | AWS Sku、AWS SKU | -| **Reservation ID** | 与订单 Reservation ID 一致 | COM ID、**Reservation Order**、Reservation ID | -| **可用数量** | 当前可发数量 | Qty Available、可用数量、Qty | +| 字段用途 | 如何维护 | +|---|---| +| 库存匹配 | 选择需要与订单字段对应的一个或多个字段,例如某企业可配置“供应商料号 + 预约参考号” | +| 库存数量 | 每个解析方案只能使用一个,用来计算当前可发数量 | +| 仓库识别 | 仅按库存行动态识别仓库的站点需要,每个方案只能使用一个 | +| 一般业务信息 | 按需创建,可写入发货模板,例如 ODM、批次、库位等;这些名称均不是系统内置 | -**AWS 库存模板**(当前系统默认支持)示例: - -- `Supplier Sku` → 内部料号 `part_number` -- `AWS Sku` → 可选 AWS 料号 `aws_part_number` -- `COM ID` / `Reservation Order` → Reservation ID -- `Qty Available` → 可用数量 - -若您的库存表带标题行(如「AWS DUB On Hand Inventory by Location」),系统会尝试跳过标题行,自动识别真正的表头。 +上传库存样本后,系统会读取工作表、表头和少量样例。字段名称与表头完全相同时可以自动预填;名称不同时,由管理员从下拉框选择,或让 Dify 根据真实表头给出候选,再由管理员确认。候选不会自动创建字段、发布方案或绑定库存站点。 --- @@ -211,9 +260,9 @@ WYC26071501 ↓ ③ 确认标准客户并生成业务编号 ↓ -④ 提供库存(上传 Excel / 等待自动导出 / 粘贴少量行) +④ 提供库存(复用有效系统库存文件 / 上传 Excel / 等待排程或手动刷新 / 粘贴少量行) ↓ -⑤ 确认库存列与订单字段的对齐关系 +⑤ 系统按已发布解析方案校验并解析库存 ↓ ⑥ 自动匹配库存 ↓ @@ -227,13 +276,13 @@ WYC26071501 **重要原则**: - 必须先确认**发货通知和标准客户**,再处理**库存**。 -- 必须先确认**字段对齐**,再执行**库存匹配**。 +- 库存文件必须通过库存站点已发布解析方案的结构校验,才能执行**库存匹配**。 - 只有**全部订单行满足**后,才能生成 Excel 并上传货代;存在缺口时系统会阻断后续步骤。 **一句话 SOP** ```text -发货通知 → 确认解析 → 确认客户并生成业务编号 → 上传库存 → 确认字段对齐 → 匹配库存 → (有缺口则阻断)→ 生成 Excel → 上传货代 +发货通知 → 确认解析 → 确认客户并生成业务编号 → 获取或上传库存 → 系统校验并解析 → 匹配库存 → (有缺口则阻断)→ 生成 Excel → 上传货代 ``` --- @@ -298,8 +347,8 @@ WYC26071501 **其他方式:** -- **自动导出**:若已对接 RPA,助手可触发从货代/仓库系统自动拉取库存(需等待完成); -- **小表粘贴**:仅几行库存时,可直接粘贴到聊天(大 Excel 请勿粘贴,易失败)。 +- **系统库存文件**:系统优先使用定时导出的有效库存文件;若文件缺失或过期,会提示等待下一次排程或由业务人员明确点击刷新库存。正常发货流程不会自动登录货代系统。 +- **任务级人工上传**:RPA 文件缺失或需要使用业务人员取得的正式库存文件时,可在当前任务点击“选择库存文件”。该文件仍必须来自任务对应的库存站点并符合已发布解析方案。 **注意:** @@ -308,43 +357,31 @@ WYC26071501 --- -### 阶段 ⑤ — 确认字段对齐 +### 阶段 ⑤ — 校验并解析库存 -上传库存后,系统会**先自动推断** Excel 列与订单字段的对应关系(例如 `Supplier Sku`→内部料号、`AWS Sku`→AWS 料号、`Reservation Order`→Reservation ID、`Qty Available`→可用数量),并展示**字段对齐表**供您核对。 +库存站点启用前,管理员已经在“库存文件解析方案”中确认 Excel 工作表、表头行、库存栏位和订单匹配键。任务获取或人工上传库存后,系统直接使用该发布方案,不再让业务人员逐票确认列映射。 -对齐表说明: +系统自动检查: -- 库存 Excel 哪一列对应内部料号、AWS 料号、Reservation ID、可用数量; -- 这些列如何与订单里的字段比对; -- 订单与库存各取几行样例供您目视检查。 +- 文件格式、工作表和表头行是否与发布方案一致; +- 解析方案配置的库存匹配字段和唯一库存数量字段是否存在; +- 动态仓站点配置的仓库识别字段是否存在; +- 文件中是否至少有一行有效库存数据。 -**示例(概念示意):** +**处理结果:** -| 比对项 | 库存 Excel 列 | 订单字段 | -|--------|---------------|----------| -| 内部料号 | Supplier Sku(或系统推断的列名) | part_number | -| AWS 料号 | AWS Sku(可选追溯列) | `aws_part_number` | -| 预留号 | COM ID / **Reservation Order**(可在下拉框中改选) | Reservation ID | -| 数量 | Qty Available(可在下拉框中改选) | 需求数量 | - -聊天页若提供**列映射下拉框**,请核对自动推断是否正确;改选后须再次点击「确认」。 - -**可选操作:** - -| 操作 | 含义 | +| 结果 | 后续 | |------|------| -| **确认** | 列映射正确,可以开始匹配 | -| **更正映射** | 列识别不对,回到映射步骤重新指定 | -| **重新上传** | 换一份库存文件 | -| **驳回 / 取消** | 终止本任务 | +| **结构一致或兼容** | 系统确定性解析并直接进入库存匹配 | +| **关键栏位或结构不一致** | 本次上传整体回滚;重新取得正确库存文件,或由管理员创建并发布新解析方案 | -**在未点击「确认」前,系统不会进行库存匹配**,以免列对错导致误判。 +业务人员不能在当前任务中更正映射,也不能通过 AI 猜列绕过结构错误。 --- ### 阶段 ⑥ — 自动匹配库存 -确认字段对齐后,系统按规则逐行比对(详见 [§7](#7-库存匹配规则))。 +库存文件通过结构校验并解析后,系统按规则逐行比对(详见 [§7](#7-库存匹配规则))。 **匹配结果类型:** @@ -402,15 +439,15 @@ WYC26071501 | 您的选择 | 含义 | 后续 | |----------|------|------| -| **重新上传库存** | 仓库/货代已更新库存快照 | 重新确认字段对齐(如有变化)→ 重新匹配 | -| **返回字段对齐** | 列映射可能有误 | 更正映射后重新匹配 | +| **重新上传库存** | 仓库/货代已更新库存文件 | 系统先解除当前库存关联并清理旧匹配结果,再按发布方案校验新文件并匹配 | +| **联系管理员修订解析方案** | 正式库存文件结构确实发生变化 | 管理员用样本创建新版本、测试并发布后重新上传 | | **重新匹配** | 订单或库存数据已修订,需重新比对 | 在同一份已确认数据上再次执行匹配 | | **驳回** | 本单暂无法处理 | 终止任务,不生成发货文件 | **重要说明**: - 本期**不支持**「确认部分发货」或按可发数量继续出单;须**全部订单行满足**后方可继续。 -- 补库存后请重新上传 Excel 并走完字段对齐确认,再执行匹配,直至结果变为「完全满足」。 +- 补库存后请重新上传 Excel;系统会按发布方案重新校验和匹配,直至结果变为「完全满足」。 若任务已被驳回,助手可能建议「重新创建发货任务」;此时应**新开对话**处理新单据,勿在已驳回任务上继续点「确认对齐」类按钮。 @@ -444,8 +481,8 @@ WYC26071501 | 已创建 | 任务已建立,尚未完成解析 | | 待核对解析 | 发货通知已解析,等您确认 | | 解析已确认 | 发货通知无误,待提供库存 | -| 待库存 / 库存映射中 | 已收到或正在处理库存文件 | -| 待确认字段对齐 | 须您确认库存列与订单字段对应关系 | +| 待库存 / 库存处理中 | 已收到或正在处理库存文件 | +| 库存结构异常 | 文件与库存站点发布解析方案不一致,须换文件或联系管理员修订方案 | | 已匹配 | 库存比对完成且全部行满足 | | 库存不足,无法发货 | 存在缺口,须补库存或返回修订后重匹配 | | 已生成 Excel | 发货文件已就绪 | @@ -461,10 +498,9 @@ WYC26071501 | 处理新发货通知 | 打开助手 → 上传 PDF/Word 或粘贴文字 | | 核对解析是否正确 | 看助手表格 → 点 **确认** 或 **重新解析** | | 上传库存 | 点 **选择库存文件**,或按助手菜单选「上传」 | -| 列映射不对 | 点 **更正映射** 或输入「更正映射」 | +| 库存结构不对 | 换正确文件;若货代模板已变更,联系管理员修订并发布库存文件解析方案 | | 换一份库存 | 点 **重新上传** | -| 确认可以比对了 | 字段对齐界面点 **确认** | -| 库存不够 | 重新上传库存 / 返回字段对齐 / 重新匹配,或点 **驳回** | +| 库存不够 | 重新上传库存 / 重新匹配,或点 **驳回** | | 整单不做 | 点 **驳回** | | 查进度 | 货代发货列表,或问助手「当前任务进度」 | | 继续未完成任务 | 从列表「在 Chat 中继续」,或对话中提供 SN-… 编号 | @@ -507,20 +543,20 @@ WYC26071501 | 发货通知上传后结果页 | 任务编号、采购单号、内部料号、客户料号、AWS 料号、Reservation ID、数量、确认/重新解析/驳回按钮 | 培训业务如何核对解析结果 | | 低置信度提示页 | 解析结果下方的风险提示或需人工核对提示 | 培训业务识别“需要更认真核对”的场景 | -### 12.3 库存上传与字段对齐阶段截图 +### 12.3 库存上传与结构校验阶段截图 | 截图位 | 应包含内容 | 用途 | |--------|------------|------| | 上传库存入口 | 选择库存文件按钮或上传动作 | 培训业务如何上传库存 Excel | -| 字段对齐页 | 库存列、订单字段、样例数据、确认/更正映射/重新上传按钮 | 培训业务如何确认列映射 | -| 列映射下拉框 | 内部料号、AWS 料号、Reservation ID、可用数量的下拉选择 | 培训业务如何修正错误映射 | +| 上传成功页 | 库存文件名、库存站点、解析方案和待匹配状态 | 培训业务确认文件已按正式方案解析 | +| 结构异常页 | 不一致说明、重新上传提示和管理员处理建议 | 培训业务识别“文件错误”与“方案需升级” | ### 12.4 匹配与缺口阻断阶段截图 | 截图位 | 应包含内容 | 用途 | |--------|------------|------| | 匹配结果页 | 内部料号、Reservation ID、需求数量、可用数量、缺口、状态 | 培训业务如何判断是否可发 | -| 缺口阻断页 | 不可发货提示、重新上传库存 / 返回字段对齐 / 重新匹配 / 驳回按钮 | 培训业务如何处理库存不足 | +| 缺口阻断页 | 不可发货提示、重新上传库存 / 重新匹配 / 驳回按钮 | 培训业务如何处理库存不足 | ### 12.5 发货 Excel 与上传阶段截图 @@ -554,7 +590,7 @@ A:避免任务编号不一致、订单行未定型就占用库存比对,导 A:不可以。请使用「选择库存文件」上传;整表粘贴易失败且无法保证列映射准确。 **Q:订单有 Reservation ID,库存表里是 COM ID,能匹配吗?** -A:可以。字段对齐环节会把 COM ID 与订单 Reservation ID 对应;确认映射无误即可。 +A:可以,前提是管理员已在该库存站点的发布解析方案中把 COM ID 映射为预约号。业务任务会直接使用该方案,不需要逐票确认。 **Q:发货通知解析结果里没有 Reservation ID(或一直为空)怎么办?** A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是库存精确匹配的关键字段。请按以下顺序处理: diff --git a/docs/features/shipping-notice/inventory_source_plan.md b/docs/features/shipping-notice/inventory_source_plan.md index 814633cc..90d460bc 100644 --- a/docs/features/shipping-notice/inventory_source_plan.md +++ b/docs/features/shipping-notice/inventory_source_plan.md @@ -1,162 +1,156 @@ -# 发货通知库存源路由方案(订单解析阶段判定) +# 发货通知库存源与库存文件方案 -## 背景 +## 目标 -发货通知的库存导出不能再假设只有一个 RPA 地址或一种页面流程。不同目的地、出货港口或仓库线索可能对应不同货代系统入口,例如 DSV 360 的不同 Program,或 Crane FootPrint Portal 的不同 Warehouse。若选错库存源,后续库存匹配和出货 Excel 会建立在错误库存池上,风险高于「未查到库存」。 +货代发货的业务主键是 **Inventory Source(库存源)**,不是 RPA Driver、登录账号或 Warehouse。正常发货流程只匹配已经导出的有效库存文件;RPA 是由排程或用户明确刷新触发的库存数据生产旁路。 -历史上 `site_id`(如 `AWSBI`)与 `warehouse_id`(如 `BYAWSATL01`)曾被混用,导致发货 Excel 与 RPA 查询参数不一致。本方案将库存源判定前移到**订单解析阶段**,并以独立数据库字段持久化业务决策。 - -## 设计原则 - -- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段(目的地、港口、仓库线索等),**不负责**最终 RPA URL / source_code 决策。 -- 订单行仅保留 `inventory_source_hint` 作为可选路由线索;库存连接器使用独立 `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` 参数,按 `connector_type` 分发到不同 Driver。 - -## 判定时机与状态机 - -### 何时判定 - -1. **`parse_notice`**:解析结构化订单后,立即调用 `adjudicate_inventory_source()` 抽取/写入库存源**线索与候选**(不抢解析人工确认)。 -2. **低置信度**:先进入 `checkpoint=parse_review`(确认 / 重新解析 / 驳回);解析通过后再看库存源是否稳定。 -3. **高置信度且唯一命中且配置完整** → `inventory_source_status=resolved`,任务可进入 `parsed`。 -4. **解析已接受但未命中 / 多命中 / 配置无效 / 路由指纹变更** → `pending_review`,`checkpoint=inventory_source_review`,`pending_human_reason=inventory_source_unresolved`。 -5. 用户在聊天区确认 `source_code` → `confirm_inventory_source` → `inventory_source_status=user_confirmed`,再推进至 `parsed` 并允许 RPA。 - -### 稳定状态 - -| status | 含义 | -| --- | --- | -| `resolved` | 规则自动唯一命中 | -| `user_confirmed` | 用户已确认 source_code | - -其余状态(`unresolved`、`ambiguous`、`invalid`、`conflicted`)均视为不稳定,gate 阻断。 - -## 独立数据库字段(`shipping_tasks`) - -| 字段 | 说明 | -| --- | --- | -| `destination_*` | 目的地候选(城市、国家、港口等),供规则匹配 | -| `inventory_source_code` | 正式库存源编码,如 `DSV360_AWSDU` | -| `inventory_connector_type` | 库存连接器类型:`dsv360` / `crane_footprint` | -| `inventory_site_id` | DSV Program / Site(如 `AWSDU`) | -| `inventory_warehouse_id` | 具体仓库(如需要) | -| `inventory_source_status` | 判定状态 | -| `inventory_source_method` | `auto` / `user` | -| `inventory_source_config_version` | YAML 配置版本指纹 | -| `inventory_routing_fingerprint` | 路由输入指纹,变更时要求重确认 | - -`step_payload_json.inventory_source_resolution` 仅保留候选列表与诊断信息,**不作为** gate 真相源。 - -## 配置文件 - -路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`) - -每个 source 含: - -- `source_code`、`connector_type`、`site_id`、`warehouse_id` -- `navigation`、`parameters`(RPA 填表) -- `match_aliases`:目的地/港口/仓库别名 -- `match`:加权评分规则(可选) - -新增 Warehouse **只改 YAML**,不改 Python。 - -## Trigger 协议 - -```json -{ - "action": "inventory_export", - "task_no": "SN-xxx", - "attempt": 1, - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "entry_url": "https://s360.dbschenker.com/...", - "query": { - "program_group": "Dublin", - "program_label": "AWSDU - Prod (JDA)", - "report_group": "Inventory", - "report_name": "On Hand Inventory by Location", - "owner_code": "CADU-0000000100" - } - } -} +```text +订单事实 -> 库存源路由规则 -> source_code 候选 -> 有效库存文件 + -> Reservation ID + Part Number 匹配 -> 最终 Warehouse -> 发货 Excel ``` -Crane 示例: +## 领域边界 -```json -{ - "source_code": "CRANE_TZR", - "connector_type": "crane_footprint", - "entry_url": "https://wms-portal.craneww.com/#/on-hand-details-query", - "query": { - "owner_code": "0000000100", - "warehouse_code": "TZR", - "project_code": null - } -} +| 概念 | 职责 | +| --- | --- | +| Inventory Source | 业务库存范围、库存文件归档和匹配主键 | +| RPA Profile | 登录地址、加密凭据与连接级登录配置 | +| `connector_type` | 选择 RPA Driver,仅允许 `dbs`、`crane` | +| Inventory File | 正常货代流程直接消费的库存快照 | +| Warehouse | 固定配置或库存行匹配得到的运行时业务结果 | +| External System Warehouse Mapping | 货代库存身份到外部系统仓库的对应关系 | + +一个库存源绑定一个 RPA Profile;一个 RPA Profile 可以服务多个库存源。RPA Profile 仅用于排程导出、用户手动刷新和配置测试,不能替代 `source_code` 作为业务身份。 + +## 库存源与 Warehouse + +### 库存源 RPA 业务配置 + +货代连接配置只承载登录地址、加密凭据和受控登录方式(当前仅 `password`)。**库存源**承载与具体库存报表相关的业务配置,必须持久化保存并随 Source 版本审计: + +```text +report_path_json # DBS: program_group / program_label / report_group / report_name +query_parameters_json # 参数名、single/multi_text/multi_select、values、required、select_all、joiner +match_aliases_json # 用于库存源线索/目的地归一,不用于选择 Warehouse ``` -## Gate 规则(硬阻断) +业务管理员维护路径和参数值;RPA Driver 模板维护 `selector_env`、CSS selector、下载模式、控件等待策略等技术细节。上述技术字段不得写入库存源。DBS 参数必须支持单选、文本多值和列表多选。Crane 当前导出完整多仓库存文件,不维护 Crane Warehouse 清单。 -以下步骤执行前调用 `assert_inventory_source_gate(task)`: +`backend/config/shipping_inventory_sources.yaml` 保留为**期初导入参考**,直到数据库导入、校验和试跑完成前不得删除;它不再是运行时读取源。导入时将旧 `dsv360` / `crane_footprint` 归一为 `dbs` / `crane`,映射报表路径、参数和别名,并丢弃 `site_id`。导入完成后,RPA 运行时只读取数据库。 -- RPA 触发 / 重试 -- 库存快照 link / 映射 / 匹配 -- 发货 Excel 生成 -- 货代上传 +### 固定 Warehouse -库存快照 link 时额外做 **identity check**:`source_code`、`connector_type`、`site_id`、`warehouse_id` 与任务字段一致,否则 `SHIPPING.INVENTORY_IDENTITY_MISMATCH`。 +库存源已细化到仓库时使用 `warehouse_resolution_mode=fixed`,配置必须提供 `fixed_warehouse_id`。任务确定库存源后直接得到最终 Warehouse,库存行如提供 Warehouse 字段则只用于一致性校验。 -## 错误码(API) +### 动态 Warehouse -| code | 场景 | +库存源覆盖多个 Warehouse 时使用 `warehouse_resolution_mode=inventory_match`。Crane 使用该模式,**不维护 Crane 网站的 Warehouse 清单**。任务使用 `reservation_id + part_number` 匹配库存行,从唯一命中行读取 Warehouse ID。 + +| 匹配结果 | Warehouse 状态 | | --- | --- | -| `SHIPPING.INVENTORY_SOURCE_UNRESOLVED` | 无法判定 | -| `SHIPPING.INVENTORY_SOURCE_AMBIGUOUS` | 多候选 | -| `SHIPPING.INVENTORY_SOURCE_INVALID` | 配置无效 | -| `SHIPPING.INVENTORY_SOURCE_CONFLICTED` | 判定冲突 | -| `SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED` | 需人工确认 | -| `SHIPPING.INVENTORY_SOURCE_CHANGED` | 路由变更需重确认 | -| `SHIPPING.INVENTORY_IDENTITY_MISMATCH` | 快照与任务不一致 | -| `SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED` | 通用 gate 阻断 | +| 所有订单行命中同一 Warehouse | `resolved` | +| 无库存行命中 | `unresolved` | +| 同一 Reservation + PN 命中多个 Warehouse | `ambiguous` | +| 不同行命中不同 Warehouse | `conflicted` | +| 库存文件缺少所需 Warehouse 字段 | `invalid` | -前端 i18n:`errors.codes.SHIPPING_INVENTORY_SOURCE_*`(点号转下划线)。 +库存数量是否足够属于履约判断;唯一命中 Warehouse 后,即使数量不足也不得重新选择其他 Warehouse。 -## 聊天区交互 +## 通用库存源路由 -- 检查点 `inventory_source_review` 展示候选按钮(携带 `source_code`)。 -- 用户可直接输入目的地线索(如 `Dublin`、`AWSDU`),前端匹配唯一候选后调用 `confirm_inventory_source`。 -- 动作:`confirm_inventory_source`、`retry_resolve_inventory_source`。 +路由规则是受控、可配置、版本化的决策表。规则只生成 `source_code` 候选,不执行 RPA,也不直接决定 Warehouse。 -## 初始路由规则(示例) +首批可注册事实包括:任务的客户、目的地、订单类型、发件人信息,以及订单行的 Reservation ID、料号和 `inventory_source_hint`。仅允许白名单字段、白名单操作符和白名单动作,禁止 Python、SQL、JavaScript 等任意表达式。 -- `BISON`, `AWSBI` → `DSV360_AWSBI` -- `CINCINNATI`, `CVG`, `AWSCV` → `DSV360_AWSCV` -- `DUB`, `DUBLIN` → `DSV360_AWSDU` -- `MOERDIJK`, `AMS`, `AWSAMS` → `DSV360_AWSAMS` -- `USLCK`, `SALT LAKE CITY` → `DSV360_AWSSL` -- `SINGAPORE`, `SG` → `DSV360_AWSSG` -- `TZR`, `THAILAND` → `CRANE_TZR` +首批 Reservation ID 兜底规则为: -完整列表以 YAML 为准。 - -## 相关代码 - -| 模块 | 路径 | +| 条件 | 候选库存源 | | --- | --- | -| 规则与指纹 | `services/shipping_notice/inventory_source_rules.py` | -| Gate | `services/shipping_notice/inventory_source_gate.py` | -| 解析集成 | `services/shipping_notice/task_workflow.py` | -| 确认 Tool | `services/shipping_notice/inventory_rpa_workflow.py` | -| 配置加载 | `services/shipping_notice/inventory_sources.py` | -| 迁移 | `migrations/versions/b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields.py` | +| 以 `1` 开头 | DUB、RTM 对应的 `source_code` | +| 以 `2` 开头 | CMH、CVG、FRA 对应的 `source_code` | +| 以 `3` 开头 | SIN 对应的 `source_code` | +| 以 `4` 开头 | SLC 对应的 `source_code` | +| 恰好五位纯数字 | `CRANE` | -## 后续演进 +五位数字必须有可信的 Reservation ID 原文证据,不能把任意五位数字视为 Reservation ID。人工确认和文档明确字段优先于通用兜底规则;同优先级的互斥结果必须进入 `conflicted`,不得静默覆盖。 -- 后台规则管理页面与审核流。 -- 批次级对话覆盖(当前仅任务级)。 -- 全局规则变更建议与审计。 +## 库存文件优先流程 + +任务得到一个或多个候选 `source_code` 后,应按每个 Source 查找最新的有效库存文件: + +```text +source_code 相同 ++ snapshot_status = ready ++ 未过期 +-> exported_at 最新的文件 +``` + +多个 Source 候选时,分别以 `reservation_id + part_number` 匹配其库存文件。只有一个 Source 的有效快照覆盖全部订单匹配键时,才能确定 Source;库存数量是否足够、是否更多均不参与 Source 选择。 + +没有有效文件时任务进入 `inventory_missing` 或 `inventory_expired`,提示等待排程或由用户明确刷新。**正常任务不得自动登录货代系统或自动触发 RPA。** + +## RPA 库存文件生产 + +### 排程导出 + +排程以 `source_codes` 为业务目标。系统按 RPA Profile 分组以复用登录 Session,但每个导出结果必须独立记录所属 `source_code`。 + +### 用户手动刷新 + +仅当用户明确选择“刷新库存”时,才可为当前任务候选或已确认的 Source 创建手动 RPA Run。重复点击应复用运行中的 Run;导出失败不得删除旧有效库存文件。 + +RPA Trigger、回调、日志和库存文件均不得携带明文凭据。`connector_type` 仅为 `dbs` 或 `crane`,用于 Driver 分发。 + +## 后台管理与生命周期 + +后台以六个二级工作区维护:**连接配置、库存源、路由规则、库存快照、导出记录、外部系统仓库映射**。前四类配置支持多个对象并以列表选择;库存快照和导出记录只读。导出记录同时展示已入库的库存文件和未生成文件的失败、跳过或等待回调的排程运行,不提供“重试”按钮。 + +路由条件由白名单业务字段、白名单匹配符号和结构化比较值组成;不使用自然语言或自由表达式。`in/not_in` 使用列表值,长度符号使用整数,空值符号不需要比较值。草稿规则可编辑、删除或发布;发布后不可修改,只能归档并新建后续规则版本。 + +配置错误且无引用时允许删除。连接配置被库存源引用时、库存源被路由规则/快照/任务/导出运行引用时,服务端拒绝删除;有历史引用的连接、库存源和映射使用停用,发布规则使用归档。停用连接前必须先停用其所有库存源,避免启用库存源指向不可用登录配置。 + +## 任务与文件身份 + +`site_id` 不再是库存业务身份,也不进入新模型。最终身份规则为: + +```text +任务业务身份:source_code + resolved_warehouse_id +固定仓库存文件:run_no + source_code + warehouse_id +动态仓原始文件:run_no + source_code +``` + +动态仓原始文件可包含多个 Warehouse,不应把它伪装为单一 Warehouse 文件。 + +## 外部系统仓库映射 + +外部系统仓库映射维护在 HXOPS 中,但当前只提供后台维护和后端内部查询 Service;不开发 Tool API、Dify Tool、Agent Context,也不在货代 Agent 中判断或创建调拨单。 + +映射字段: + +```text +external_system_code +external_organization_code # 可空;TOPGP 无此概念时为 NULL +external_site_code # 可空 +external_warehouse_code +external_warehouse_name +``` + +查询顺序: + +```text +source_code + resolved_warehouse_id 精确映射 +-> source_code + NULL 默认映射 +-> unmapped +``` + +一个货代 `source + warehouse` 最多对应一个外部系统仓库;多个货代 Warehouse 可以对应同一个外部系统仓库。Crane 若全部 Warehouse 对应同一外部系统仓库,只维护 Source 级默认映射即可。 + +## 阶段门禁 + +实施必须按以下顺序推进,每一阶段均执行实现、测试、Review、验收;未通过不得进入下一阶段: + +1. 领域契约与文档。 +2. 数据模型、迁移与凭据安全。 +3. 配置入库、通用路由与后台管理。 +4. 库存文件优先、排程和手动刷新。 +5. Warehouse、Excel、外部系统内部映射与 `site_id` 清理。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 78e1a273..f65574bc 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -49,13 +49,18 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open | 修订任务 | `create_revision` 继承原业务单和业务编号,展示时追加任务版本信息 | | 强制新建 | `force_create` 创建独立业务单并申请新流水 | | 客户更正 | 编号前可重新绑定;编号后不得静默改号,须保留原号作废与替代关系 | -| 历史任务 | 允许无标准客户和业务编号,默认不补发历史业务号 | +| 任务完整性 | 所有货代任务必须关联业务单;缺少业务单或未确认标准客户时阻断下游副作用 | ### 目标数据边界 - `ShippingTask.customer_name/customer_code` 保留为邮件或文件解析原值,继续兼容现有业务指纹与库存列映射,不作为标准客户外键。 - 标准客户由独立客户主数据维护,至少包含内部 `customer_id`、标准名称、全局唯一简码、启停状态和审计字段。 - 已审核识别证据独立存储,支持名称别名、完整邮箱、非公共且独占域名、模板指纹等;Agent/LLM 只能提出候选,不能直接创建有效简码或自动批准识别规则。 +- 永久删除前必须调用生命周期影响查询。业务单、业务编号流水、外部来源键、导入目标/结果、影子候选和人工真值是阻断引用;识别证据是可级联配置。影子候选同时保留展示 JSON 和规范化关联表,删除/合并逻辑只以服务端统一统计为准。 +- 管理员删除误建客户时,前端先展示影响预检;提交时仍必须携带当前 `confirmation_short_code` 和 `reason`。后端以客户行锁重新统计全部引用,任一引用返回 `SHIPPING.CUSTOMER_DELETE_BLOCKED`;成功后只保留 `ShippingCustomerLifecycleEvent(event_type='deleted')` 的客户快照审计,不保留指向已删除客户的外键。 +- 客户合并使用源客户的 `merged_into_customer_id` 和快照审计表 `shipping_customer_merges`。`GET /api/admin/shipping-customers/{source_id}/merge-impact` 返回历史保留引用与可迁移配置;提交合并需目标客户、源简码二次确认和原因。合并事务只迁移 `shipping_customer_identifiers` 与 `shipping_customer_external_refs`,业务单、业务流水、导入行、影子候选和人工标签均保持原引用;源客户状态设为 `merged`,新选客与识别入口只接受 `active` 客户。 +- 客户创建、编辑、启停、简码变更及识别证据创建/审核/停用/自动匹配授权均写入 `ShippingCustomerLifecycleEvent` 快照;简码、状态和自动匹配授权属于高风险变更,服务端强制要求 `reason`。管理员通过 `/lifecycle-timeline` 查询单客户时间线。 +- 自动确认除 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED` 外,还须通过 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES`(默认 20)及 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY`(默认 0.98)门禁。统计分母仅包括当前强规则会唯一命中的已人工真值样本;未达标返回降级状态、不绑定客户、不生成业务号。`/governance-quality` 和影子报告均返回门禁状态及阈值快照。 - 业务编号归属于独立业务单聚合,不直接归属于某个任务版本;一个业务单可以关联线性的 `ShippingTask` 修订链。 - 流水表按 `(business_type, customer_id, business_date)` 唯一,使用 PostgreSQL 原子 upsert/returning 分配,`business_no` 唯一约束提供最终保护。 @@ -78,7 +83,6 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open - 标准模板包含 `customers` 与 `identifiers` 两个 Sheet;客户行使用 `source_system + legacy_customer_key` 保证幂等。 - 导入必须经历“上传暂存 → 标准化/预检 → 重复与冲突人工处理 → 审核发布 → 对账”,禁止上传后逐行直接写正式客户表。 - 阻断项包括标准名称缺失、简码格式或唯一性冲突、标识找不到客户、允许自动匹配的邮箱冲突;名称相似、公共域名和共享域名只产生警告,不得自动合并。 -- 历史任务客户回填是独立批次:保留原始解析字段,仅回填稳定客户关联,默认不生成历史业务编号。 ### 分阶段交付与验收门 @@ -89,8 +93,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open | 2 | 客户管理与期初导入 | 导入可预检、幂等、整批发布、审计和对账;简码与标识冲突被阻断 | | 3 | 客户影子识别 | 只记录候选不阻断;真实历史样本形成准确率报告;误自动匹配为 0 | | 4 | 客户人工确认 Gate | 所有后续副作用入口均不可绕过;客户确认事件完整审计 | -| 5 | 业务编号生成、查询和展示 | PostgreSQL 并发无重复;修订继承、强制新建重新编号;双号查询与历史兼容通过 | -| 6 | 有限自动识别、监控和历史回填 | 仅已审核强规则自动放行;可降级;质量指标、纠错和回填审计可查询 | +| 5 | 业务编号生成、查询和展示 | PostgreSQL 并发无重复;修订继承、强制新建重新编号;双号查询通过 | +| 6 | 有限自动识别、监控和纠错 | 仅已审核强规则自动放行;可降级;质量指标与纠错审计可查询 | 每一阶段完成前必须执行本阶段代码 Review,按严重度列出全部发现、修复后重跑对应测试,并逐条核对验收标准;存在未处理高风险问题时不得进入下一阶段。 @@ -297,21 +301,164 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 # RPA 目录 -FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers -FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers + +## 唯一订单 Schema(阶段一) + +当前业务只有一组必须满足库存路由、匹配和发货 Excel 的订单字段,因此所有 EML 正文和 PDF/Word 附件共享唯一逻辑 Schema `SHIPPING_ORDER`。文件类型只影响文本提取方式,不选择不同字段配置。 + +管理端入口:`/admin/shipping-notice`(页面名称为“货代配置”)中的“订单字段”工作区;订单字段不再作为左侧一级菜单。主要接口: + +管理界面以业务字段工作台呈现:管理员填写的“字段名称(系统标识)”就是 `field_code`,必须为小写下划线格式,例如 `part_number`、`reservation_id`、`request_qty`。系统不再生成随机字段编码;下游配置使用稳定 `field_id` 关联字段,发布快照同时冻结当时的 `field_code`,因此管理员可重命名系统标识且不会污染历史版本。字段首次发布后 `scope/value_type` 仍不可修改。字段清单与单字段规则编辑器分栏显示,避免字段数量增长时将全部规则纵向堆叠。 + +版本字段定义中的 `display_name` 仅为当前版本的业务展示文案,不参与下游关联。例如 `field_code=part_number` 可以显示为“内部料号”;修改显示名称不会改变运行时字段身份。草稿为每个 active 字段保存完整规则和 `enabled` 状态;未纳入字段仍可编辑并保存显示名称,但发布契约、checksum 与 Dify 运行时只包含 `enabled=true` 字段。 + +### 版本治理与审计(阶段一) + +- `ShippingOrderSchemaVersion.definition_json` 是草稿和发布版本唯一的配置真相;不再从版本字段关联表读取草稿,避免草稿和发布快照出现双数据源分叉。 +- 草稿保存和发布请求必须携带 `expected_lock_version`。后端锁版本不一致时返回 `SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT`(HTTP 409);管理端提示后自动刷新最新草稿,禁止静默覆盖其他管理员的改动。 +- 发布时冻结完整定义及 checksum;未纳入字段仍保存在发布快照中供审计,但后端编译 Dify contract 和运行时裁决只读取 `enabled=true` 字段。 +- 创建草稿、从版本复制、保存草稿、发布、删除草稿以及字段目录变更均写入只追加的 `ShippingOrderSchemaAuditEvent`,记录操作者、请求 ID、前后快照和结构化摘要。草稿删除后事件保留快照,`version_id` 置空。 +- 历史草稿与旧版本字段关联记录不迁移。升级时清理旧草稿及其子记录,保留既有已发布版本作为新版本治理的起点;生产部署前必须确认没有需要保留的草稿。 + +### 历史版本浏览(阶段二) + +- 管理端“版本历史”以侧边抽屉展示 `draft / published / retired` 版本时间线;列表接口分页返回概要,选择版本时才读取完整快照,避免一次加载所有历史定义。 +- `GET /api/admin/shipping-order-schema/versions?page=1&page_size=20` 返回版本号、状态、字段数、变更说明、创建/发布人、时间和 checksum,不返回 `definition`。可加 `version_number=` 精确定位业务版本号,供 URL 恢复使用。 +- `GET /api/admin/shipping-order-schema/versions/{version_id}` 返回完整不可变 `definition`;历史详情只读取该快照,不回读当前字段目录,故后续 `field_code` 重命名不会污染 V1/V2 展示。 +- 管理端使用 `?version=<业务版本号>` 记录当前查看的历史版本;刷新后按版本号精确恢复。历史抽屉无编辑、删除或发布操作,关闭抽屉不会改变当前草稿编辑状态。 +- 版本概要和详情接口均要求管理员权限;创建人/发布人仅返回 `id` 和 `real_name || username`,不返回邮箱、手机号等敏感资料。 + +### 版本差异与配置审计时间线(阶段三) + +- `GET /api/admin/shipping-order-schema/versions/{version_id}/diff?against_version_id={id}` 在后端以稳定 `field_id` 比较任意两个同一 Schema 版本,返回新增、移除、修改、未变字段和属性级差异;`field_code` 重命名必须是一次 `modified`,不能误报为删除加新增。 +- 差异覆盖纳入状态、系统标识、显示名称、说明、必填、别名、文本处理、校验器、枚举、证据策略、关联角色、核对方式、识别说明和字段顺序。别名、校验器、枚举与证据来源同时返回新增/移除,以及“仅顺序变化”标记,前端不得自行用名称推断差异。 +- `GET /api/admin/shipping-order-schema/audit-events?page=1&page_size=20` 分页返回只追加的配置审计摘要;可附 `version_id` 过滤。接口仅返回事件类型、版本号、操作者安全展示信息、时间、请求 ID 和字段计数摘要,不向时间线输出完整前后快照。 +- 历史抽屉可将所选版本与当前草稿(无草稿时与当前发布版)进行只读比较,并展示审计时间线;任一历史版本、审计事件和比较结果均不提供就地编辑、发布或回滚操作。 + +### 版本运行追溯与历史复制(阶段四) + +- `GET /api/admin/shipping-order-schema/versions/{version_id}/usage?page=1&page_size=20` 返回实际使用该版本的 `ShippingOrderExtraction` 分页记录,以及总数、状态分布、首次/最近使用时间。查询使用 `(schema_version_id, created_at)` 索引,版本使用统计不得通过当前任务投影或当前字段目录反推。 +- `GET /api/admin/shipping-order-schema/order-extractions/{extraction_id}` 返回一条解析的只读证据链:锁定的 Schema 版本/完整定义、输入快照 hash 和冻结文档文本、LLM 原始结果、归一化和校验结果、Line、Observation、Decision、FieldValue 及逐字证据。字段身份来自当时版本快照,后续 `field_code` 或显示名修改不得污染审计展示。 +- 新创建的动态解析会在 `input_snapshot_json` 冻结参与裁决的 Document 文本和指纹;历史记录若产生于该列上线前,详情仅显示已保存 hash,并明确没有可用的输入快照。该列和版本使用复合索引由 `f99e4f5a6b7c` 迁移创建。 +- 管理员可从 `published` 或 `retired` 历史版本复制出独立新草稿;草稿不能作为复制来源,且历史版本永远不可直接编辑、发布或回滚。若已经存在草稿,创建请求明确冲突,不覆盖现有草稿。 +- **阶段四 Dify 配置结论**:无需修改 Dify 画布、Prompt 或重新导入 OpenAPI。Dify 继续提交既有动态字段候选和逐字证据;HXOPS 在后端冻结输入、原始提交、裁决和最终投影。 + +字段规则运行语义如下: + +| 管理项 | 版本定义字段 | 后端运行行为 | +|---|---|---| +| 别名、识别说明 | `aliases`、`extraction_instruction` | 写入 Dify 抽取契约,作为原文表头/语义提示,不直接产生最终值 | +| 业务必填、原文证据、单一来源 | `required`、`evidence_policy.required`、`allow_single_source` | 后端裁决 Observation 后校验缺失、证据与单来源门槛 | +| 文本处理、核对方式 | `normalizer_key`、`comparator_key` | 先规范化,再对 EML/附件 Observation 进行字段级比较 | +| 跨文档关联、冲突策略 | `relation_role`、`conflict_policy` | 关联字段用于证明文档归属;高可信冲突按策略阻断或进入复核 | +| 内容校验、可识别来源 | `validator_keys`、`source_precedence` | 仅允许受控校验器和来源;LLM 输出只能作为候选,不能绕过原文证据策略 | +| 变更说明 | `change_note` | 记录草稿/发布调整原因,供版本审计 | + +```text +GET /api/admin/shipping-order-schema +POST /api/admin/shipping-order-schema +POST /api/admin/shipping-order-schema/fields +PUT /api/admin/shipping-order-schema/fields/{field_id} +POST /api/admin/shipping-order-schema/versions +GET /api/admin/shipping-order-schema/versions/{version_id}/diff?against_version_id={id} +GET /api/admin/shipping-order-schema/versions/{version_id}/usage +PUT /api/admin/shipping-order-schema/versions/{version_id} +POST /api/admin/shipping-order-schema/versions/{version_id}/publish +GET /api/admin/shipping-order-schema/audit-events +GET /api/admin/shipping-order-schema/order-extractions/{extraction_id} +GET /api/admin/shipping-order-schema/published-contract +``` + +阶段二已将订单抽取主链切换为动态 Schema。`get_order_extraction_context.contract` 返回 `schema_version_id/checksum/fields[]`;Dify LLM 节点必须按该数组抽取,提交 `header_fields[]` 与 `lines[].fields[]`,每个字段包含稳定 `field_id` 和一个或多个 `observations[]`(`value/document_id/quote/confidence`)。Dify 不得提交自定义 field_code、决定最终值、决定库存源或绕过后端裁决。 + +#### Dify 手工配置步骤(阶段二) + +> **阶段一 Dify 变更结论**:无需修改 Dify 画布或重新导入 OpenAPI。管理员只需确认现有节点继续把 `get_order_extraction_context.contract` 中的 `schema_version_id`、`checksum` 和 `fields[]` 原样传回;未纳入当前版本的字段不会出现在 `fields[]`,不得由 Prompt 或 Code 节点自行补回。 + +1. Tool 节点先调用 `get_order_extraction_context`,把完整 `documents[]` 和 `contract` 传入 LLM 节点。 +2. LLM Prompt 明确:所有 EML 正文、PDF/Word 附件共享同一 `contract.fields[]`;逐 Document 提取 Observation,不得因文件类型改变字段集合。 +3. JSON 结构化节点输出订单级 `schema_version_id/schema_checksum/source_intake_no/primary_document_id/classification/classification_confidence/header_fields/lines/conflicts`。 +4. `header_fields[]` 与 `lines[].fields[]` 每项只允许 `{field_id, observations:[{value, document_id, quote, confidence}]}`;`quote` 必须逐字复制原文。 +5. Tool 节点调用 `submit_order_extraction`。若返回待审或冲突,Dify 只解释 HXOPS 结果,不自行选择某个 Observation。 + +后端会锁定 Schema 与输入快照,持久化 `ShippingOrderExtraction/Line/Observation/Decision/FieldValue`;相同值跨 EML/PDF 时标记 `corroborated`,可信冲突按字段 `conflict_policy` 阻断或复核。Candidate 和 Task 只消费 accepted/corroborated 的 field_code 投影。 + +### 动态订单字段驱动库存源路由(阶段三) + +- 订单业务条件保存 `order_field_id`,管理端只能从当前 published Schema 的 Header/Line 字段中选择;不再保存 `line.reservation_id` 等固定字符串路径。 +- 新 Schema 版本发布前反向检查 draft/published 路由规则、解析 Profile 与 Excel 模板;任何仍被引用字段都不能通过“取消勾选”绕过退役门禁。 +- Task 级规则只能选择 Header 字段,Line 级规则只能选择 Line 字段;字段退役、作用域不匹配或不存在时禁止保存规则。 +- 少量非订单系统事实仍使用受控 `system_fact_key`,与 `order_field_id` 数据库互斥;禁止任意模型路径。 +- 运行时按 `ShippingTask.current_order_extraction_id -> ShippingOrderFieldValue` 读取 accepted/corroborated 类型化值;行规则按 `ShippingOrderLine.position` 定位。 +- 规则发布快照保存稳定字段 ID,字段显示名修改不会改变路由语义;字段被新 Schema 版本移除后,既有已发布规则仍可审计,但新草稿必须重新选择 active 字段。 + +### 可复用库存解析 Profile(阶段四) + +#### 库存字段目录 + +- “库存字段目录”是“库存文件解析方案”内的子功能,不作为左侧独立业务入口。它独立于 DBS、Crane 和库存站点,统一维护跨文件复用的业务字段名称、说明、数据格式、用途和显示顺序。 +- 字段目录初始化为空,不预置内部料号、AWS 料号、ODM 编号、仓库编码、批次号、库位或任何其他具体字段。管理员自行创建全部字段;系统只提供“库存匹配、库存数量、仓库识别、一般业务信息”四种用途。 +- 解析 Profile 的 `field_mapping` 键、`match_keys[].inventory_field_id`、库存快照行 JSON 和发货模板 `source_kind=inventory_field` 的 `source_key` 均直接使用库存字段目录 ID。内部 `field_code` 只用于审计,不得参与解析、匹配、仓库识别或导出。 +- 发布解析方案必须至少映射一个“库存匹配”字段,且必须且只能映射一个“库存数量”字段;动态仓库存站点还必须且只能映射一个“仓库识别”字段。一般业务字段数量不限,可供发货模板输出。 + +- `ShippingInventoryParsingProfile` 独立于 RPA 登录 Profile 和 Inventory Source,使用 `draft -> published -> retired` 版本生命周期。 +- Profile 定义保存 `file_format/sheet_name/header_row_index/field_mapping/match_keys`;`field_mapping` 为 `inventory_field_id -> source_header`,`match_keys` 为稳定订单 `order_field_id -> inventory_field_id`,均不保存显示名称或原始表头以外的技术字段。 +- 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。 +- 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、少量样例、推断类型与空值率;页面只允许从分析结果选择工作表、表头和来源栏位。`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。 +- 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。 +- 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。 +- 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。 +- 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 +- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。 +- 正式单票和批量 RPA 回调在创建/链接快照后、进入解析前调用 `inventory_structure_drift.validate_production_inventory_structure`。它以已绑定 published Profile 的格式、**指定工作表和表头行**、方案实际映射栏位作确定性比较,绝不采用分析器自动挑选的其他工作表:`exact` 放行;仅非关键栏位差异为 `compatible`,放行并写入 `schema_preview_json.structure_validation`;无候选方案或格式不一致抛出 `SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED`,回滚本次快照。放行后 `ingest_inventory_file` 显式接收 Profile 的 `field_mapping / sheet_name / header_row_index`,不得使用自动表头建议。 +- 正式库存快照因缓存行缺失而需要重读时,只能调用 `parse_inventory_snapshot_file`,并从快照所属已启用库存站点读取 published Profile;正式解析 API 已删除外部栏位映射、LLM 匹配说明和自动猜列表头参数。仅临时会话和管理员样本分析可产生候选建议,且其结果不能写入正式快照或库存站点绑定。 +- 管理端接口为 `POST /api/admin/shipping-notice/sources/{id}/activate` 与 `POST /api/admin/shipping-notice/sources/{id}/deactivate`。普通 `POST/PUT /sources` 只维护基础配置,不承担启停状态切换,避免在编辑报表参数时误使站点进入正式运行。 +- 同编码新版本发布后不自动退役旧 published 版本;既有 Source 继续锁定原版本。管理员将全部 Source 显式迁移后,旧版本才允许退役。 +- `parse_linked_inventory_file` 未显式传入映射时,从快照的 `source_code` 找到 Source 和绑定 Profile,使用发布定义确定性解析;LLM 不参与正常库存源文件判断与映射。 +- 对话上传 `.xls/.xlsx/.csv` 且用户明确声明库存文件时,不会创建库存快照、不会自动确定库存源。后端先把它保存为当前用户和当前聊天会话隔离的“临时库存文件会话”,执行确定性结构初检;只有同时识别到料号和可用库存数量时,才作为库存候选交给后续受控映射建议流程。未知或不符合最低特征的文件明确拒绝,不能仅靠文件名或扩展名认定为库存文件。与之独立的任务级人工库存上传必须使用任务已确认库存站点绑定的 published 解析方案;结构一致后直接进入待匹配,结构漂移则完整回滚,不再产生任务级字段对齐确认。 +- 临时文件“库存候选分类”只使用受控表头特征阻止明显订单/未知表格,不能作为最终字段映射;最终映射仍保存库存字段目录 ID,并在确认质量检查时按字段的匹配标识/库存数量用途解析,避免把可配置字段错误退化为固定技术编码。 + +发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改,`field_code` 重命名仅影响后续草稿,历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。 # 发货 Excel 模板 -FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx -# 字段对齐确认 -# SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true +- 模板在“货代配置 → 发货模板”独立维护,状态为 `draft / published / retired`;库存站点只能绑定 published 版本。 +- 定义契约为 `filename_pattern + mappings[]`。每条 mapping 包含 `sheet`、`row_mode(header|line)`、`start_row`、`target_column`、`source_kind`、`source_key`、`formatter`。管理端上传模板时读取工作表与首行表头,管理员从实际工作表和目标列中选择,不要求记忆列序号。 +- 文件名规则默认推荐 `{business_no}.xlsx`(例如 `WYC26060201.xlsx`)。可用变量必须在界面显式展示:`{business_no}`、`{customer_short_code}`、`{business_date}`(六位)、`{sequence}`(两位)、`{task_no}`、`{source_code}`、`{date}`(八位)、`{ts}`。业务单相关变量只读取 `ShippingCase` 已锁定的客户简称、业务日期和流水快照,保证重新导出与历史审计一致。 +- 管理端使用结构化映射行;`source_kind`、订单字段、库存标准字段、系统事实、row mode 与 formatter 均来自后端受控目录,只有常量值和模板坐标允许自由输入。 +- `source_kind=order_field` 时 `source_key` 必须为当前已发布订单模板中的稳定 `order_field_id`。订单头区域只能引用订单信息字段;货品明细区域可引用货品明细字段,也可把订单信息字段重复写入每条明细。另允许标准 `inventory_field`、白名单 `system_fact` 和常量。 +- 系统事实 `export_date` 按 `Asia/Shanghai` 获取实际导出日期,并由 `date_mmddyyyy` 格式化为 `MM/DD/YYYY`;它不依赖服务器所在时区。 +- 发布时后端验证实际 Sheet、目标列冲突、字段有效性、格式化器和文件 checksum;发布后文件与定义不可变。管理端可点击“创建新版本”直接复制对象存储中的原 Excel 和映射定义创建草稿,不要求重新上传;只有 Excel 工作表、表头或版式发生变化时,才在草稿中替换模板文件。 +- 模板原文件上传到平台私有 MinIO,数据库仅保存 provider/bucket/key 与 checksum;禁止本地模板静默 fallback。上传时验证真实 xlsx 和大小,事务失败补偿删除对象。 +- 生成时按 `task.inventory_source_code -> Inventory Source -> published Excel Template` 唯一确定模板,不再使用全局环境变量或空白工作簿 fallback。 +- Inventory Source 可先以 `enabled=false` 保存基础配置;启用前必须同时绑定 published 解析 Profile 与 published Excel Template。禁用 Source 的既有绑定同样必须先显式迁移,才能退役 Profile 或模板。 +- 生成前使用解析 Profile `match_keys[]` 按稳定订单 `field_id -> inventory_field_id` 匹配库存行,订单和库存两侧均直接按字段 ID 取值;禁止按字段名称或数组顺序配对。零命中或模板所需库存字段冲突时阻断;模板引用库存字段必须存在于库存站点已绑定解析方案的 `field_mapping`。 +- 每次生成新增 `ShippingExportArtifact`,锁定模板、订单 Schema/Extraction、库存解析 Profile、库存快照、输入 checksum、文件 checksum 和大小;新生成会 supersede 旧产物,下载只解析仍与 Task 当前导出引用一致的 ready Artifact。 +- Dify 不选择模板、不传映射,仅在后端门禁允许时调用 `generate_shipment_excel`。 + +### AWS PVMI 发货模板 V1(草稿) + +- 模板编码为 `AWS_PVMI_PULL_REQUEST`,显示名称为“AWS PVMI 发货模板”,文件名规则为 `{business_no}.xlsx`;当前仅回写为草稿,未发布、未绑定库存站点。 +- `PVMI Pull Request Header` 从第 4 行写入:Warehouse ID=`warehouse_id`,Order Type=`n`,Supplier ID=`WEL`,Priority=`normal`,Request Delivery Date=`export_date`,Ship to ODM Code=`odm_id`,Pull Request Number=`business_no`。 +- `PVMI Pull Request Detail` 从第 4 行逐条写入:Pull Request Number=`business_no`,Pull Request Line Number=`line_no`,AWS Part Number=`aws_part_number`,Supplier Part Number=`part_number`,Order Qty=`qty`,AWS Reference Number=`reservation_id`,ODM PO Number=`po_number`,Shipment Value=`amount`,Shipment Value Currency Code=`currency`。 +- `po_number` 属于订单信息字段,但按业务文件要求重复写入每条货品明细;模板文件只保留格式、说明和表头,不保留旧样例业务数据。 + +### 批次 ZIP 下载 + +- Workspace 调用 `POST /api/workspace/shipping-exports/archive`,请求体二选一:`{"batch_no":"..."}` 或 `{"task_nos":["..."]}`;Dify 不参与此下载接口。 +- 工作台提供“下载本批次 ZIP”和任务列表显式多选两种入口;多选可全选当前查询结果、显示选择数量,并在刷新或切换筛选后剔除不可见任务。 +- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。 +- 每票只选择最新且仍与 Task 当前导出路径一致的 `status=ready` Artifact,并在打包前复算 SHA-256;任务纠错清空引用、文件缺失或校验失败均不进入 ZIP 文件区,但必须进入 `manifest.json`。 +- manifest 状态为 `included / missing_artifact / missing_file / checksum_mismatch`;同名文件保留首个,其余追加 `task_no`,禁止覆盖。 +- ZIP 使用 `SpooledTemporaryFile`:小文件在内存,超过 16 MiB 自动落临时磁盘,由响应结束后释放。 # 自动推进 / 自动上传 # SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true # SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -# SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true # SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true # SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true # 真实货代上传 RPA 尚未完成,默认 false;仅 mock 或已接入正式上传 Driver 后再开启。 @@ -366,7 +513,7 @@ python seed_shipping_notice_agents.py ```powershell $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" -$env:FREIGHT_RPA_MOCK = "true" +$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" python scripts/rpa/freight_rpa_worker.py ``` @@ -438,9 +585,7 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { scripts\rpa\freight_rpa_worker.py scripts\rpa\dsv_report_parameters.py scripts\rpa\dsv_login_smoke.py -scripts\rpa\dsv_export_smoke.py -scripts\rpa\dsv_export_batch_smoke.py -backend\config\shipping_inventory_sources.yaml +scripts\rpa\run_inventory_batch_trigger.py ``` 放置为: @@ -449,16 +594,12 @@ backend\config\shipping_inventory_sources.yaml C:\HxopsRpaTest\scripts\rpa\freight_rpa_worker.py C:\HxopsRpaTest\scripts\rpa\dsv_report_parameters.py C:\HxopsRpaTest\scripts\rpa\dsv_login_smoke.py -C:\HxopsRpaTest\scripts\rpa\dsv_export_smoke.py -C:\HxopsRpaTest\scripts\rpa\dsv_export_batch_smoke.py -C:\HxopsRpaTest\backend\config\shipping_inventory_sources.yaml +C:\HxopsRpaTest\scripts\rpa\run_inventory_batch_trigger.py C:\HxopsRpaProd\scripts\rpa\freight_rpa_worker.py C:\HxopsRpaProd\scripts\rpa\dsv_report_parameters.py C:\HxopsRpaProd\scripts\rpa\dsv_login_smoke.py -C:\HxopsRpaProd\scripts\rpa\dsv_export_smoke.py -C:\HxopsRpaProd\scripts\rpa\dsv_export_batch_smoke.py -C:\HxopsRpaProd\backend\config\shipping_inventory_sources.yaml +C:\HxopsRpaProd\scripts\rpa\run_inventory_batch_trigger.py ``` 不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。 @@ -505,45 +646,52 @@ python -m pip install playwright openpyxl pyyaml python -m playwright install chromium ``` -若使用本机 Edge 浏览器,worker 可配置 `FREIGHT_RPA_BROWSER_CHANNEL=msedge`。 +若使用本机 Edge 浏览器,worker 可配置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`。 #### 1.5.5 Windows RPA 主机:临时环境变量与登录测试 先在 PowerShell 当前窗口配置临时环境变量,确认链路可用后再改成永久环境变量: +> `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 是 RPA Profile 凭据的 Fernet 主密钥。 +> Windows Worker 与对应 test/prod 后端必须使用同一个值,否则 Worker 无法解密 +> 后端下发的 Profile 密文。该值必须从 Jenkins/Secret 管理器或受控运维渠道注入, +> 禁止写入仓库、命令历史、截图或日志。 + ```powershell cd C:\HxopsRpaTest $env:HXOPS_API_BASE = "http://测试后端地址:端口" $env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOOL_API_KEY" +# SHIPPING_NOTICE_RPA_CREDENTIAL_KEY 由受控 Secret 工具注入当前进程; +# 手工部署请直接使用下方 set_rpa_worker_env.ps1 的安全交互输入。 -$env:FREIGHT_RPA_MOCK = "false" -$env:FREIGHT_RPA_HEADLESS = "false" -$env:FREIGHT_RPA_BROWSER_CHANNEL = "msedge" -$env:FREIGHT_RPA_POLL_SECONDS = "3" +$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" +$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" +$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge" +$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" -$env:FREIGHT_RPA_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers" -$env:FREIGHT_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop" -$env:FREIGHT_RPA_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers" -$env:FREIGHT_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue" -$env:FREIGHT_RPA_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile" -$env:FREIGHT_RPA_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" -$env:FREIGHT_RPA_LOG_MAX_BYTES = "10485760" -$env:FREIGHT_RPA_LOG_BACKUP_COUNT = "5" +$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers" +$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop" +$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers" +$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue" +$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile" +$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" +$env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" +$env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" -$env:FREIGHT_RPA_DSV_USERNAME = "请替换为DSV账号" -$env:FREIGHT_RPA_DSV_PASSWORD = "请替换为DSV密码" +$env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" +$env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" -$env:FREIGHT_RPA_CRANE_USERNAME = "请替换为Crane账号" -$env:FREIGHT_RPA_CRANE_PASSWORD = "请替换为Crane密码" +$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "请替换为Crane账号" +$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码" # 心跳与共享 scope(test/prod 必填;与 Ubuntu SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致) -$env:FREIGHT_RPA_ENVIRONMENT = "test" -$env:FREIGHT_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data" -$env:FREIGHT_RPA_HEARTBEAT_SECONDS = "20" +$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "test" +$env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data" +$env:SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20" ``` -正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,`FREIGHT_RPA_ENVIRONMENT` 改为 `prod`,`FREIGHT_RPA_SHARED_SCOPE_ID` 改为 `hxops-rpa-prod-data`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。 +正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` 改为 `prod`,`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 改为 `hxops-rpa-prod-data`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。 也可使用仓库脚本一次性写入用户级永久变量(推荐): @@ -552,16 +700,49 @@ cd C:\HxopsRpaTest .\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://测试后端:端口" -ToolApiKey "<与后端一致的密钥>" ``` +脚本会交互式安全提示输入 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`,不会把该主密钥 +放进命令行历史或输出到控制台。后端侧必须通过 Jenkins/CI、Docker Secret 或系统 +环境变量注入同一值;`.env.shared` 只保留空占位。 + +#### 1.5.5b RPA 环境变量命名迁移 + +新部署只允许使用统一命名空间。旧名称在当前版本仅作为 fallback,全部环境迁移完成后将删除兼容读取。 + +| 历史名称 | 规范名称 | +| --- | --- | +| `SHIPPING_RPA_CREDENTIAL_KEY` | `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` | +| `FREIGHT_INVENTORY_DROP_DIR` | `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR` | +| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR` | +| `FREIGHT_UPLOAD_QUEUE_DIR` | `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR` | +| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR` | +| `FREIGHT_RPA_SHARED_SCOPE_ID` | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | +| `FREIGHT_RPA_<配置项>` | `SHIPPING_NOTICE_RPA_WORKER_<配置项>` | + +迁移步骤:先运行新版 `set_rpa_worker_env.ps1` 写入新变量,重启 PowerShell/计划任务并完成 +心跳、哨兵及真实库存导出验证;确认稳定后再清理 Windows 用户级旧变量: + +```powershell +[Environment]::GetEnvironmentVariables("User").Keys | + Where-Object { $_ -like "FREIGHT_RPA_*" -or $_ -in @( + "FREIGHT_INVENTORY_DROP_DIR", + "FREIGHT_UPLOAD_QUEUE_DIR", + "SHIPPING_RPA_CREDENTIAL_KEY" + ) } | + ForEach-Object { [Environment]::SetEnvironmentVariable([string]$_, $null, "User") } +``` + +清理前不得跳过验证;旧变量删除后需要重新打开 PowerShell,并再次确认 Worker 启动、心跳和库存导出正常。 + #### 1.5.5a RPA Worker 心跳、共享 scope 与哨兵 -test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`FREIGHT_RPA_INVENTORY_TRIGGER_DIR`,如 `...\inventory_triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME` 覆盖)。 +test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR`,如 `...\inventory_triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME` 覆盖)。 | 侧 | 变量 | 测试示例 | 正式示例 | | --- | --- | --- | --- | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | -| Windows RPA | `FREIGHT_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | -| Windows RPA | `FREIGHT_RPA_ENVIRONMENT` | `test` | `prod` | -| Windows RPA | `FREIGHT_RPA_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | +| Windows RPA | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | +| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` | `prod` | +| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` | @@ -571,7 +752,7 @@ test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是 **多进程去重**:告警冷却状态以 `app_settings` 为权威源,Redis 仅作缓存同步;DB 不可读写时才回退 Redis/进程内内存 claim。 -**为何必须显式配置 scope**:Windows 标准路径 `C:\HxopsRpaTest\data\...` 不含 `hxops-rpa-test-data` 字样,后端无法从路径推导 scope;漏配 `FREIGHT_RPA_SHARED_SCOPE_ID` 时 Worker 不写哨兵,就绪检查报 `shared_sentinel_missing`。 +**为何必须显式配置 scope**:Windows 标准路径 `C:\HxopsRpaTest\data\...` 不含 `hxops-rpa-test-data` 字样,后端无法从路径推导 scope;漏配 `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 时 Worker 不写哨兵,就绪检查报 `shared_sentinel_missing`。 Worker 启动后验证哨兵(测试环境示例): @@ -601,32 +782,13 @@ python scripts\rpa\dsv_login_smoke.py SUCCESS — DSV session ready ``` -再验证单个库存源导出: +库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行: ```powershell -python scripts\rpa\dsv_export_smoke.py DSV360_AWSBI_BYAWSCMH01 +python scripts\rpa\run_inventory_batch_trigger.py ``` -可选:验证 DSV **批量**导出链路(一次登录连续多仓,不回调后端): - -```powershell -python scripts\rpa\dsv_export_batch_smoke.py warehouse -python scripts\rpa\dsv_export_batch_smoke.py source_code -python scripts\rpa\dsv_export_batch_smoke.py all -``` - -batch smoke **默认语义**:链路跑完即通过(退出码 0),**全 skipped(确认无库存、未导出 Excel)也算通过**。 - -若 CI 或联调需要“至少真实导出一个 Excel”,启用严格模式: - -```powershell -$env:FREIGHT_RPA_SMOKE_REQUIRE_EXPORT = "true" -python scripts\rpa\dsv_export_batch_smoke.py warehouse -``` - -| 环境变量 | 默认值 | 说明 | -| --- | --- | --- | -| `FREIGHT_RPA_SMOKE_REQUIRE_EXPORT` | `false` | 为 `true` 时要求至少一条 `success` 导出;全 skipped 时退出码 **2** | +该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。 如果登录或导出失败,先排查 Windows 主机是否能手工打开 DSV/Crane、账号密码是否正确、是否需要 MFA/验证码/SSO、公司代理和证书是否正常。 @@ -768,12 +930,12 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers -FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers -FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers +SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers +SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue -# Worker 心跳与共享 scope(与 Windows FREIGHT_RPA_SHARED_SCOPE_ID 一致) +# Worker 心跳与共享 scope(与 Windows SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致) SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true @@ -809,27 +971,29 @@ volumes: [Environment]::SetEnvironmentVariable("HXOPS_API_BASE", "http://192.168.1.20:8890", "User") [Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_TOOL_API_KEY", "请替换为与后端一致的ASCII密钥", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_MOCK", "false", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_HEADLESS", "false", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_BROWSER_CHANNEL", "msedge", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_POLL_SECONDS", "3", "User") +# 凭据主密钥不要以内联明文命令设置;优先使用 set_rpa_worker_env.ps1 的安全交互输入。 -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "C:\HxopsRpaTest\data\inventory_triggers", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_INVENTORY_DROP_DIR", "C:\HxopsRpaTest\data\inventory_drop", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "C:\HxopsRpaTest\data\upload_triggers", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_UPLOAD_QUEUE_DIR", "C:\HxopsRpaTest\data\upload_queue", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_BROWSER_PROFILE_DIR", "C:\HxopsRpaTest\data\browser_profile", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_LOG_FILE", "C:\HxopsRpaTest\data\logs\worker.log", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_LOG_MAX_BYTES", "10485760", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_LOG_BACKUP_COUNT", "5", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS", "3", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_DSV_USERNAME", "请替换为DSV账号", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_DSV_PASSWORD", "请替换为DSV密码", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", "C:\HxopsRpaTest\data\inventory_triggers", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR", "C:\HxopsRpaTest\data\inventory_drop", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR", "C:\HxopsRpaTest\data\upload_triggers", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR", "C:\HxopsRpaTest\data\upload_queue", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "C:\HxopsRpaTest\data\browser_profile", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", "C:\HxopsRpaTest\data\logs\worker.log", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10485760", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "5", "User") + +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "请替换为DSV账号", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "请替换为DSV密码", "User") # 心跳与共享 scope(test 示例;正式改为 prod + hxops-rpa-prod-data + C:\HxopsRpaProd\...) -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_ENVIRONMENT", "test", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data", "User") -[Environment]::SetEnvironmentVariable("FREIGHT_RPA_HEARTBEAT_SECONDS", "20", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT", "test", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data", "User") +[Environment]::SetEnvironmentVariable("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20", "User") ``` 或使用脚本(参数按实际后端地址与密钥填写): @@ -839,15 +1003,17 @@ cd C:\HxopsRpaTest .\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://192.168.1.20:8890" -ToolApiKey "<密钥>" ``` +脚本随后会安全提示输入与 test 后端一致的 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。 + 以上写法适合只常驻一个 worker。若同一台 Windows 主机要同时常驻测试与正式,建议不要依赖用户级环境变量,而是分别准备两个启动脚本或任务计划,确保每个任务内显式设置各自的目录、API Base、scope 与 Key。 关闭并重新打开 PowerShell 后检查: ```powershell echo $env:HXOPS_API_BASE -echo $env:FREIGHT_RPA_INVENTORY_TRIGGER_DIR -echo $env:FREIGHT_RPA_SHARED_SCOPE_ID -echo $env:FREIGHT_RPA_ENVIRONMENT +echo $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR +echo $env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID +echo $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT ``` 确认 worker 可手动启动: @@ -862,8 +1028,8 @@ python scripts\rpa\freight_rpa_worker.py 日志默认按大小轮转,避免单个文件长期膨胀: ```text -FREIGHT_RPA_LOG_MAX_BYTES=10485760 # 单个 worker.log 最大 10MB;设为 0 可禁用轮转 -FREIGHT_RPA_LOG_BACKUP_COUNT=5 # 最多保留 worker.log.1 到 worker.log.5 +SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760 # 单个 worker.log 最大 10MB;设为 0 可禁用轮转 +SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5 # 最多保留 worker.log.1 到 worker.log.5 ``` 确认可用后再创建任务计划。先查 Python 路径: @@ -895,7 +1061,7 @@ Register-ScheduledTask ` 1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 2. Windows 执行 `python scripts\rpa\dsv_login_smoke.py`。 -3. Windows 执行 `python scripts\rpa\dsv_export_smoke.py DSV360_AWSBI_BYAWSATL01`。 +3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。 4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。 5. Windows 启动 `python scripts\rpa\freight_rpa_worker.py`。 6. 确认哨兵:`Get-Content C:\HxopsRpaTest\data\inventory_triggers\.hxops_rpa_shared_mount` 含正确 `scope_id`。 @@ -909,7 +1075,7 @@ Register-ScheduledTask ` #### 1.5.12 常见问题 - Ubuntu `smbclient` 能访问,但后端写失败:用 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test.txt` 测试后端服务用户权限,检查挂载参数中的 `uid/gid` 与 Windows 共享/NTFS 权限。 -- Windows worker 没反应:确认 worker 正在运行,测试环境 `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\inventory_triggers`,正式环境指向 `C:\HxopsRpaProd\data\inventory_triggers`,且后端真的把 JSON 写到了对应共享目录。 +- Windows worker 没反应:确认 worker 正在运行,测试环境 `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\inventory_triggers`,正式环境指向 `C:\HxopsRpaProd\data\inventory_triggers`,且后端真的把 JSON 写到了对应共享目录。 - worker 回调失败:确认 Windows 能访问 `HXOPS_API_BASE`,`SHIPPING_NOTICE_TOOL_API_KEY` 与后端一致,Ubuntu 防火墙允许 Windows 访问 HXOPS 端口。 - DSV/Crane 登录失败:先用 Windows Edge 手工登录,再跑 `dsv_login_smoke.py`;重点检查 MFA/验证码/SSO、企业代理、证书、账号密码。 - Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。 @@ -967,13 +1133,17 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv 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` +8. `create_temporary_inventory_session`(用户明确声明后的临时分析) +9. `get_temporary_inventory_session`(用户明确声明后的临时分析) +10. `submit_temporary_inventory_mapping_suggestion`(用户明确声明后的临时分析) +11. `confirm_temporary_inventory_use`(用户明确确认后的临时分析) +12. `submit_decision` +13. `get_task_status` +14. `get_batch_status` -当前 Dify 正式职责包括:读取上传预处理结果、完整理解一封或多封邮件中的 `orders[]`、提交订单抽取结果、通知解析、字段修订、库存映射建议、人工决策提交、任务/批次状态查询与用户解释。Dify 不直接写 HXOPS 数据库;Candidate 判重、自动建 Batch/Task 与状态推进均由 HXOPS Tool 或 worker 完成。 +任务级 `get_inventory_schema_preview` 与 `apply_inventory_mapping` 已移除;任务级人工上传通过宿主 Chat Turn 进入 published 解析方案的确定性结构校验,成功后直接进入待匹配。陌生表头的解析方案沉淀仅能走受控临时会话。 + +当前 Dify 正式职责包括:读取上传预处理结果、完整理解一封或多封邮件中的 `orders[]`、提交订单抽取结果、通知解析、字段修订、人工决策提交、任务/批次状态查询与用户解释。正式库存源及任务级人工上传均使用已发布解析 Profile 确定性解析,不调用 Dify 判断列映射。用户明确声明对话附件为库存文件且后端无精确方案时,Dify 可基于脱敏真实表头返回本次临时候选;管理员也可在库存文件解析方案草稿中显式请求同类候选。旧 `map_json` 正式库存流程保持关闭。Dify 不直接写 HXOPS 数据库;Candidate 判重、自动建 Batch/Task 与状态推进均由 HXOPS Tool 或 worker 完成。 当前后端 worker 主职责包括:批次派发、自动续跑、库存准备、匹配、生成 Excel、上传货代与 RPA 回写。 ### 2.2.1 编排职责边界 @@ -987,8 +1157,9 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv | 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`;完整库存解析写入批次库存快照,字段对齐确认后本批各票独立匹配 | +| 正式库存源文件解析 | Hxops 后端 | 按库存源绑定的 published 解析 Profile 读取表头、标准字段与 `match_keys`;不得调用 LLM 猜测列映射 | +| 陌生库存表头候选解释 | Dify 兜底 | 用户明确声明的临时库存分支无精确方案时,或管理员从库存文件解析方案草稿显式发起;输入仅含真实表头、列类型/空值率和允许目标字段,输出候选及理由,不能输出发布/绑定决定 | +| 采用库存字段映射 | Hxops 管理端 | 管理员在结构化下拉框中选择已分析栏位,后端验证后保存草稿;Dify 不提交 `map_json`,不解析正式库存快照 | | 主状态机、checkpoint、人审门 | Hxops 后端 | `checkpoint` / `human_options` / `forbidden_next_tools` 以状态机为准;Dify 只能读取并遵守 | | 匹配、生成 Excel、上传货代、RPA 重试 | Hxops worker / RPA workflow | 属于长链路、有副作用、需幂等与重试的生产职责,不由 Dify 同轮串行主导 | | 任务解释、下一步建议、人工确认收口 | Dify + `submit_decision` | Dify 负责把后端状态翻译成用户可执行动作;真正状态推进交给 `submit_decision` 与 worker | @@ -1000,11 +1171,11 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv 1. **先做能力路由**:`parse_agent_runtime_context` 读取 `refs.capability / refs.intake_nos`;命中 `order_extraction` 时,必须先走固定订单抽取分支并在该分支结束本轮。 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 链。 +3. **读取真相源**:凡属“继续处理 / 切换任务 / 询问当前状态 / 确认或驳回当前步骤”,优先调用 `get_task_status`;用户明确声明的新临时库存文件只走 `temporary_inventory_new`,跨回合明确确认只走 `temporary_inventory_confirm`,两者均不进入任务状态机。 +4. **优先直连确定性动作**:`confirm / reject / reparse / retry_rpa / rematch` 必须先走直连 Tool,不先进入 Agent 自由推理。 +5. **仅在固定窗口调用重工具**:`get_order_extraction_context / submit_order_extraction` 仅允许出现在 `order_extraction_path`;`parse_notice` 仅允许出现在已建 Task 的“通知待解析”链;临时映射建议只能在 `temporary_inventory_new` 调用,临时确认只能在 `temporary_inventory_confirm` 调用。 6. **遇到人工门立即停下**:返回 `needs_human`、`stop_agent_turn=true` 或 `forbidden_next_tools` 时,本轮结束;Dify 只展示 `message / parse_msg / align_msg` 并等待用户。 -7. **副作用长链路交回后端**:确认字段对齐后,后续匹配、Excel、上传由后端 worker 自动续跑;Dify 在下一轮通过 `get_task_status` 解释结果,而不是继续串调用多个 Tool。 +7. **副作用长链路交回后端**:库存站点按 published 方案确定性解析后,后续匹配、Excel、上传由后端 worker 自动续跑;Dify 在下一轮通过 `get_task_status` 解释结果,而不是继续串调用多个 Tool。 #### 回合收口规则 @@ -1014,7 +1185,6 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv | `status=needs_human` | 原文展示 `message`,结合 `human_options` 引导用户选择 | 自作主张替用户确认 | | `stop_agent_turn=true` | 立刻结束本轮 | 继续追调下一个 Tool | | `forbidden_next_tools` 非空 | 视为硬门禁,禁止调用列出的 Tool | 忽略门禁继续匹配 / 生成 Excel / 上传 | -| `checkpoint=align_review` | 展示字段对齐结果,等待 `confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory` | 直接进入匹配 | | shortage / 匹配不全满足 | 停留在步骤 5,提示补库存 / 返回修订 / 重新匹配 / 驳回 | 生成 Excel、上传货代、暗示可带缺口继续发货 | ### 2.2.3 多任务与互斥规则 @@ -1049,13 +1219,14 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv 主编排分为两层路由: -1. `顶层能力路由`:只判断平台显式注入的能力契约,决定 `order_extraction_path / normal_path`。 -2. `主路由分支节点`:仅在 `normal_path` 内继续判断 `inventory_path / agent_path / direct_answer`。 +1. `临时库存续办意图判断 + 顶层能力路由`:订单抽取与新库存文件由平台显式能力契约决定;跨回合临时库存确认由“数据库恢复会话号 + 用户明确确认”共同决定,输出 `order_extraction_path / temporary_inventory_new / temporary_inventory_confirm / normal_path`。 +2. `主路由分支节点`:仅在 `normal_path` 内继续判断 `agent_path / direct_answer`;普通附件不进入库存解析。 ```text 开始 -> Tool 解析运行态上下文 -> 运行态上下文标准化 +-> 临时库存续办意图判断 -> 顶层能力路由 ├─ order_extraction_path │ -> Tool 读取订单抽取上下文 @@ -1073,12 +1244,21 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv │ -> 提交结果是否有效 │ ├─ false -> 订单抽取提交失败回复 -> 结束 │ └─ true -> 订单抽取结果回复 -> 结束 + ├─ temporary_inventory_new(用户明确声明新文件为库存) + │ -> 创建临时库存候选会话 + │ -> 临时库存分析结果标准化(Tool text JSON) + │ -> exact 则展示复用建议;否则陌生表头候选解释 LLM + │ -> 提交临时映射建议 -> 标准化 -> 结束 + ├─ temporary_inventory_confirm(下一轮明确确认) + │ -> 读取临时库存分析 + │ -> 临时库存分析结果标准化(Tool text JSON) + │ -> 待确认状态校验 + │ -> 确认临时库存使用 -> 标准化 -> 结束 └─ normal_path -> 用户意图预处理 -> 附件意图分类 -> 分支调度 -> 主路由分支节点 - ├─ inventory_path ├─ agent_path └─ direct_answer ``` @@ -1087,7 +1267,7 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv | 阶段 | 输入 | 输出 | 真相源 / 约束 | | --- | --- | --- | --- | -| 顶层能力识别 | `agent_runtime_context` | `capability`、`intake_nos_json` | 只读取 `parse_agent_runtime_context` 结果,不分析用户文案 | +| 顶层能力识别 | `agent_runtime_context`、`sys.query` | `capability`、`temporary_route`、`intake_nos_json` | 订单抽取/新文件只读平台能力;只有已有待确认会话时才对明确确认话术做受控判断 | | 抽取上下文读取 | 原样 `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[]`,不判重、不建单、不推进任务 | @@ -1206,17 +1386,24 @@ normal_path: -> 分支调度 -> 主路由分支节点 -inventory_path: - 库存任务检查 - -> 是否已有库存绑定任务 - -> Tool 读取库存 schema 预览 - -> 库存 schema 标准化 - -> 库存列映射 LLM - -> 列映射 JSON 标准化 - -> Tool 应用库存列映射 - -> 映射结果标准化 - -> Agent 状态输入标准化 - -> 货代续办 Agent +temporary_inventory_new / temporary_inventory_confirm(用户明确声明后的临时分析与跨回合确认): + 新文件:Tool 创建临时库存候选会话 + 续办确认:Tool 读取临时库存分析 + -> 临时库存分析结果标准化(统一解析 Tool text JSON) + -> (exact)展示可复用解析方案并等待用户确认 + -> (无 exact)陌生表头候选解释 LLM + -> Tool 提交临时映射建议 + -> 临时映射建议结果标准化 + -> 展示待确认结果并结束 + -> 用户下一轮明确确认 + -> Tool 确认临时库存使用 + -> 临时库存确认结果标准化 + -> 展示质量校验结果并结束 + +正式库存站点: + RPA / 管理端上传快照 + -> Hxops 后端按库存站点绑定的 published 解析方案确定性解析 + -> 不经过 Dify agent_path: 准备读取任务状态 @@ -1252,7 +1439,7 @@ agent_path: ```text 我是货代发货通知助手。请在 Hxops 聊天区上传发货通知 PDF/Word,或直接发送任务编号 SN-... 继续处理当前任务。 -库存 Excel 也请在对话区上传;我会结合后端状态继续引导字段确认、库存映射建议、匹配结果解释,以及后续步骤确认。 +正式库存文件优先由库存源配置通过 RPA 导出;已有任务也可使用“选择库存文件”进行受控人工上传,后端按该任务库存站点的发布方案校验并解析。普通对话附件若要进行临时库存分析,用户必须明确声明库存用途;该临时链不进入任务快照或库存匹配。我会结合后端状态继续引导匹配结果解释和后续步骤确认。 ``` ##### Suggested Questions @@ -1274,7 +1461,7 @@ agent_path: 说明: -- 当前保持 `enabled=true`,是为了让嵌入式聊天态把附件透传为 `sys.files`,供 `附件意图分类` 节点识别库存附件与通知附件。 +- 当前保持 `enabled=true`,是为了让嵌入式聊天态把附件透传为 `sys.files`,供 `附件意图分类` 节点识别通知附件,并拦截普通会话中的库存附件。 - 通知原文件由 HXOPS 上传预处理,不依赖 Dify `sys.files`;用户点击发送后,HXOPS 通过 `agent_runtime_context.refs.intake_nos` 触发现有 Chatflow 的固定订单抽取分支,最终建单仍由 HXOPS Tool 完成。 - 若宿主前端已经完全接管附件上传,且不会向 Dify 透传 `sys.files`,则应关闭 Dify 原生 File Upload,并同步移除本文档中依赖 `sys.files` 的附件分流配置。 @@ -1324,7 +1511,7 @@ agent_path: - Dify 画布只读取 `agent_runtime_context`,不依赖 `conversation.current_*` 私有变量。 - Start 节点只保留 `agent_runtime_context`,不得再新增或保留 `hxops_context`。 -- 业务对象锚点统一放在 `agent_runtime_context.refs`,字段名使用统一协议:`task_no`、`batch_no`、`run_purpose`。 +- 业务对象锚点统一放在 `agent_runtime_context.refs`,字段名使用统一协议:`task_no`、`batch_no`、`run_purpose`。对话临时库存分支额外只传递 `temporary_inventory_asset_no` 和后续 Tool 返回的 `temporary_inventory_session_no`;它们不是文件路径、二进制或库存明细。 - 模糊指代统一通过 `reference_context` 读取,不允许仅靠对话记忆猜测对象。 - `domain.state_hint` 和 `reference_context` 都只是现场提示,不是业务事实源;`checkpoint / human_options / forbidden_next_tools` 仍以 Tool 返回为准。 - 推荐给 `parse_agent_runtime_context` 的常用 paths: @@ -1336,6 +1523,49 @@ agent_path: - `refs.batch_no` - `domain.state_hint.status` +#### 2.4.3.1 对话临时库存文件(阶段一,Dify 由管理员手工配置) + +> 适用范围:用户在货代对话中上传 `.xls` / `.xlsx` / `.csv`,并明确说明该附件是库存文件。表格扩展名不是业务分类依据;用户未声明时前端只保留附件并提示澄清,绝不猜测它是库存或订单。此分支与已启用库存站点的 RPA 正式库存链路完全隔离。 + +前端仅在用户明确声明库存文件后,将文件上传为当前用户私有 `FileAsset`,再以 `capability=temporary_inventory`、`refs.temporary_inventory_asset_no` 发起本轮 Chatflow。HXOPS 后端会在后续聊天回合从数据库恢复当前会话最新、未过期且仍待确认的 `refs.temporary_inventory_session_no`;该锚点不会自动把普通消息改成库存操作,Dify 仍须先判断用户是否明确确认。Dify 必须按以下顺序编排: + +1. 在“运行态上下文标准化”节点增加 `temporary_inventory_asset_no`、`temporary_inventory_session_no` 和 `capability` 输出;从 `parse_agent_runtime_context` 读取 `refs.capability`、`refs.temporary_inventory_asset_no`、`refs.temporary_inventory_session_no`。 +2. 在“顶层能力路由”中增加 `temporary_inventory_new` 与 `temporary_inventory_confirm`:当 `capability == "temporary_inventory"` 且 asset 编号非空时进入新文件分支;当数据库恢复会话号且用户明确确认时进入确认分支;两者均不得进入普通会话任务状态机。 +3. 在顶层路由前增加“临时库存续办意图判断” Code 节点:只有 `temporary_inventory_session_no` 非空且用户明确表达“确认本次临时使用/采用该方案”时,才输出 `temporary_route=confirm_pending` 和 `confirmation_intent=true`。普通问答、订单操作、含糊的“继续”不得命中。 +4. 新建 Tool 节点“创建临时库存候选会话”,调用 `create_temporary_inventory_session(agent_runtime_context, asset_no)`。`asset_no` 必须直接取运行态上下文中的编号,禁止让 LLM 编造、改写或从用户文本猜测。 +5. 新建 Tool 节点“读取临时库存分析”,在跨回合明确确认时调用 `get_temporary_inventory_session(agent_runtime_context, temporary_session_no)`;会话号直接取运行态上下文恢复值。 +6. 两个 Tool 后必须进入同一个“临时库存分析结果标准化” Code 节点,输入为 Tool 的 `text` 字符串,使用 `json.loads` 后再输出 `session_no / status / classification / analysis_json / headers_json / available_inventory_fields_json / exact_profile_id / result_ok / error_message`。禁止直接引用假定的 Tool 顶层字段。 +7. 回复节点仅解释标准化后的 `file_classification_status`、表头、字段建议和候选解析方案;`rejected/not_inventory` 时说明该附件未达到库存最低特征并请用户澄清,不得改走订单建单。 + +阶段一禁止在画布中新增映射 LLM、`apply_inventory_mapping`、库存匹配、库存站点绑定、仓库映射或发布解析方案调用。阶段二仅新增下列受控映射建议节点,仍由后端验证和用户确认决定是否生效。 + +#### 2.4.3.2 临时库存方案复用与映射建议(阶段二,Dify 由管理员手工配置) + +1. 读取“临时库存分析结果标准化”的 `analysis.match_result`。当 `status=exact` 时,回复“发现可复用的库存文件解析方案”,并展示方案名称、版本和结构差异;不得调用 LLM 映射节点。只有唯一 exact 候选时才可预填 `exact_profile_id`;多个 exact 候选必须要求用户明确选择。该阶段只记录“待确认采用方案”,不会自动绑定任何库存站点。 +2. 当无 `exact` 方案且 `file_classification_status=inventory_candidate` 时,LLM 节点输入只能是:真实表头、每列推断类型/空值率、`available_inventory_fields` 和后端规则建议。禁止把 Excel 二进制、文件路径、样例库存值、库存行或用户自由文本当作映射事实。Tool 返回已主动移除所有 `sample_values`,画布不得配置 `sample_rows_json` 或任何样例行变量。 +3. LLM 输出只能为 JSON object:`{"field_mapping":{"<库存字段目录ID>":"<真实表头>"}}`。键必须来自 `available_inventory_fields[].id`;值必须来自真实表头;一个表头最多映射一次。无法确定时可省略字段,不能猜测。 +4. Tool 节点调用 `submit_temporary_inventory_mapping_suggestion(agent_runtime_context, temporary_session_no, field_mapping)`。后端会校验字段目录、表头存在性、重复表头、匹配/数量能力完整性和会话归属;任何校验失败都回到澄清回复,不能自行修正或调用旧 `apply_inventory_mapping`。 +5. Tool 输出仍先进入“临时映射建议结果标准化” Code 节点解析 `text` JSON。返回 `awaiting_mapping_confirmation` 仅代表“候选映射已保存,待用户确认当前会话后续使用”,不代表已发布方案、已绑定库存站点或已可匹配订单。 + +此阶段不可调用:`apply_inventory_mapping`、发布库存文件解析方案、绑定/启用库存站点、创建仓库映射、库存匹配、生成发货 Excel。正式库存站点仍只使用 published 方案的后端确定性解析。 + +#### 2.4.3.3 临时库存确认与质量门禁(阶段三,Dify 由管理员手工配置) + +1. 候选方案或候选映射只可由 Dify 说明并询问用户“是否仅在本次对话临时确认使用”;用户未明确确认时不得调用确认 Tool。下一轮由“临时库存续办意图判断”识别明确确认,并使用 HXOPS 恢复的 `temporary_inventory_session_no` 续办,禁止依赖 Dify 会话记忆猜会话号。 +2. 用户确认后,Tool 节点调用 `confirm_temporary_inventory_use(agent_runtime_context, temporary_session_no, selected_profile_id?)`。`selected_profile_id` 只允许从 `exact` 已发布候选中由用户选择;该 Tool 不接收任务编号,确认结果只属于当前对话临时审计。 +3. 后端在确认时重新依据已锁定的表头行、工作表和映射解析原文件,校验每一行均有料号、预约号以及非负可用库存数量。任何行不合格、文件漂移、会话过期或任务越权均拒绝确认。 +4. 确认 Tool 输出必须进入“临时库存确认结果标准化” Code 节点解析 `text` JSON。成功返回 `confirmed_for_temporary_use` 和质量摘要,仅表示已允许后续阶段在本会话范围内消费该临时文件;不创建 `ShippingInventoryFile`,不修改 `ShippingTask.inventory_lines_json`,不绑定库存站点,不执行订单库存匹配。 + +禁止将确认结果描述为“库存已匹配”或“库存站点已生效”。Dify 不能在用户未明确确认时自动调用本 Tool;也不能把任何临时文件提升为库存文件解析方案。 + +**安全边界**:Dify 不读取 `.xls/.xlsx/.csv` 二进制、对象存储路径、下载 URL 或全量库存行;Tool 返回的结构预览不包含样例库存值。Dify 不得将“结构初检通过”表述为“库存已可用于订单匹配”。正式库存站点已绑定 published 解析方案时继续由后端确定性解析,绝不调用本临时分支或 Dify 映射。 + +#### 2.4.3.4 管理员沉淀解析方案草稿(阶段四) + +1. 只有状态为 `confirmed_for_temporary_use` 的临时会话,才会出现在管理端“库存文件解析方案”的“来自已确认对话文件”选择器中。 +2. 管理员填写解析方案编码、显示名称和订单匹配键后,调用 `POST /api/admin/shipping-notice/temporary-inventory-sessions/{session_no}/create-profile-draft`;后端忽略客户端提交的字段映射,强制复用会话已锁定的映射、工作表和表头行。 +3. 结果永远是 `draft`,重复操作返回同一草稿;Dify 不得调用此接口或把临时映射直接发布、绑定库存站点、建立仓库映射。 + #### 2.4.4 OpenAPI Tool 导入 1. Dify → **工具** → **导入自定义 OpenAPI** @@ -1366,7 +1596,8 @@ http:///api/shipping-notice/tools/openapi.json flowchart TD A["开始"] --> B["Tool 解析运行态上下文"] B --> B1["运行态上下文标准化"] - B1 --> R{"顶层能力路由"} + B1 --> B2["临时库存续办意图判断"] + B2 --> R{"顶层能力路由"} R -- "order_extraction_path" --> OE1["Tool 读取订单抽取上下文"] OE1 --> OE2["订单抽取上下文标准化"] OE2 --> OE3{"订单抽取上下文是否有效?"} @@ -1380,24 +1611,26 @@ flowchart TD OE8 --> OE9{"提交结果是否有效?"} OE9 -- "否" --> OEF3["订单抽取提交失败回复"] OE9 -- "是" --> OES["订单抽取结果回复"] + R -- "temporary_inventory_new" --> TI1["Tool 创建临时库存候选会话"] + TI1 --> TIS["临时库存分析结果标准化"] + TIS --> TI2{"发现 exact 方案?"} + TI2 -- "是" --> TIR["临时库存结果回复"] + TI2 -- "否且为库存候选" --> TI3["陌生表头候选解释 LLM"] + TI3 --> TI4["提交临时映射建议"] + TI4 --> TI5["临时映射建议结果标准化"] + TI5 --> TIR + R -- "temporary_inventory_confirm" --> TIC1["Tool 读取临时库存分析"] + TIC1 --> TICS["临时库存分析结果标准化"] + TICS --> TIC2{"待确认状态校验"} + TIC2 -- "可确认" --> TIC3["Tool 确认临时库存使用"] + TIC2 -- "不可确认" --> TIR + TIC3 --> TIC4["临时库存确认结果标准化"] + TIC4 --> TIR R -- "normal_path" --> C["用户意图预处理"] C --> C1["附件意图分类"] C1 --> D["分支调度"] D --> E{"主路由分支节点"} - E -- "inventory_path" --> F["库存任务检查"] - F --> G{"has_task?"} - G -- "否" --> H["无TASK_ID提示"] - G -- "是" --> I["Tool 读取库存 schema 预览"] - I --> J["库存 schema 标准化"] - J --> K["库存列映射 LLM"] - K --> L["列映射 JSON 标准化"] - L --> M{"mapping_ok?"} - M -- "否" --> N["列映射失败回复"] - M -- "是" --> O["Tool 应用库存列映射"] - O --> P["映射结果标准化"] - P --> QA["Agent 状态输入标准化"] - E -- "direct_answer" --> S["直接回复(引导)"] E -- "agent_path" --> W["准备读取任务状态"] W --> X["Tool 读取任务状态"] @@ -1406,7 +1639,7 @@ flowchart TD Y1 --> Y2{"是否进入 Agent?"} Y2 -- "否" --> Y3{"当前任务直连动作分支"} Y3 -- "retry_rpa" --> Y4["Tool 重试库存导出"] - Y3 -- "confirm / reject / reparse / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory" --> Y5["Tool 提交当前任务决策"] + Y3 -- "confirm / reject / reparse" --> Y5["Tool 提交当前任务决策"] Y3 -- "rematch" --> Y6["Tool 重新匹配库存"] Y4 --> Y8["直连动作结果标准化"] Y5 --> Y8 @@ -1434,12 +1667,23 @@ 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` | `capability`、`intake_nos_json`、`task_no`、`batch_no`、`trigger_source`、`focus_task_no`、`last_action`、`candidate_count` | -| 顶层能力路由 | `顶层能力路由` | If-Else | 最高优先级识别点击发送订单抽取回合,并与普通聊天链隔离 | `capability` | `order_extraction_path / normal_path` | +| 运行态上下文标准化 | `运行态上下文标准化` | Code | 将 parse 结果转为后续节点可直接使用的 shipping 领域变量 | `Tool 解析运行态上下文.text` | `capability`、`intake_nos_json`、`task_no`、`batch_no`、`temporary_inventory_asset_no`、`temporary_inventory_session_no`、`trigger_source`、`focus_task_no`、`last_action`、`candidate_count` | +| 临时库存续办意图判断 | `临时库存续办意图判断` | Code | 仅在存在待确认会话且用户明确确认本次临时使用时进入确认链 | `sys.query`、`capability`、临时资产/会话号 | `temporary_route`、`confirmation_intent` | +| 顶层能力路由 | `顶层能力路由` | If-Else | 最高优先级识别订单抽取、临时库存新文件和跨回合确认,并与普通聊天链隔离 | `capability`、`temporary_route` | `order_extraction_path / temporary_inventory_new / temporary_inventory_confirm / normal_path` | +| 创建临时库存候选会话 | `创建临时库存候选会话` | Tool | 对当前用户私有文件执行后端结构初检 | `agent_runtime_context`、`temporary_inventory_asset_no` | 临时会话、分类结论、脱敏结构预览 | +| 读取临时库存分析 | `读取临时库存分析` | Tool | 跨回合确认前读取 HXOPS 恢复的待确认会话 | `agent_runtime_context`、`temporary_inventory_session_no` | Tool `text` | +| 临时库存分析结果标准化 | `临时库存分析结果标准化` | Code | 统一解析创建/读取 Tool 的 `text` JSON,输出受控结构变量 | Tool `text` | 会话号、状态、真实表头、字段目录、候选方案、错误信息 | +| 是否可复用已发布方案 | 自动生成 | If-Else | `exact` 方案可复用时跳过 LLM | 临时库存分析结果标准化 | true / false | +| 待确认状态校验 | `待确认状态校验` | If-Else | 确认分支只允许方案确认或映射确认状态进入确认 Tool | 标准化 `status`、`exact_profile_id` | `confirmable / invalid` | +| 陌生表头候选解释 LLM | `陌生表头候选解释 LLM` | LLM | 输出库存字段目录 ID 到真实表头的候选 | 表头、脱敏结构、`available_inventory_fields` | `field_mapping` JSON | +| 提交临时映射建议 | `提交临时映射建议` | Tool | 仅保存当前会话的待确认候选 | 会话上下文、会话号、`field_mapping` | Tool `text` | +| 临时映射建议结果标准化 | `临时映射建议结果标准化` | Code | 解析映射建议 Tool 的 `text` JSON | Tool `text` | `result_ok`、状态、会话号、回复信息 | +| 确认临时库存使用 | `确认临时库存使用` | Tool | 用户明确确认后执行后端质量门禁 | 会话上下文、会话号、可选 exact 方案与任务锚点 | Tool `text` | +| 临时库存确认结果标准化 | `临时库存确认结果标准化` | Code | 解析确认 Tool 结果并裁剪为最终回复 | Tool `text` | `result_ok`、状态、质量摘要、错误信息 | | 用户意图预处理 | `用户意图预处理` | 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` | +| 附件意图分类 | `附件意图分类` | Code | 区分普通附件、库存附件与任务续办;普通库存附件只做引导 | `用户意图预处理.normalized_query`、`sys.files` | `route_key`、`reason` | +| 分支调度 | `分支调度` | Code | 决定任务续办或引导路径 | `附件意图分类.route_key`、任务号 | `branch`、`final_reply`、`resolved_task_no` | +| 主路由分支节点 | `主路由分支节点` | If-Else / Branch | 普通回合按 `branch` 分流到任务续办或引导回复 | `分支调度.branch` | `agent_path / direct_answer` | ##### A2. `order_extraction_path` 分支节点 @@ -1459,21 +1703,23 @@ flowchart TD | 订单抽取 JSON 失败回复 | `订单抽取 JSON 失败回复` | Answer | LLM 输出不符合 JSON 结构时结束本轮 | `订单抽取 JSON 标准化.error_message` | 最终回复 | | 订单抽取提交失败回复 | `订单抽取提交失败回复` | Answer | 提交 Tool 返回异常或非法结果时结束本轮 | `订单抽取提交结果标准化.error_message` | 最终回复 | -##### B. `inventory_path` 分支节点 +##### B. `temporary_inventory_new / temporary_inventory_confirm` 分支节点 -| 节点名 | 节点标识 | 类型 | 主要职责 | 核心输入 | 核心输出 | -| ------------------- | ----- | ------- | -------------------------------- | ------------------------------------ | --------------------------------------------------------- | -| 库存任务检查 | 自动生成 | Code | 判断库存文件当前是否有可绑定任务 | `resolved_task_no` | `task_id`、`has_task`、`final_reply` | -| 是否已有库存绑定任务 | 自动生成 | If-Else | 判断当前库存链是否已有 task\_id | `库存任务检查.has_task` | true / false | -| 无TASK\_ID提示 | 自动生成 | Answer | 没任务号时直接提示 | `库存任务检查.final_reply` | 最终回复 | -| Tool 读取库存 schema 预览 | 自动生成 | Tool | 调 `get_inventory_schema_preview` | `库存任务检查.task_id` | Tool `text` | -| 库存 schema 标准化 | 自动生成 | Code | 提取 headers / sample\_rows | `Tool 读取库存 schema 预览.text` | `headers_json`、`sample_rows_json`、`schema_preview_json` | -| 库存列映射 LLM | 自动生成 | LLM | 推断 `map_json` | `headers_json`、`sample_rows_json` | `text` | -| 列映射 JSON 标准化 | 自动生成 | Code | 把 LLM 输出转成合法 JSON | `库存列映射 LLM.text` | `map_json`、`mapping_ok`、`error_message` | -| 库存列映射是否成功 | 自动生成 | If-Else | 判断列映射 JSON 是否可用于 apply | `列映射 JSON 标准化.mapping_ok` | true / false | -| 列映射失败回复 | 自动生成 | Answer | 非法 JSON 时回复用户 | `列映射 JSON 标准化.error_message` | 最终回复 | -| Tool 应用库存列映射 | 自动生成 | Tool | 调 `apply_inventory_mapping` | `task_id`、`map_json` | Tool `text` | -| 映射结果标准化 | 自动生成 | Code | 标准化 apply 结果 JSON | `Tool 应用库存列映射.text` | `tool_status`、`tool_message`、`tool_checkpoint`、`raw_json` | +| 节点名 | 节点标识 | 类型 | 主要职责 | 核心输入 | 核心输出 | +| --- | --- | --- | --- | --- | --- | +| 创建临时库存候选会话 | `创建临时库存候选会话` | Tool | 对用户私有文件做结构初检与候选方案检索 | `agent_runtime_context`、资产编号 | Tool `text` | +| 读取临时库存分析 | `读取临时库存分析` | Tool | 跨回合确认前读取待确认会话 | 会话上下文、恢复的会话号 | Tool `text` | +| 临时库存分析结果标准化 | `临时库存分析结果标准化` | Code | 解析创建/读取 Tool 的 `text` JSON | Tool `text` | 会话号、状态、表头、字段目录、候选方案 | +| 是否可复用已发布方案 | 自动生成 | If-Else | `match_result.status=exact` 时跳过 LLM | 标准化分析结果 | true / false | +| 待确认状态校验 | `待确认状态校验` | If-Else | 仅允许 `awaiting_profile_confirmation / awaiting_mapping_confirmation` | 标准化状态 | `confirmable / invalid` | +| 陌生表头候选解释 LLM | `陌生表头候选解释 LLM` | LLM | 仅将真实表头映射为库存字段目录 ID 候选 | 表头、脱敏结构、`available_inventory_fields` | `field_mapping` JSON | +| 提交临时映射建议 | `提交临时映射建议` | Tool | 保存候选,等待当前用户确认 | 会话上下文、临时会话号、`field_mapping` | Tool `text` | +| 临时映射建议结果标准化 | `临时映射建议结果标准化` | Code | 解析候选保存结果 | Tool `text` | 状态、会话号、回复信息 | +| 确认临时库存使用 | `确认临时库存使用` | Tool | 用户明确确认后重新解析并执行质量门禁 | 会话上下文、临时会话号、可选 exact 方案/任务号 | Tool `text` | +| 临时库存确认结果标准化 | `临时库存确认结果标准化` | Code | 解析确认结果并输出质量摘要 | Tool `text` | 状态、质量摘要、回复信息 | +| 临时库存结果回复 | 自动生成 | Answer | 展示复用建议、待确认候选或确认质量结果后结束本轮 | 标准化结果 | 最终回复 | + +正式库存站点的文件解析不属于 Dify 节点:RPA 或管理端上传的快照由后端根据库存站点绑定的 published 解析方案确定性处理。 ##### C. `direct_answer` 分支节点 @@ -1497,7 +1743,7 @@ flowchart TD | ------------- | ----- | ---------------- | -------------------------------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------- | | 当前任务直连动作分支 | 自动生成 | If-Else / Branch | 按 Tool 分组分发确定性动作,减少重复 Tool 节点 | `当前任务动作判断.direct_action` | `retry_rpa / submit_decision_path / rematch` | | Tool 重试库存导出 | 自动生成 | Tool | 调 `submit_decision(task_id, decision=retry_rpa)`,由后端 RPA 工作流继续处理库存准备链路 | `task_id` | Tool `text` | -| Tool 提交当前任务决策 | 自动生成 | Tool | 调 `submit_decision(task_id, decision={{direct_action}})`,统一承接确认、驳回、重解析、字段对齐确认等动作 | `task_id`、`direct_action` | Tool `text` | +| Tool 提交当前任务决策 | 自动生成 | Tool | 调 `submit_decision(task_id, decision={{direct_action}})`,统一承接确认、驳回、重解析、重新匹配等动作 | `task_id`、`direct_action` | Tool `text` | | Tool 重新匹配库存 | 自动生成 | Tool | 提交重匹配相关决策,由后端 worker 续跑匹配链路 | `task_id` | Tool `text` | | 直连动作结果标准化 | 自动生成 | Code | 统一解析直连 Tool 返回,并生成最终回复文本 | 各直连 Tool `text` | `tool_status`、`tool_message`、`tool_checkpoint`、`raw_json`、`answer_text` | | 直接回复(动作结果) | 自动生成 | Answer | 输出直连动作 Tool 文本 | `直连动作结果标准化.answer_text` | 最终回复 | @@ -1512,7 +1758,7 @@ flowchart TD | 结构化结果标准化 | 自动生成 | Code | 把 LLM 输出转成 `structured_json` | `订单需求解析 LLM.text` | `structured_json`、`parse_ok`、`error_message` | | Tool 解析发货通知 | 自动生成 | Tool | 调 `parse_notice(structured=...)` | `task_id`、`structured_json` | Tool `text` | | 解析结果标准化 | 自动生成 | Code | 标准化 parse\_notice 返回 | `Tool 解析发货通知.text` | `tool_status`、`tool_message`、`tool_checkpoint`、`raw_json`、`answer_text` | -| Agent 状态输入标准化 | 自动生成 | Code | 合并普通续办 / 通知解析 / 库存映射三条链的最新状态 | `工具结果标准化.raw_json`、`解析结果标准化.raw_json`、`映射结果标准化.raw_json` | `agent_raw_json`、`agent_task_id`、`agent_checkpoint` | +| Agent 状态输入标准化 | 自动生成 | Code | 合并普通续办与通知解析两条链的最新状态 | `工具结果标准化.raw_json`、`解析结果标准化.raw_json` | `agent_raw_json`、`agent_task_id`、`agent_checkpoint` | | 货代续办 Agent | `货代续办 Agent` | Agent | 仅处理模糊自由输入、解释性问题与复杂续办 | `normalized_query`、`agent_raw_json`、`agent_task_id` | `text` | | Agent 指令(维护入口) | 自动生成 | 文档锚点 | 指向生产可粘贴的完整 Agent Instruction | 无 | 无 | | 直接回复 | `直接回复` | Answer | 输出 Agent 文本 | `货代续办 Agent.text` | 最终回复 | @@ -1528,71 +1774,72 @@ flowchart TD 1. 开始 2. Tool 解析运行态上下文 3. 运行态上下文标准化 -4. 顶层能力路由 +4. 临时库存续办意图判断 +5. 顶层能力路由 order_extraction_path: -5. Tool 读取订单抽取上下文 -6. 订单抽取上下文标准化 -7. 订单抽取上下文是否有效 -8. 订单抽取上下文失败回复 -9. 订单完整抽取 LLM -10. 订单抽取 JSON 标准化 -11. 抽取 JSON 是否有效 -12. 订单抽取 JSON 失败回复 -13. Tool 提交订单抽取 -14. 订单抽取提交结果标准化 -15. 提交结果是否有效 -16. 订单抽取提交失败回复 -17. 订单抽取结果回复 +6. Tool 读取订单抽取上下文 +7. 订单抽取上下文标准化 +8. 订单抽取上下文是否有效 +9. 订单抽取上下文失败回复 +10. 订单完整抽取 LLM +11. 订单抽取 JSON 标准化 +12. 抽取 JSON 是否有效 +13. 订单抽取 JSON 失败回复 +14. Tool 提交订单抽取 +15. 订单抽取提交结果标准化 +16. 提交结果是否有效 +17. 订单抽取提交失败回复 +18. 订单抽取结果回复 normal_path 入口与总路由: -18. 用户意图预处理 -19. 附件意图分类 -20. 分支调度 -21. 主路由分支节点 +19. 用户意图预处理 +20. 附件意图分类 +21. 分支调度 +22. 主路由分支节点 -inventory_path: -22. 库存任务检查 -23. 是否已有库存绑定任务 -24. 无TASK_ID提示 -25. Tool 读取库存 schema 预览 -26. 库存 schema 标准化 -27. 库存列映射 LLM -28. 列映射 JSON 标准化 -29. 库存列映射是否成功 -30. 列映射失败回复 -31. Tool 应用库存列映射 -32. 映射结果标准化 +temporary_inventory_new / temporary_inventory_confirm: +23. 创建临时库存候选会话 +24. 读取临时库存分析 +25. 临时库存分析结果标准化 +26. 是否可复用已发布方案 +27. 待确认状态校验 +28. 陌生表头候选解释 LLM +29. 提交临时映射建议 +30. 临时映射建议结果标准化 +31. 确认临时库存使用 +32. 临时库存确认结果标准化 +33. 临时库存结果回复 direct_answer: -33. 直接回复(引导) +34. 直接回复(引导) agent_path 公共前置: -34. 准备读取任务状态 -35. Tool 读取任务状态 -36. 工具结果标准化 -37. 当前任务动作判断 -38. 是否进入 Agent +35. 准备读取任务状态 +36. Tool 读取任务状态 +37. 工具结果标准化 +38. 当前任务动作判断 +39. 是否进入 Agent agent_path / direct_action: -39. 当前任务直连动作分支 -40. 当前任务直连 Tool 节点 -41. 直连动作结果标准化 -42. 直接回复(动作结果) +40. 当前任务直连动作分支 +41. 当前任务直连 Tool 节点 +42. 直连动作结果标准化 +43. 直接回复(动作结果) agent_path / need_agent: -43. 是否待解析通知 -44. 提取通知原文 -45. 订单需求解析 LLM -46. 结构化结果标准化 -47. Tool 解析发货通知 -48. 解析结果标准化 +44. 是否待解析通知 +45. 提取通知原文 +46. 订单需求解析 LLM +47. 结构化结果标准化 +48. Tool 解析发货通知 +49. 解析结果标准化 共享收口: -49. Agent 状态输入标准化 -50. 货代续办 Agent -51. Agent 指令(维护入口) -52. 直接回复 +50. Agent 状态输入标准化 +51. 货代续办 Agent +52. Agent 指令(维护入口) +53. 直接回复 ``` 说明: @@ -1692,6 +1939,7 @@ Tool 绑定: - 本节点是画布唯一的运行态上下文解析入口;禁止其他 Code 节点直接 `json.loads(agent_runtime_context)` 重复解析。 - `parse_agent_runtime_context` 只读,不推进任何业务状态。 +- 已完成消费的 Intake 不得再次传入订单抽取分支;前端仅传 `parse_status=parsed` 的未消费 Intake。后端若收到已消费 Intake,返回 `SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED`,提示查看已有任务或订单抽取结果;只有预处理未完成才返回 `SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING`。 - 解析不到的字段会进入 Tool 返回的 `missing`,下游应按空值处理,不应报错中断。 ##### 节点:运行态上下文标准化 @@ -1708,8 +1956,10 @@ Tool 绑定: | 字段 | 说明 | | --- | --- | -| `capability` | 平台显式请求的能力;本期订单抽取固定为 `order_extraction` | +| `capability` | 平台显式请求的能力;可为 `order_extraction` 或 `temporary_inventory` | | `intake_nos_json` | 本轮 Intake 编号数组的 JSON 字符串;仅用于观察和排查,不作为 Tool 手写参数 | +| `temporary_inventory_asset_no` | 本轮临时库存文件资产编号;只可直接传给创建临时会话 Tool | +| `temporary_inventory_session_no` | 已创建的临时库存会话编号;只可直接传给读取临时会话 Tool | | `task_no` | shipping 当前任务号,来自 `refs.task_no` | | `batch_no` | shipping 当前批次号,来自 `refs.batch_no` | | `run_purpose` | 本轮运行目的,如 `chat_turn / parse_notice` | @@ -1763,6 +2013,8 @@ def main(text: str = ""): return { "capability": _value(parsed, "refs.capability"), "intake_nos_json": json.dumps(intake_nos, ensure_ascii=False), + "temporary_inventory_asset_no": _value(parsed, "refs.temporary_inventory_asset_no").upper(), + "temporary_inventory_session_no": _value(parsed, "refs.temporary_inventory_session_no").upper(), "task_no": _value(parsed, "refs.task_no").upper(), "batch_no": _value(parsed, "refs.batch_no").upper(), "run_purpose": _value(parsed, "refs.run_purpose"), @@ -1790,13 +2042,14 @@ def main(text: str = ""): 类型:`If-Else` -上游节点:`运行态上下文标准化` +上游节点:`临时库存续办意图判断` 输入字段: | Dify 变量 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | `运行态上下文标准化.capability` | String | 是 | 平台显式能力标识;普通聊天为空 | +| `临时库存续办意图判断.temporary_route` | String | 是 | `new_file / confirm_pending / none` | 条件配置: @@ -1805,6 +2058,14 @@ def main(text: str = ""): 运算符:is 右值:order_extraction +条件 2:临时库存续办意图判断.temporary_route +运算符:is +右值:new_file + +条件 3:临时库存续办意图判断.temporary_route +运算符:is +右值:confirm_pending + ``` 分支去向: @@ -1812,12 +2073,14 @@ def main(text: str = ""): | 分支 | 下游节点 | 说明 | | --- | --- | --- | | true / `order_extraction_path` | `Tool 读取订单抽取上下文` | 点击发送后的完整订单抽取固定链 | -| false / `normal_path` | `用户意图预处理` | 原有库存、任务续办和引导回复链 | +| true / `temporary_inventory_new` | `创建临时库存候选会话` | 用户明确声明的对话 `.xls/.xlsx/.csv` 受控初检链;不进入 Task、库存快照或映射发布 | +| true / `temporary_inventory_confirm` | `读取临时库存分析` | 明确确认上一轮待确认临时库存;使用 HXOPS 恢复的会话号 | +| false / `normal_path` | `用户意图预处理` | 普通任务续办和引导回复链 | 说明: - 本节点是主编排最高优先级路由;必须位于所有用户意图、附件意图、任务状态和 Agent 节点之前。 -- 不得添加 `run_purpose`、关键词、文件扩展名或 `sys.files` 作为订单抽取判断条件。 +- 不得添加 `run_purpose`、文件扩展名或 `sys.files` 作为订单抽取判断条件;临时新文件由平台 capability + 资产编号决定,跨回合确认由明确用户话术 + 数据库恢复会话号共同决定。 ##### 节点:Tool 读取订单抽取上下文 @@ -2144,8 +2407,9 @@ def _fail(message: str): 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() + text = str(llm_text or "").replace("\u00a0", " ").strip() + text = re.sub(r"^```(?:json)?[ \t\r\n]*", "", text, flags=re.I) + text = re.sub(r"[ \t\r\n]*```$", "", text).strip() try: payload = json.loads(text) except (TypeError, ValueError) as exc: @@ -2194,6 +2458,7 @@ def main(llm_text: str = ""): 说明: - 本节点只校验 JSON 形状和 50 单上限,不复制 HXOPS 的置信度、证据、判重与自动建单业务门禁。 +- LLM 输出中的不间断空格(`U+00A0`)会先转换为普通空格,并剥离可选 JSON 代码围栏,避免合法 JSON 因排版字符被误判为解析失败。 - `orders=[]` 是合法结果,必须继续调用 `submit_order_extraction`,由 HXOPS 正确消费“非发货需求/无订单”Intake。 - OpenAPI 中 `orders` 是 `Array[Object]`;Tool 参数必须直接选择本节点的 `orders` 数组变量。`orders_json` 只用于日志和联调,不得绑定到 Tool 的数组参数,也不得手工复制 LLM 文本。 @@ -2443,7 +2708,7 @@ def main(text: str = ""): | `normalized_query` | 标准化后的用户消息 | | `detected_batch_no` | 识别出的批次号 | | `detected_task_no` | 识别出的任务号 | -| `intent_hint` | `message / parse_notice / batch_switch / task_switch / retry_rpa / rematch / confirm / reparse / reject / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory` | +| `intent_hint` | `message / parse_notice / batch_switch / task_switch / retry_rpa / rematch / confirm / reparse / reject` | | `trigger_source` | `运行态上下文标准化.trigger_source`,如 `frontend_chat / backend_orchestrator` | | `conversation_id` | 透传会话号 | | `error_message` | 预留错误文本 | @@ -2477,12 +2742,6 @@ def main(query: str = "", conversation_id: str = "", task_no: str = "", batch_no intent_hint = "reparse" elif re.search(r"驳回|取消|reject", normalized_query, re.I): intent_hint = "reject" - elif re.search(r"确认字段对齐|确认映射|confirm_inventory_mapping", normalized_query, re.I): - intent_hint = "confirm_inventory_mapping" - elif re.search(r"更正映射|更正列映射|correct_inventory_mapping", normalized_query, re.I): - intent_hint = "correct_inventory_mapping" - elif re.search(r"重新上传库存|重传库存|reparse_inventory", normalized_query, re.I): - intent_hint = "reparse_inventory" elif re.search(r"切到|切换到|换到|处理\s*sn-|上一票|下一票|\bnext\b|\bprev\b|\bprevious\b", lower_text, re.I): intent_hint = "task_switch" elif re.search(r"切换批次|切到批次|处理批次|batch\s*switch", normalized_query, re.I): @@ -2524,7 +2783,7 @@ def main(query: str = "", conversation_id: str = "", task_no: str = "", batch_no | 字段 | 说明 | | ----------- | ------------------------------------------------------------------------------------- | -| `route_key` | `inventory_path / agent_path / direct_answer` | +| `route_key` | `agent_path / direct_answer` | | `reason` | 路由原因 | 代码: @@ -2540,8 +2799,8 @@ def main(normalized_query: str = "", intent_hint: str = "", sys_files=None): text = str(normalized_query or "").strip() if files: lower_names = " ".join(_file_name(f) for f in files) - if any(ext in lower_names for ext in [".xlsx", ".csv"]): - return {"route_key": "inventory_path", "reason": "inventory_file"} + if any(ext in lower_names for ext in [".xls", ".xlsx", ".csv"]): + return {"route_key": "direct_answer", "reason": "inventory_file_requires_admin_temporary_analysis"} return {"route_key": "direct_answer", "reason": "notice_files_managed_by_hxops"} if intent_hint in { "parse_notice", @@ -2550,9 +2809,6 @@ def main(normalized_query: str = "", intent_hint: str = "", sys_files=None): "confirm", "reparse", "reject", - "confirm_inventory_mapping", - "correct_inventory_mapping", - "reparse_inventory", "task_switch", "batch_switch", }: @@ -2564,8 +2820,8 @@ def main(normalized_query: str = "", intent_hint: str = "", sys_files=None): 说明: -- `parse_notice / retry_rpa / rematch / confirm / reparse / reject / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory` 都属于**当前任务动作**,必须落到 `agent_path`。 -- 通知附件由 HXOPS 前端/后端接管上传、建批、建任务与文本抽取;Dify 收到通知附件时只走 `direct_answer` 回引,不在画布内建 task。 +- `parse_notice / retry_rpa / rematch / confirm / reparse / reject` 都属于**当前任务动作**,必须落到 `agent_path`。 +- 通知附件由 HXOPS 前端/后端接管上传、建批、建任务与文本抽取;Dify 收到通知附件时只走 `direct_answer` 回引,不在画布内建 task。普通会话中的库存附件只有在用户明确声明库存用途后,宿主系统才显式注入 `capability=temporary_inventory`;正式库存只能从库存站点导入或既有任务的受控人工上传进入。 - 即使文本里带了 `SN-...`,也不应把这类动作改走其他分支。 ##### 节点:分支调度 @@ -2583,7 +2839,7 @@ def main(normalized_query: str = "", intent_hint: str = "", sys_files=None): | 字段 | 说明 | | ------------------ | --------------------------------------------- | -| `branch` | `direct_answer / inventory_path / agent_path` | +| `branch` | `direct_answer / agent_path` | | `final_reply` | 引导回复 | | `resolved_task_no` | 最终任务号 | | `action_hint` | 当前任务动作提示;供续办链直接执行 | @@ -2595,17 +2851,10 @@ def main(route_key: str = "", normalized_query: str = "", detected_task_no: str rk = str(route_key or "").strip() hint = str(intent_hint or "").strip() task = str(detected_task_no or "").strip().upper() - if rk == "inventory_path": - return { - "branch": "inventory_path", - "final_reply": "", - "resolved_task_no": task, - "action_hint": "", - } if rk == "direct_answer": return { "branch": "direct_answer", - "final_reply": "请在 Hxops 聊天区上传发货通知文件,系统会创建任务并后台解析;完成后可发送“继续处理”或直接发送 SN- 任务号。", + "final_reply": "请在 Hxops 聊天区上传发货通知文件,系统会创建任务并后台解析;正式库存请由已配置库存站点导入,或在已有任务中使用受控人工上传。若仅需分析对话中的表格,请明确说明它是库存文件。", "resolved_task_no": task, "action_hint": "", } @@ -2622,7 +2871,7 @@ def main(route_key: str = "", normalized_query: str = "", detected_task_no: str 说明: - `分支调度` 不能仅因消息里出现 `SN-...` 就改写当前任务动作。 -- 当 `intent_hint` 是 `parse_notice / retry_rpa / rematch / confirm / reparse / reject / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory` 时,应视为**当前任务上的动作执行**,进入统一续办链。 +- 当 `intent_hint` 是 `parse_notice / retry_rpa / rematch / confirm / reparse / reject` 时,应视为**当前任务上的动作执行**,进入统一续办链。 ##### 节点:主路由分支节点 @@ -2634,14 +2883,10 @@ def main(route_key: str = "", normalized_query: str = "", detected_task_no: str 输入字段:分支调度.branch 分支 1: - 条件值:inventory_path - 去向:库存任务检查 - -分支 2: 条件值:agent_path 去向:准备读取任务状态 -分支 3: +分支 2: 条件值:direct_answer 去向:直接回复(引导) ``` @@ -2649,162 +2894,177 @@ def main(route_key: str = "", normalized_query: str = "", detected_task_no: str 说明: - 这里使用 Dify 的**多分支能力** -- 不再拆成“先判断库存,再判断是否任务续办”的两个菱形 -- `branch` 的三个合法值必须和 `分支调度` 输出保持一致: - - `inventory_path` +- `branch` 的两个合法值必须和 `分支调度` 输出保持一致: - `agent_path` - `direct_answer` -##### 节点:库存任务检查 +##### 节点:临时库存续办意图判断 + +类型:`Code` 输入映射: -| 变量名 | 来源 | -| ------------------ | -------------------------------------- | -| `resolved_task_no` | `分支调度.resolved_task_no` | +| 变量名 | 来源 | 类型 | +| --- | --- | --- | +| `query` | `sys.query` | String | +| `capability` | `运行态上下文标准化.capability` | String | +| `asset_no` | `运行态上下文标准化.temporary_inventory_asset_no` | String | +| `session_no` | `运行态上下文标准化.temporary_inventory_session_no` | String | -输出: +输出变量: -| 字段 | 说明 | -| ------------- | --------- | -| `task_id` | 库存要绑定的任务号 | -| `has_task` | 是否已有任务号 | -| `final_reply` | 缺少任务号时的提示 | +| 字段 | Dify 类型 | 说明 | +| --- | --- | --- | +| `temporary_route` | String | `new_file / confirm_pending / none` | +| `confirmation_intent` | Boolean | 是否为待确认临时库存的明确确认 | 代码: ```python -def main(resolved_task_no: str = ""): - task_id = str(resolved_task_no or "").strip().upper() - return { - "task_id": task_id, - "has_task": bool(task_id), - "final_reply": "" if task_id else "检测到库存文件,但当前还没有可绑定的任务号。请先在 Hxops 上传发货通知生成 SN-任务,再重新上传库存文件。", +def main(query="", capability="", asset_no="", session_no=""): + text = "".join(str(query or "").strip().lower().split()) + capability = str(capability or "").strip() + asset_no = str(asset_no or "").strip() + session_no = str(session_no or "").strip() + + if capability == "temporary_inventory" and asset_no: + return {"temporary_route": "new_file", "confirmation_intent": False} + + exact_confirmations = { + "确认本次临时库存使用", "确认本次库存使用", + "采用本次库存方案", "使用本次库存方案", + "确认使用这个库存映射", "按这个库存映射使用", } + explicit_confirmation = ( + text in exact_confirmations + or (("确认" in text or "采用" in text or "使用" in text) + and "库存" in text + and ("方案" in text or "映射" in text or "本次" in text or "临时" in text)) + ) + if session_no and explicit_confirmation: + return {"temporary_route": "confirm_pending", "confirmation_intent": True} + return {"temporary_route": "none", "confirmation_intent": False} ``` 说明: -- 本节点只决定“库存文件当前能否绑定到某个 task”,不负责真正上传库存文件。 -- 多任务场景下若没有明确 task,上游必须在这里被拦住,不能继续进入库存解析链。 +- `确认 / 确定 / 同意 / 继续 / 继续处理 / 下一步` 单独出现均不属于临时库存明确确认,必须返回 `none`,避免抢占当前发货任务的确认动作。 +- HXOPS 只恢复未完成且未过期的会话号;本节点仍负责判断本轮用户是否授权确认。 +- 顶层能力路由依次判断 `order_extraction`、`temporary_route=new_file`、`temporary_route=confirm_pending`,其余进入 `normal_path`。 -##### 节点:是否已有库存绑定任务 +##### 节点:创建临时库存候选会话 / 读取临时库存分析 -类型:`If-Else` +两个节点类型均为 `Tool`: -条件配置(直接照填): +| 节点 | Tool | 参数 | +| --- | --- | --- | +| 创建临时库存候选会话 | `create_temporary_inventory_session` | `agent_runtime_context`;`asset_no=运行态上下文标准化.temporary_inventory_asset_no` | +| 读取临时库存分析 | `get_temporary_inventory_session` | `agent_runtime_context`;`temporary_session_no=运行态上下文标准化.temporary_inventory_session_no` | -```text -左值:库存任务检查.has_task -运算符:is -右值:true -``` +两个 Tool 的输出都只连接“临时库存分析结果标准化”。不得直接从 Tool 节点选择 `status / analysis / headers` 等假定顶层字段。 -true: +##### 节点:临时库存分析结果标准化 -- 进入 `Tool 读取库存 schema 预览` - -false: - -- 进入 `无TASK_ID提示` - -说明: - -- 这是库存链的硬门禁;`has_task=false` 时必须结束本轮。 -- 不允许在这里兜底猜测任务号或默认绑定任意历史 task。 - -##### 节点:无TASK\_ID提示 - -类型:`Answer` - -内容: - -```text -{{#库存任务检查.final_reply#}} -``` - -说明: - -- 本节点只输出缺少任务号时的固定引导,不做额外判断。 -- 若库存上传前置规则调整,只改 `库存任务检查.final_reply` 的生成逻辑即可。 - -##### 节点:Tool 读取库存 schema 预览 - -Tool 绑定: - -| 项 | 值 | -| -------------------- | ------------------------------ | -| provider\_show\_name | `Hxops Shipping Notice` | -| tool\_name | `get_inventory_schema_preview` | - -参数映射: - -| 参数名 | 来源 | 是否必填 | 说明 | -| --------- | ---------------------- | ---- | ------------- | -| `task_id` | `{{#库存任务检查.task_id#}}` | 是 | 当前库存文件要绑定的任务号 | - -输出: - -| 字段 | 说明 | -| ------ | --------------------------------------------------------------- | -| `text` | Tool 原始返回 JSON 字符串,交给 `库存 schema 标准化` 提取 headers / sample\_rows | - -说明: - -- 本节点只读取小 payload 的 schema preview,不在 Dify 侧处理完整库存文件。 -- 真正的完整库存解析只允许发生在 `apply_inventory_mapping` 之后,由后端负责。 - -##### 节点:库存 schema 标准化 +类型:`Code` 输入映射: -| 变量名 | 来源 | -| ------ | -------------------------- | -| `text` | `Tool 读取库存 schema 预览.text` | +| 变量名 | 来源 | 类型 | +| --- | --- | --- | +| `create_text` | `创建临时库存候选会话.text` | String | +| `read_text` | `读取临时库存分析.text` | String | -输出: +不同入边没有值时传空字符串。输出变量: -| 字段 | 说明 | -| --------------------- | ------------------- | -| `headers_json` | 表头 JSON 字符串 | -| `sample_rows_json` | 样例行 JSON 字符串 | -| `schema_preview_json` | schema preview JSON | -| `raw_json` | 全量 JSON | +| 字段 | Dify 类型 | 说明 | +| --- | --- | --- | +| `result_ok` | Boolean | Tool JSON 是否有效 | +| `session_no` | String | 临时会话号 | +| `status` | String | 当前临时状态 | +| `classification` | String | 文件分类结论 | +| `headers_json` | String | 真实表头、类型和空值率;不含样例值 | +| `available_inventory_fields_json` | String | 可选择的库存字段目录 | +| `analysis_json` | String | 脱敏完整分析 | +| `exact_profile_id` | Number | 唯一 exact 候选 ID;否则为 `0` | +| `error_message` | String | 标准化失败原因 | 代码: ```python import json -def main(text: str = ""): - raw = str(text or "").strip() + +def main(create_text="", read_text=""): + raw = str(read_text or create_text or "").strip() try: data = json.loads(raw) if raw else {} - except json.JSONDecodeError: + except (TypeError, ValueError): data = {} if not isinstance(data, dict): data = {} - payload = data.get("data") or {} - schema_preview = payload.get("schema_preview") or {} - headers = schema_preview.get("headers") or [] - sample_rows = schema_preview.get("sample_rows") or schema_preview.get("rows") or [] + + analysis = data.get("analysis") if isinstance(data.get("analysis"), dict) else {} + structure = analysis.get("structure") if isinstance(analysis.get("structure"), dict) else {} + columns = structure.get("selected_columns") if isinstance(structure.get("selected_columns"), list) else [] + safe_columns = [] + for column in columns: + if not isinstance(column, dict): + continue + safe_columns.append({ + "header": str(column.get("header") or ""), + "inferred_type": str(column.get("inferred_type") or ""), + "empty_rate": column.get("empty_rate"), + }) + + fields = data.get("available_inventory_fields") + fields = fields if isinstance(fields, list) else [] + match_result = analysis.get("match_result") if isinstance(analysis.get("match_result"), dict) else {} + candidates = match_result.get("candidates") if isinstance(match_result.get("candidates"), list) else [] + exact = [item for item in candidates if isinstance(item, dict) and item.get("level") == "exact"] + session_no = str(data.get("session_no") or "").strip() + status = str(data.get("status") or "").strip() + error = "" if session_no and status else "临时库存分析结果无效,请重新上传或稍后重试。" return { - "headers_json": json.dumps(headers, ensure_ascii=False), - "sample_rows_json": json.dumps(sample_rows, ensure_ascii=False), - "schema_preview_json": json.dumps(schema_preview, ensure_ascii=False), - "raw_json": json.dumps(data, ensure_ascii=False), + "result_ok": not bool(error), + "session_no": session_no, + "status": status, + "classification": str(data.get("file_classification_status") or ""), + "headers_json": json.dumps(safe_columns, ensure_ascii=False), + "available_inventory_fields_json": json.dumps(fields, ensure_ascii=False), + "analysis_json": json.dumps(analysis, ensure_ascii=False), + "exact_profile_id": int(exact[0].get("profile_id") or 0) if len(exact) == 1 else 0, + "error_message": error, } ``` -说明: +说明:不得从原 Tool JSON重新引出 `sample_values`。如果后端未来新增字段,Dify 仍只消费上面列出的白名单投影。 -- 本节点只负责把 schema preview 拆成 LLM 可消费的轻量输入。 -- 若后端 preview 结构调整,只改这里的提取逻辑,不改后续库存映射 Prompt 模板。 +##### 节点:待确认状态校验 -##### 节点:库存列映射 LLM +类型:`If-Else` + +上游仅接“读取临时库存分析 → 临时库存分析结果标准化”,不要连接新文件创建分支。 + +```text +分支 1:临时库存分析结果标准化.status is awaiting_profile_confirmation + 且 临时库存分析结果标准化.exact_profile_id > 0 + -> 确认临时库存使用 + +分支 2:临时库存分析结果标准化.status is awaiting_mapping_confirmation + -> 确认临时库存使用 + +其他状态 + -> 临时库存结果回复(提示当前会话尚未形成可确认方案,或已经结束) +``` + +`awaiting_mapping_suggestion` 不能进入确认 Tool,必须先经过陌生表头候选解释与候选映射保存;`confirmed_for_temporary_use / rejected / expired` 均为不可再次确认状态。 + +##### 节点:陌生表头候选解释 LLM 类型:`LLM` +> **状态:默认关闭,仅在受控临时库存分支兜底。** 此节点不属于任务级人工上传、库存刷新、RPA 测试导出或正式库存导出链路。用户明确声明对话表格为库存文件后,Dify 才可基于后端脱敏表头提出候选;管理员在“库存文件解析方案”草稿中也可手动启用一次候选解释。输出不能发布解析方案、绑定库存站点、创建仓库映射或解除结构漂移阻断。 + 模型建议: | 项 | 值 | @@ -2816,207 +3076,142 @@ def main(text: str = ""): System Prompt: ```text -你是库存 Excel 列映射助手。你的任务是根据表头和样例行,只输出合法 JSON,不要输出任何解释文字。 - -目标字段只允许包含: -- part_number -- reservation_id -- available_qty +你是库存文件解析方案的候选解释助手。你的任务是根据真实表头、列类型/空值率和受控字段目录,给当前用户提供候选含义;不能作出任何生效决定。 规则: -1. 返回 JSON object -2. value 必须来自提供的真实表头,禁止臆造 -3. `part_number` 必须映射库存 Supplier Sku/内部料号列,禁止映射 AWS Sku -4. `reservation_id` 与 `available_qty` 均为必填;任何必填列无法判断时返回空字符串,由下游进入人工修正 -5. 不要输出 markdown,不要输出代码块 +1. 只从输入 `available_inventory_fields` 的 `id` 中选择目标字段;不得使用或猜测固定业务字段编码。 +2. 返回 JSON object,格式为 `{"field_mapping":{"<库存字段目录ID>":"真实表头"}}`。 +3. 键必须是允许库存字段的目录 ID;值必须来自真实表头;一个真实表头最多映射一次。无法判断时省略该字段。 +4. 不得要求或使用样例库存值;候选只表示语义建议,不是发布、绑定或放行依据。 +5. 不要输出 `map_json`、发布状态、库存站点、仓库映射或任何执行指令;不要输出 markdown 或代码块。 ``` User Prompt: ```text -表头: -{{#库存 schema 标准化.headers_json#}} +表头与列结构: +{{#临时库存分析结果标准化.headers_json#}} -样例行: -{{#库存 schema 标准化.sample_rows_json#}} +允许库存字段: +{{#临时库存分析结果标准化.available_inventory_fields_json#}} -请输出 map_json。 +请输出候选解释 JSON。 ``` 期望输出: ```json -{"part_number":"Supplier Sku","reservation_id":"Reservation Order","available_qty":"Qty Available"} +{"field_mapping":{"9e6a5bb9-4f3c-4d6a-ae64-5af0d9932118":"Supplier Sku"}} ``` 说明: -- 本节点只负责“列名建议”,不负责决定库存是否可继续匹配。 -- 若模型效果不稳定,应先调整 Prompt 与样例,不要把列映射容错逻辑堆到下游 If-Else 节点。 +- 本节点只负责候选解释,不负责决定库存是否可继续匹配。对话临时分支必须由当前用户确认且只形成临时质量审计;需要沉淀正式方案时,仍须由管理员在库存文件解析方案草稿中选择来源栏位并发布。 +- 若模型效果不稳定,应先调整表头词典、字段说明与 Prompt,不要向模型增加库存样例值,也不要把列映射容错逻辑堆到下游 If-Else 节点。 +- **Dify 手工配置**:对话临时分支将 LLM 输出传给 `submit_temporary_inventory_mapping_suggestion` 并等待当前用户确认;管理端显式请求可只展示给管理员。严禁连接旧 `apply_inventory_mapping`。当前 Dify 画布由业务管理员手工调整,HXOPS 不通过代码改写画布。 -##### 节点:列映射 JSON 标准化 - -输入映射: - -| 变量名 | 来源 | -| ------ | ---------------- | -| `text` | `库存列映射 LLM.text` | - -输出: - -| 字段 | 说明 | -| --------------------- | ----------- | -| `map_json` | 合法 JSON 字符串 | -| `mapping_ok` | 是否成功 | -| `error_message` | 错误提示 | - -代码: - -```python -import json - -def main(text: str = ""): - raw = str(text or "").strip() - try: - mapping = json.loads(raw) if raw else {} - except json.JSONDecodeError: - mapping = None - if not isinstance(mapping, dict): - return { - "map_json": "{}", - "mapping_ok": False, - "error_message": "库存列映射生成失败:LLM 未返回合法 JSON。请检查表头是否清晰,或人工更正列名后重试。", - } - allowed_keys = {"part_number", "reservation_id", "available_qty"} - normalized = {k: str(v or "").strip() for k, v in mapping.items() if k in allowed_keys} - if not all(normalized.get(key) for key in ("part_number", "reservation_id", "available_qty")): - return { - "map_json": json.dumps(normalized, ensure_ascii=False), - "mapping_ok": False, - "error_message": "库存列映射不完整:必须识别内部料号、Reservation ID 和可用数量三列。请人工确认后重试。", - } - return { - "map_json": json.dumps(normalized, ensure_ascii=False), - "mapping_ok": True, - "error_message": "", - } -``` - -说明: - -- 本节点只校验并规范化 LLM 返回的 `map_json`,不生成业务结论。 -- 字段缺失、JSON 非法等失败都应在这里收口成统一错误文本,供后续 Answer 节点直接展示。 -- Dify OpenAPI Tool 参数使用 `string` 才能稳定选择上游变量,因此本节点输出 JSON 字符串;后端仍兼容对象入参,仅供 Hxops 前端内部调用。 - -##### 节点:库存列映射是否成功 - -类型:`If-Else` - -条件配置(直接照填): - -```text -左值:列映射 JSON 标准化.mapping_ok -运算符:is -右值:true -``` - -true: - -- 进入 `Tool 应用库存列映射` - -false: - -- 进入 `列映射失败回复` - -说明: - -- 这里的判断标准只看 `mapping_ok`,不在 If-Else 节点内重复解析 JSON。 -- `false` 时必须直接回复用户,不允许带着非法 `map_json` 继续调 `apply_inventory_mapping`。 - -##### 节点:列映射失败回复 - -类型:`Answer` - -内容: - -```text -{{#列映射 JSON 标准化.error_message#}} -``` - -说明: - -- 本节点只输出列映射失败原因。 -- 若后续要支持“人工修改映射后重试”的更细引导,应在失败文案里补充,而不是在本节点再做分支。 - -##### 节点:Tool 应用库存列映射 +##### 节点:提交临时映射建议 Tool 绑定: -| 项 | 值 | -| -------------------- | ------------------------- | -| provider\_show\_name | `Hxops Shipping Notice` | -| tool\_name | `apply_inventory_mapping` | +| 项 | 值 | +| --- | --- | +| provider\_show\_name | `Hxops Shipping Notice` | +| tool\_name | `submit_temporary_inventory_mapping_suggestion` | 参数映射: -| 参数名 | 来源 | 是否必填 | 说明 | -| --------------------- | ---------------------------------------- | ---- | ------------------------- | -| `task_id` | `{{#库存任务检查.task_id#}}` | 是 | 当前库存文件所属任务号 | -| `map_json` | `{{#列映射 JSON 标准化.map_json#}}` | 是 | 由库存列映射 LLM 产出的合法 JSON 字符串 | - -输出: - -| 字段 | 说明 | -| ------ | ------------------------------------ | -| `text` | Tool 原始返回 JSON 字符串,必须交给 `映射结果标准化` 处理 | +| 参数名 | 来源 | 是否必填 | 说明 | +| --- | --- | --- | --- | +| `agent_runtime_context` | 当前会话上下文 | 是 | 用于校验管理员会话归属 | +| `temporary_session_no` | `临时库存分析结果标准化.session_no` | 是 | 当前临时分析会话编号 | +| `field_mapping` | `陌生表头候选解释 LLM.text` | 是 | `库存字段目录 ID -> 真实表头` 的 JSON 对象 | 说明: -- 本节点提交的只是 `task_id + map_json`,不在画布层追加任何自动推进逻辑。 -- `apply_inventory_mapping` 返回后是否进入人工确认、是否继续自动续跑,以后端返回为准。 +- 该 Tool 只保存当前临时会话的候选建议,返回“待当前用户确认”;不解析正式快照、不匹配订单、不发布或绑定库存站点。 +- 后端负责验证 JSON、目录字段、真实表头、重复来源列、匹配/数量能力完整性和会话归属;失败时由页面提示管理员在结构化映射编辑器修正。 -##### 节点:映射结果标准化 +##### 节点:临时映射建议结果标准化 -输入映射: +类型:`Code` -| 变量名 | 来源 | -| ------ | ------------------- | -| `text` | `Tool 应用库存列映射.text` | - -输出: - -| 字段 | 说明 | -| ----------------- | --------------- | -| `tool_status` | Tool 状态 | -| `tool_message` | Tool message | -| `tool_checkpoint` | Tool checkpoint | -| `raw_json` | 全量 JSON | - -代码: +输入 `text=提交临时映射建议.text`,输出 `result_ok / session_no / status / answer_text`。代码: ```python import json -def main(text: str = ""): - raw = str(text or "").strip() + +def main(text=""): try: - data = json.loads(raw) if raw else {} - except json.JSONDecodeError: + data = json.loads(str(text or "").strip()) + except (TypeError, ValueError): data = {} if not isinstance(data, dict): data = {} + session_no = str(data.get("session_no") or "").strip() + status = str(data.get("status") or "").strip() + ok = bool(session_no and status == "awaiting_mapping_confirmation") return { - "tool_status": str(data.get("status") or "").strip(), - "tool_message": str(data.get("message") or "").strip(), - "tool_checkpoint": str(data.get("checkpoint") or "").strip(), - "raw_json": json.dumps(data, ensure_ascii=False), + "result_ok": ok, + "session_no": session_no, + "status": status, + "answer_text": ( + "已保存本次临时库存字段候选,请明确回复‘确认本次临时使用’后,系统才会重新解析并执行质量校验。" + if ok else "临时库存字段候选保存失败,请检查字段映射后重试。" + ), } ``` -说明: +##### 节点:确认临时库存使用 -- 本节点只做结果标准化,不做“是否继续匹配”的业务判断。 -- 后续进入 Agent 时,应由 Agent 基于 `tool_status / tool_checkpoint / raw_json` 决定如何解释当前状态。 +类型:`Tool` + +Tool 绑定:`confirm_temporary_inventory_use` + +| 参数名 | 来源 | 是否必填 | 说明 | +| --- | --- | --- | --- | +| `agent_runtime_context` | 当前会话上下文 | 是 | 后端反查当前用户与会话 | +| `temporary_session_no` | `运行态上下文标准化.temporary_inventory_session_no` | 是 | HXOPS 数据库恢复的待确认会话号 | +| `selected_profile_id` | `临时库存分析结果标准化.exact_profile_id` | 否 | 只有唯一 exact 候选且用户明确采用时传入 | + +必须由“临时库存续办意图判断.confirmation_intent=true”进入。禁止由 Agent 自主调用,也禁止在首次候选回复同一轮自动调用。 + +##### 节点:临时库存确认结果标准化 + +类型:`Code` + +输入 `text=确认临时库存使用.text`,输出 `result_ok / status / quality_json / answer_text`。代码: + +```python +import json + + +def main(text=""): + try: + data = json.loads(str(text or "").strip()) + except (TypeError, ValueError): + data = {} + if not isinstance(data, dict): + data = {} + confirmed = data.get("confirmed_usage") if isinstance(data.get("confirmed_usage"), dict) else {} + quality = confirmed.get("quality") if isinstance(confirmed.get("quality"), dict) else {} + status = str(data.get("status") or "").strip() + ok = status == "confirmed_for_temporary_use" and quality.get("passed") is True + if ok: + count = int(quality.get("valid_line_count") or 0) + answer = f"本次临时库存已通过质量校验,共 {count} 行有效数据。该确认仅用于本会话审计,尚未匹配订单、绑定库存站点或生成正式库存快照。" + else: + answer = "本次临时库存未通过质量校验,请根据后端错误检查料号、预约号、库存数量或文件结构。" + return { + "result_ok": ok, + "status": status, + "quality_json": json.dumps(quality, ensure_ascii=False), + "answer_text": answer, + } +``` + +`临时库存结果回复` 只输出两个标准化节点之一的 `answer_text`;不得自行补充“库存已匹配、已生效、已绑定”等结论。 ##### 节点:直接回复(引导) @@ -3181,16 +3376,11 @@ def main(intent_hint: str = "", resolved_task_no: str = "", tool_checkpoint: str "confirm", "reject", "reparse", - "confirm_inventory_mapping", - "correct_inventory_mapping", - "reparse_inventory", "rematch", } direct_action = "" - if hint == "confirm" and checkpoint == "align_review": - direct_action = "confirm_inventory_mapping" - elif hint in direct_actions: + if hint in direct_actions: direct_action = hint if hint == "parse_notice" and task_no: @@ -3215,8 +3405,9 @@ def main(intent_hint: str = "", resolved_task_no: str = "", tool_checkpoint: str - 本节点的目标是**减少 Agent 调用时间**。 - 对于已由上游代码节点明确识别的短动作,直接走 Tool 即可,不要再让 Agent 做第二轮判断。 -- 当前生产优先绕开 Agent 的动作包括:`retry_rpa / confirm / reject / reparse / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory / rematch`。 -- 当用户只输入 `确认` 且当前 `checkpoint=align_review` 时,应标准化为 `confirm_inventory_mapping`,优先进入库存字段对齐确认直连链,而不是误调普通 `confirm`。 +- 当前生产优先绕开 Agent 的动作包括:`retry_rpa / confirm / reject / reparse / rematch`。 +- 已启用库存站点由 published 解析方案确定性读取;没有“确认字段对齐”或“任务级更正映射”的 Dify 决策分支。 +- 聊天前端已删除历史 `shipping-inventory-mapping` 消息类型、映射表单、粘贴映射入口和 `align_review / map_infer` 展示分支;订单解析复核卡与库存匹配结果卡继续保留。 - `need_agent` 必须返回布尔值 `True/False`,不要返回字符串 `"true" / "false"`;否则 Dify If-Else 可能把 `"false"` 当作 truthy,导致直连动作分支失效。 - `parse_notice` 是后台解析意图,应进入固定的 `是否待解析通知` 链,不作为直连 Tool 动作。 @@ -3263,9 +3454,6 @@ retry_rpa ----------------------> Tool 重试库存导出 confirm ------------------------> Tool 提交当前任务决策 reject -------------------------> Tool 提交当前任务决策 reparse ------------------------> Tool 提交当前任务决策 -confirm_inventory_mapping -----> Tool 提交当前任务决策 -correct_inventory_mapping -----> Tool 提交当前任务决策 -reparse_inventory -------------> Tool 提交当前任务决策 rematch -----------------------> Tool 重新匹配库存 其他 / 默认 --------------------> Agent 状态输入标准化 ``` @@ -3282,14 +3470,12 @@ rematch -----------------------> Tool 重新匹配库存 | 节点名 | 绑定 Tool | 参数映射 | 说明 | | ------------- | ------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | Tool 重试库存导出 | `submit_decision` | `task_id={{#准备读取任务状态.task_id#}}`;`decision=retry_rpa` | 用户触发重试 RPA 导出库存时使用,真正恢复由后端 RPA workflow 执行 | -| Tool 提交当前任务决策 | `submit_decision` | `task_id={{#准备读取任务状态.task_id#}}`;`decision={{#当前任务动作判断.direct_action#}}` | 用同一个 Tool 节点统一承接 `confirm / reject / reparse / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory` | +| Tool 提交当前任务决策 | `submit_decision` | `task_id={{#准备读取任务状态.task_id#}}`;`decision={{#当前任务动作判断.direct_action#}}` | 用同一个 Tool 节点统一承接 `confirm / reject / reparse` | | Tool 重新匹配库存 | `submit_decision` 或等价恢复入口 | `task_id={{#准备读取任务状态.task_id#}}`;按当前实现映射为重匹配类 decision | 在库存已就绪的前提下请求后端重新执行匹配 | 说明: -- 这里故意**不**把 `confirm_inventory_mapping` 绑定成 `auto_progress`。 -- 原因是“确认字段对齐”语义上属于**确认当前步骤**,更适合显式落到 `submit_decision(confirm_inventory_mapping)`;后续是否自动推进,交给后端状态机或后续 `继续` / Agent 决策处理。 -- 这样可以避免用户只是点击“确认映射”,却在画布层面被直接解释成“立刻推进后续全部动作”。 +- 站点库存无需 Dify 字段确认:发布 Profile 已锁定工作表、表头行和字段目录映射;若需调整,管理员在“库存文件解析方案”创建并发布新版本,再由 `retry_rpa` 重新获取快照。 ##### 节点:直连动作结果标准化 @@ -3693,7 +3879,6 @@ def main(text: str = ""): | -------------------- | --------------------------------- | | `status_raw_json` | `工具结果标准化.raw_json` | | `parsed_raw_json` | `解析结果标准化.raw_json` | -| `inventory_raw_json` | `映射结果标准化.raw_json` | | `fallback_task_id` | `准备读取任务状态.task_id` | 输出: @@ -3791,13 +3976,10 @@ Agent 必开 Tool: Agent 禁用 Tool: - `parse_notice` -- `apply_inventory_mapping` +- `submit_temporary_inventory_mapping_suggestion` 前端动作,不配置为 Agent Tool: -- `upload_inventory_file` -- `paste_inventory_json` -- `edit_inventory_mapping` - `match_inventory` - `generate_excel` - `download_excel` @@ -3820,7 +4002,7 @@ Agent 禁用 Tool: ```text #### 角色 你是 **货代发货通知助手**,通过发货通知 Tool API 处理客户发货指令。需要人工复核时暂停,等待用户明确选择后再继续。 -发货通知已由 **当前对话上传并保存 raw_text**;随后由画布 LLM 节点解析订单需求,并调用 `parse_notice(structured=...)` 落库。你收到 `parse_msg`(或 `get_task_status.message`)后**原文展示**并引导确认。库存 Excel 由用户在当前对话上传后,由画布 **Tool 节点**完成列映射;Agent **禁止**自行推断 `map_json`,也不要脱离既定解析节点重复执行 `parse_notice`。 +发货通知已由 **当前对话上传并保存 raw_text**;随后由画布 LLM 节点解析订单需求,并调用 `parse_notice(structured=...)` 落库。你收到 `parse_msg`(或 `get_task_status.message`)后**原文展示**并引导确认。正式库存优先由库存站点 RPA 导出,并由后端按已绑定解析方案确定性解析;已有任务受控人工上传也使用同一发布方案,成功后直接进入待匹配。普通对话附件只有在用户明确声明库存用途时,才能进入隔离的临时库存分支。Agent 不生成或提交 `map_json`,也不解释为“已识别/已绑定”库存方案。固定 LLM 节点只可基于后端脱敏表头提出候选,候选不能触发发布、绑定、仓库映射或门禁放行。 若用户用自然语言要求“改采购单号 / 改预订单号 / 改料号 / 改数量 / 新增一行 / 删除一行”,应优先调用 `update_notice_fields`、`update_notice_line`、`add_notice_line`、`remove_notice_line` 持久化修改,禁止只在回复里口头改写解析结果。 当 **当前对话** 已上传通知并自动发起首轮续办时,你**不得**再询问用户“是否开始解析”“是否现在开始解析”“请确认是否开始解析”。首轮续办的正确行为是:立即读取 `raw_text` → 由画布 LLM 节点抽取 structured → 调用 `parse_notice(structured=...)` → 再根据返回结果决定是否进入人工确认。只有当 `parse_notice` 或后端状态机明确返回 `needs_human` / `stop_agent_turn=true` 时,才允许进入确认语义。 首层附件分流由 Chatflow 的 Code 节点完成(通知/库存附件 → 引导回 **当前对话** 上传)。你负责第二层业务理解与 Tool 调用,**不要接管首层分流职责**。 @@ -3833,9 +4015,8 @@ Agent 禁用 Tool: 【宿主系统已完成】建 task + raw_text 落库 → Dify LLM 解析订单需求 + parse_notice(structured=...) → submit_decision(confirm) - → Tool 库存上传(**当前对话** 前端)+ apply_inventory_mapping(Tool) - → 【暂停】align_msg - → submit_decision(confirm_inventory_mapping) + → Hxops 后端根据路由结果选择已启用库存站点 + → RPA / 管理端上传库存快照,后端按 published 解析方案确定性解析 → hxops worker 统一续跑匹配、Excel 生成与上传 #### Tool 响应字段 每轮 Tool 调用后必须读取: @@ -3848,8 +4029,8 @@ Agent 禁用 Tool: | `human_options` | 须人工时的选项 | | `action_buttons` | 宿主系统可渲染的按钮配置,Agent 只读取语义,不在正文重复列出 | | `message` | 固定格式人类可读文案(须原文展示) | -| `data.schema_preview` | 表头 + 样例行 | -| `data.field_alignment` | 字段对齐详情 | +| `data.schema_preview` | 管理端样本分析或隔离临时库存的结构预览;正式任务不以此请求人工映射 | +| `data.field_alignment` | 已解析库存与订单字段的只读对照,用于结果解释,不是确认关卡 | #### agent_runtime_context 使用规则 每轮可通过 Query 中的 `HXOPS 运行态上下文` 读取平台注入的 `agent_runtime_context`。该上下文只用于理解现场,不是业务事实源。 @@ -3896,9 +4077,8 @@ Agent 禁用 Tool: 2. 每轮先看 `status`、`stop_agent_turn`、`forbidden_next_tools`、`human_options`;`message` / `parse_msg` / `align_msg` 须原文展示。 3. 工具返回 `needs_human` 或 `stop_agent_turn=true` 时,必须停下等待用户。 4. 工具返回 `forbidden_next_tools` 时,不能继续调用被禁止工具。 -5. 未完成库存字段确认前,不能直接调 `match_inventory`。 -6. `align_review` 首轮:原文展示 `align_msg` 后结束;用户确认后调用 `submit_decision(confirm_inventory_mapping)`。 -7. 后续匹配、Excel、上传由后端 worker 统一续跑;Agent 不在同一轮主导长链路推进。 +5. 正式库存仅在后端确认 published 解析方案和结构校验通过后进入匹配;Agent 不得提交字段映射。 +6. 后续匹配、Excel、上传由后端 worker 统一续跑;Agent 不在同一轮主导长链路推进。 8. 若 `get_task_status` 返回 `needs_human` 或 `failed`,按返回结果停下并引导用户下一步。 9. 存在 shortage 时,不能默认继续发货。 10. 上传是否成功只能以后端 `get_task_status` 或上传回调结果为准。 @@ -3906,9 +4086,9 @@ Agent 禁用 Tool: 12. 解析修订:自然语言改 PO/料号/数量/增删行 → `update_notice_*`;禁止只在回复里口头改写。 13. 禁止 Agent 调用 `create_batch` / `create_task`。 14. 通知文件原始上传由 **当前对话** 完成;订单需求首轮解析由 Dify LLM 节点产出 structured,再由 `parse_notice(structured=...)` 落库。 -15. 禁止自行推断 `map_json`。 -16. 若 `human_options` 出现 `upload_inventory_file / paste_inventory_json / retry_upload / generate_excel / download_excel / mark_manual_uploaded / refresh` 等前端动作,只负责解释并引导,不得把它们当作 Tool 调用。 -17. 若 Tool 返回 `action_buttons` / `human_options`,最终回复正文**禁止**生成任何操作菜单、编号选项、按钮清单或“推荐下一步”动作列表。不要输出类似“推荐下一步:”“请选择以下操作:”“请选择操作:”“1. 重新上传库存”“2. 更正映射”“3. 重新匹配”“4. 驳回”。正文只说明当前状态、业务原因和影响;如需要用户操作,只写“请使用下方按钮继续”。可点击按钮由宿主系统根据 `action_buttons` 渲染。 +15. 禁止自行推断字段映射、目录字段 ID 或任何临时映射 JSON。 +16. 若 `human_options` 出现 `retry_rpa / retry_upload / generate_excel / download_excel / mark_manual_uploaded / refresh` 等前端动作,只负责解释并引导,不得把它们当作 Tool 调用。 +17. 若 Tool 返回 `action_buttons` / `human_options`,最终回复正文**禁止**生成任何操作菜单、编号选项、按钮清单或“推荐下一步”动作列表。正文只说明当前状态、业务原因和影响;如需要用户操作,只写“请使用下方按钮继续”。可点击按钮由宿主系统根据 `action_buttons` 渲染。 18. 禁止依赖 `hxops_context`;画布中所有上下文读取必须使用 `agent_runtime_context` 与 `parse_agent_runtime_context`。 #### 查询模板 HXOPS 运行态上下文: @@ -3970,18 +4150,21 @@ Tool 提交订单抽取 -> 订单抽取提交结果标准化 附件意图分类 -> 分支调度 分支调度 -> 主路由分支节点 -主路由分支节点(inventory_path) -> 库存任务检查 -库存任务检查 -> 是否已有库存绑定任务 -是否已有库存绑定任务(false) -> 无TASK_ID提示 -是否已有库存绑定任务(true) -> Tool 读取库存 schema 预览 -Tool 读取库存 schema 预览 -> 库存 schema 标准化 -库存 schema 标准化 -> 库存列映射 LLM -库存列映射 LLM -> 列映射 JSON 标准化 -列映射 JSON 标准化 -> 库存列映射是否成功 -库存列映射是否成功(false) -> 列映射失败回复 -库存列映射是否成功(true) -> Tool 应用库存列映射 -Tool 应用库存列映射 -> 映射结果标准化 -映射结果标准化 -> Agent 状态输入标准化 +顶层能力路由(temporary_inventory_new) -> 创建临时库存候选会话 +顶层能力路由(temporary_inventory_confirm) -> 读取临时库存分析 +创建临时库存候选会话 -> 临时库存分析结果标准化 +读取临时库存分析 -> 临时库存分析结果标准化 +临时库存分析结果标准化(来自创建) -> 是否可复用已发布方案 +是否可复用已发布方案(exact) -> 临时库存结果回复 +是否可复用已发布方案(无 exact 且 inventory_candidate) -> 陌生表头候选解释 LLM +陌生表头候选解释 LLM -> 提交临时映射建议 +提交临时映射建议 -> 临时映射建议结果标准化 +临时映射建议结果标准化 -> 临时库存结果回复 +临时库存分析结果标准化(来自读取) -> 待确认状态校验 +待确认状态校验(confirmable) -> 确认临时库存使用 +待确认状态校验(invalid) -> 临时库存结果回复 +确认临时库存使用 -> 临时库存确认结果标准化 +临时库存确认结果标准化 -> 临时库存结果回复 主路由分支节点(direct_answer) -> 直接回复(引导) @@ -3996,9 +4179,6 @@ Tool 读取任务状态 -> 工具结果标准化 当前任务直连动作分支(confirm) -> Tool 提交当前任务决策 当前任务直连动作分支(reject) -> Tool 提交当前任务决策 当前任务直连动作分支(reparse) -> Tool 提交当前任务决策 -当前任务直连动作分支(confirm_inventory_mapping) -> Tool 提交当前任务决策 -当前任务直连动作分支(correct_inventory_mapping) -> Tool 提交当前任务决策 -当前任务直连动作分支(reparse_inventory) -> Tool 提交当前任务决策 当前任务直连动作分支(rematch) -> Tool 重新匹配库存 Tool 重试库存导出 -> 直连动作结果标准化 Tool 提交当前任务决策 -> 直连动作结果标准化 @@ -4040,8 +4220,10 @@ Agent 状态输入标准化 -> 货代续办 Agent - [ ] Start 节点只配置 `agent_runtime_context`,未配置 `hxops_context` - [ ] `Tool 解析运行态上下文` 已绑定 `parse_agent_runtime_context` -- [ ] `Tool 解析运行态上下文.paths` 已包含 `refs.capability / refs.intake_nos` -- [ ] `运行态上下文标准化` 已输出 `capability / intake_nos_json` +- [ ] `Tool 解析运行态上下文.paths` 已包含 `refs.capability / refs.intake_nos / refs.temporary_inventory_asset_no / refs.temporary_inventory_session_no` +- [ ] `运行态上下文标准化` 已输出 `capability / intake_nos_json / temporary_inventory_asset_no / temporary_inventory_session_no` +- [ ] HXOPS 可从当前聊天数据库恢复未过期、仍待确认的 `temporary_inventory_session_no`;已确认/拒绝/过期会话不再注入 +- [ ] `临时库存续办意图判断` 只接受明确的“确认本次临时使用/采用该方案”,含糊“继续”或普通订单操作不会进入确认 Tool - [ ] `顶层能力路由` 判断 `order_extraction` - [ ] `order_extraction_path` 位于用户意图、任务读取、库存和 Agent 节点之前 - [ ] `Tool 读取订单抽取上下文` 只传原始 `agent_runtime_context` @@ -4068,17 +4250,24 @@ Agent 状态输入标准化 -> 货代续办 Agent - [ ] `解析结果标准化` 代码正确 - [ ] `直连动作结果标准化` 代码正确 - [ ] `Agent 状态输入标准化` 代码正确 -- [ ] `库存任务检查` 代码正确 -- [ ] `库存 schema 标准化` 代码正确 -- [ ] `库存列映射 LLM` Prompt 正确 -- [ ] `列映射 JSON 标准化` 代码正确 -- [ ] `映射结果标准化` 代码正确 +- [ ] 临时库存分支只在用户明确声明对话 `.xls/.xlsx/.csv` 为库存文件后以 `temporary_inventory` 能力进入 +- [ ] `创建临时库存候选会话` 不接收文件路径、二进制或库存明细 +- [ ] `创建临时库存候选会话` 与 `读取临时库存分析` 的 Dify 输出均先按 `text` JSON 标准化,未直接引用假定的 Tool 顶层字段 +- [ ] 新文件标准化结果才进入 `是否可复用已发布方案`;跨回合读取结果直接进入 `待确认状态校验`,不会重复调用 LLM 或再次保存映射 +- [ ] `待确认状态校验` 只放行 `awaiting_profile_confirmation`(且存在唯一 exact 方案)或 `awaiting_mapping_confirmation` +- [ ] `陌生表头候选解释 LLM` 输入含 `available_inventory_fields`,输出只使用库存字段目录 ID +- [ ] `陌生表头候选解释 LLM` 不接收 `sample_rows_json`、`sample_values`、文件路径或库存明细 +- [ ] `提交临时映射建议` 已绑定 `submit_temporary_inventory_mapping_suggestion`,未绑定旧 `apply_inventory_mapping` +- [ ] `提交临时映射建议` 输出先经 `临时映射建议结果标准化` 解析 Tool `text` +- [ ] `确认临时库存使用` 已绑定 `confirm_temporary_inventory_use`,只在用户明确确认后调用,并使用恢复的临时会话号 +- [ ] `确认临时库存使用` 输出先经 `临时库存确认结果标准化`;成功只描述临时质量审计,不描述为已匹配或已绑定 +- [ ] 临时候选建议/确认链在展示结果后结束,不进入任务状态机、匹配、导出或 RPA - [ ] `是否进入 Agent` 与 `当前任务直连动作分支` 条件正确 - [ ] `Tool 提交当前任务决策` 已绑定 `decision={{direct_action}}` - [ ] 直连动作分支仅绑定当前允许保留的确认/决策类 Tool - [ ] Agent 已绑定必开 Tool(含 `parse_agent_runtime_context`) -- [ ] Agent 未绑定 `parse_notice / apply_inventory_mapping` -- [ ] Agent 未误绑定 `upload_inventory_file / paste_inventory_json / retry_upload / generate_excel / download_excel / mark_manual_uploaded / refresh` +- [ ] Agent 未绑定 `parse_notice / apply_inventory_mapping / submit_temporary_inventory_mapping_suggestion` +- [ ] Agent 未误绑定 `retry_upload / generate_excel / download_excel / mark_manual_uploaded / refresh` ##### 运行验收矩阵 @@ -4088,11 +4277,11 @@ Agent 状态输入标准化 -> 货代续办 Agent | --- | --- | --- | --- | --- | --- | --- | | 继续处理 | `继续处理` | `get_task_status` | 是,直连 Tool 读状态 | `agent_runtime_context.refs.task_no` 或 `reference_context.focus_object.id` | 不改写任务;返回当前阶段、检查点、可用动作 | 待实测 | | SN-... 读状态 | `SN-20260617-ABCDEFGH` | `get_task_status` | 是,直连 Tool 读状态 | 文本中提取到的 `SN-...` | 不改写任务;返回该任务状态,不切换其他任务 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_get_task_status_accepts_task_no_anchor` | -| 确认 / 驳回 / 重匹配直连 | `确认` / `驳回` / `重新匹配` / `rematch` | `submit_decision` | 是,直连决策 Tool | 当前任务或显式 `SN-...` | 按状态机推进;`rematch` 清理 shortage 并重新入队当前任务 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_submit_decision_rematch_is_direct_recovery_entry` | -| shortage 阻断 | shortage review 后输入 `继续` 或自动续跑 | `match_inventory` / `submit_decision` 返回门禁 | 是,命中状态机门禁后停止 | 当前任务 | `status=needs_human`;禁止 `generate_shipment_excel` / `upload_to_freight`;不生成 Excel | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_shipping_notice_match_shortage_needs_human` | +| 确认 / 驳回 / 重匹配直连 | `确认` / `驳回` / `重新匹配` / `rematch` | `submit_decision` | 是,直连决策 Tool | 当前任务或显式 `SN-...` | 按状态机推进;`rematch` 清理旧结果并同步重算当前任务 | 后端通过:`test_contract_dynamic_order_shortage_and_rematch_recompute_inventory`;Dify 直连分支待手工实测 | +| shortage 阻断 | shortage review 后输入 `继续` 或自动续跑 | `match_inventory` / `submit_decision` 返回门禁 | 是,命中状态机门禁后停止 | 当前任务 | `status=needs_human`;禁止 `generate_shipment_excel` / `upload_to_freight`;不生成 Excel | 后端通过:`test_contract_dynamic_order_shortage_and_rematch_recompute_inventory`;Dify 停止本轮待手工实测 | | 多任务只推进 focus task | 多票批次中输入 `继续处理` | `get_batch_status` + 当前 focus 的 `get_task_status` | 是,先读状态再决定 | `batch.current_focus_task_no` | 每轮只围绕一个 focus task;读批次状态不循环推进整批 | 通过:`PYTHONPATH=. pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_batches.py -q`;`test_contract_batch_status_keeps_single_focus_without_advancing_other_tasks` | -| 库存上传链路 | 上传 `.xlsx/.csv` | `get_inventory_schema_preview` → 映射 LLM → `apply_inventory_mapping` | 否,进入库存专用分支,不走自由 Agent | 当前任务 / 所属批次库存快照 | 生成 schema preview;应用映射后进入 `align_review` 或后端续跑 | 待实测 | -| 字段对齐人工门 | `apply_inventory_mapping` 返回 `align_review` 后输入 `确认` | `submit_decision(decision=confirm_inventory_mapping)` | 是,直连决策 Tool | 当前任务 | 停住等待确认;确认后交由 hxops worker 续跑匹配 / 导出 / 上传 | 待实测 | +| 对话临时库存分析 | 用户上传 `.xls/.xlsx/.csv` 并明确声明库存文件;下一轮明确确认本次临时使用 | `create_temporary_inventory_session` → Tool text 标准化 →(无 exact)候选 LLM → `submit_temporary_inventory_mapping_suggestion` → 下一轮由 HXOPS 恢复会话号 → `confirm_temporary_inventory_use` | 是,不进入自由 Agent | 数据库恢复的临时会话号 | 仅保存待确认候选和确认质量审计;不创建正式快照、不匹配、不导出 | 后端跨回合锚点与隔离测试通过;Dify 画布待手工实测 | +| 正式库存站点解析 | RPA 或管理端为已启用站点导入快照 | Hxops 后端 `validate_production_inventory_structure` → published Profile | 不经 Dify | 站点 + Profile + 快照 | 使用指定工作表、表头行和字段目录映射;结构漂移则阻断 | 后端等价测试通过 | | Tool 人工门收口 | 任一 Tool 返回 `needs_human` 或 `stop_agent_turn=true` | 工具结果标准化 | 是,硬停止本轮 | 当前任务 | 本轮不再继续调用后续 Tool | 待实测 | | forbidden_next_tools 门禁 | Tool 返回 `forbidden_next_tools` | 工具结果标准化 | 是,硬门禁 | 当前任务 | 画布不调用被禁止 Tool | 待实测 | | need_agent 布尔分流 | 直连动作判断节点输出 | `是否进入 Agent` | 视分支结果 | 当前任务 | `need_agent` 必须为布尔值,节点按布尔条件分流 | 待实测 | @@ -4105,10 +4294,10 @@ Agent 状态输入标准化 -> 货代续办 Agent - 预期:按该任务号读取状态 3. 对一个尚未解析的通知任务发送 `继续处理` - 预期:进入 `提取通知原文 -> 订单需求解析 LLM -> Tool 解析发货通知` -4. 上传一个库存 `.xlsx` - - 预期:进入 `get_inventory_schema_preview -> 库存列映射 LLM -> apply_inventory_mapping` -5. 在字段对齐确认状态下输入 `确认` - - 预期:不进入 Agent,直接走 `Tool 提交当前任务决策(decision=confirm_inventory_mapping)` +4. 用户上传一个临时库存 `.xls`、`.xlsx` 或 `.csv` 并明确发起分析 + - 预期:进入 `create_temporary_inventory_session`;exact 候选直接展示,无 exact 时才进入 `陌生表头候选解释 LLM -> submit_temporary_inventory_mapping_suggestion`,随后结束本轮 +5. 正式库存站点 RPA 导出或管理端上传快照 + - 预期:不进入 Dify;后端按该站点已发布解析方案确定性解析,不能使用 LLM 或临时映射 6. 在库存待匹配状态下输入 `开始匹配` - 预期:Agent 先解释当前状态,并按当前后端契约提交对应决策或提示等待 worker 续跑 7. 在 shortage_review 状态下输入 `重新匹配` @@ -4188,8 +4377,6 @@ Agent 状态输入标准化 -> 货代续办 Agent - `parse_review` - `upload_req` / `inventory_pending` -- `map_infer` -- `align_review` - `ready_to_match` - `ready_to_export` / `export_ready` - `waiting_upload` @@ -4244,7 +4431,7 @@ shortage 规则: - `step1_notice_submit` / `step2_parse_confirm`:发货通知解析中、解析完成 - `step3_inventory_prepare`:库存文件上传、RPA 库存导出等待、库存快照读取完成 -- `step4_align_confirm`:字段对齐待确认 +- `step4_align_confirm`:库存结构与必要字段校验(正式库存自动完成,不设置人工映射关卡) - `step5_match_inventory`:库存匹配中、匹配完成、缺口待人工处理 - `step6_generate_file`:发货 Excel 生成中、生成完成 - `step7_upload_freight`:RPA 上传中、手工上传确认完成、上传失败待人工处理 @@ -4292,12 +4479,12 @@ shortage 规则: - **三层进度展示**:当前已具备批次层摘要、任务层七步 Stepper,以及统一的 `step_payload_json.current_step_progress` 步骤内进度协议;但“第 `i/n` 个文件解析中”“匹配严格逐行 `x/y`”这类更细运行态仍未完全达到原型描述粒度。 - **工作台职责收敛**:正式口径应收敛为“**对话主路径 + 轻量批次工作台**”;聊天页右侧轻量工作台允许执行动作,但只负责渲染后端 `ui_state.action_buttons` 与查看类辅助入口,不能本地二次推导“继续处理 / 重试 RPA / 查看详情”等业务按钮;独立详情页仍主要承担只读排查与管理视角。 -- **任务列表筛选口径**:工作台已支持按部分 `process_status` 过滤,但尚未完全覆盖原型验收视角下的全部用户态状态。 -- **解析复核状态命名**:前端个别展示逻辑仍存在旧状态名 / 特殊判断,和当前状态机中的 `parse_review`、`rsv_required` 等口径有进一步统一空间。 +- **任务列表筛选口径**:工作台已覆盖全部可展示流程状态;`shortage_review` 由后端按 `review_status / pending_human_reason` 复合过滤,其余选项按真实 `process_status` 过滤。状态目录由 `shippingTaskStatuses.spec.ts` 锁定。 +- **解析复核状态命名**:前端使用当前 `parse_review / rsv_required / shortage_review` 口径,已移除任务级库存映射旧状态。 ### 3.3 尚不能判定为已完全落地的项 -- **四语言验收**:原型要求 `zh-CN / zh-TW / en-US / th-TH` 全量覆盖;本次对齐主要核了流程与接口,尚未逐条完成文案完整性复核。 +- **四语言验收**:货代配置、货代聊天和货代工作台三棵业务文案树已完成 `zh-CN / zh-TW / en-US / th-TH` 键集合一致性校验,并由 `shippingI18nParity.spec.ts` 持续验证。 - **库存自动抓取业务闭环**:代码层已具备后端库存准备、RPA 回调与自动推进入口,但是否达到真实业务可用,还依赖货代库存导出 SOP、正式 RPA 脚本和运行环境联调。 - **正式方案 P0 验收项**:从代码结构看已接近“对话主路径 + 轻量批次工作台”的目标要求,但像“不中断续办”“多票并行下的细粒度进度提示”“轻量工作台与对话聚焦任务的一致性”等,仍需要按原型测试用例逐项实测,而不能仅凭仓库代码直接视为全部完成。 @@ -4323,8 +4510,10 @@ shortage 规则: - `update_notice_line` - `add_notice_line` - `remove_notice_line` -- `get_inventory_schema_preview` -- `apply_inventory_mapping` +- `create_temporary_inventory_session`(用户明确声明的临时分析) +- `get_temporary_inventory_session`(用户明确声明的临时分析) +- `submit_temporary_inventory_mapping_suggestion`(用户明确声明的临时分析) +- `confirm_temporary_inventory_use`(用户明确确认临时使用) - `submit_decision` - `get_task_status` - `get_batch_status` @@ -4332,26 +4521,21 @@ shortage 规则: 说明: - RPA 回调、主推进工具、批量文件上传接口也不在 Dify 导出范围内 +- 任务级 `parse_inventory`、`get_inventory_schema_preview` 与 `apply_inventory_mapping` 已移除,不纳入 Dify 目标导出或正式库存站点链路。 +- `confirm_inventory_mapping`、`correct_inventory_mapping` 仅作为废弃输入被后端拒绝,前端不再生成;`reparse_inventory` 保留为“重新上传库存”,它只停用当前库存 link、清理匹配/导出派生结果并返回文件选择引导,不进入列推断。 +- 缺库存与重新上传检查点同时提供“选择库存文件”和“重新获取库存”;任务级文件仍使用当前库存站点的 published Profile 校验。 ### 3.2 大库存 Excel 特殊处理 -`upload_inventory_file` 为 multipart 接口,适合: +临时库存文件由宿主前端在用户明确声明库存用途后上传为用户私有资产;正式库存文件可由库存站点 RPA、管理端或已有任务的受控人工上传进入快照链路。两者均不作为 Agent OpenAPI Tool 让 LLM 携带 Excel 内容。临时分析候选链路为: -- 聊天前端直接上传 -- Dify HTTP 节点上传 +1. 前端上传用户私有临时文件 +2. `create_temporary_inventory_session` +3. exact 时展示可复用方案;否则 LLM 按 `available_inventory_fields` 产生目录 ID 映射候选 +4. `submit_temporary_inventory_mapping_suggestion` +5. 用户确认临时使用;不得发布、绑定、创建正式快照或续跑订单匹配 -不适合: - -- 作为 Agent OpenAPI tool 让 LLM 直接携带 Excel 内容 - -目标推荐链路: - -1. 上传库存文件 -2. `get_inventory_schema_preview` -3. LLM 推断字段映射 -4. `apply_inventory_mapping` -5. 用户确认字段映射 -6. hxops worker 统一续跑匹配 +正式库存链路为:库存站点 RPA 快照或已有任务受控人工上传 → 后端按站点 published Profile 执行结构门禁与确定性解析 → 后端匹配与导出。 ### 3.3 后端模块分层(已落地) @@ -4380,7 +4564,7 @@ API 层 - API 写操作只 import `tools.*`;读操作优先 import `query_service.*` - `query_service` 提供 `TOOL` / `SUMMARY` / `DETAIL` 投影;Tool `data` 经 `user_facing_status.strip_internal_task_fields` 剔除 `process_status` 等内部码 -- checkpoint 使用 `constants.py` 短名(如 `align_review`、`upload_req`、`map_infer`),与 `state_machine.CHECKPOINT_REGISTRY` 对齐 +- checkpoint 使用 `constants.py` 短名(如 `parse_review`、`inventory_pending`、`upload_req`),与 `state_machine.CHECKPOINT_REGISTRY` 对齐 **批次能力(Tool API 已补齐)** @@ -4392,7 +4576,7 @@ API 层 ### 3.4 联调验收重点 - 多文件上传创建 1 个 batch、多个 task -- 当前聚焦 task 切换后,确认/上传仍作用于该 task;库存文件上传和列映射作用于该 task 所属批次库存快照 +- 当前聚焦 task 切换后,确认/上传仍作用于该 task;正式库存文件只按库存站点绑定的已发布解析方案确定性解析 - 全流程可在无侧边栏前提下于对话内闭环 - 自动上传成功、失败、人工接管三条路径可验证 - Dify 在 `needs_human` 与 `forbidden_next_tools` 返回时会正确停下 @@ -4440,31 +4624,30 @@ API 层 | `backend/tests/test_shipping_notice_query_service.py` | 读模型投影与批次汇总单测 | | `backend/tests/test_shipping_notice_batches.py` | 批次建单 / focus 切换测试 | | `backend/tests/test_shipping_notice_inventory_rpa_workflow.py` | RPA 库存触发与回调单测 | -| `backend/tests/test_shipping_notice_inventory_sources_config.py` | 库存源 JSON 配置加载与校验单测 | -| `backend/tests/test_shipping_notice_inventory_snapshot_reuse.py` | 库存快照 TTL 复用与 link 审计单测 | +| `backend/tests/test_shipping_inventory_configuration.py` | 库存 Source、RPA Profile、外部系统仓库映射与凭据安全单测 | +| `backend/tests/test_shipping_inventory_routing_engine.py` | 通用路由规则引擎单测 | | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | | `scripts/rpa/freight_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | -| `backend/config/shipping_inventory_sources.yaml` | 库存 RPA 源配置(新增 Warehouse 只改此 YAML) | | `seed_shipping_notice_agents.py` | Agent 注册脚本 | --- ## 5. 库存 RPA 独立化与快照复用(2026-07) -### 5.1 配置文件 +### 5.1 数据库主数据 -- 路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`) -- **新增 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) +- `ShippingInventorySource` 是业务主键;`connector_type` 仅允许 `dbs` / `crane`。 +- `ShippingRpaProfile` 保存登录 URL、加密凭据和连接级登录配置;同一 connector 可配置多个 Profile。 +- `ShippingInventorySource` 保存 DBS 报表路径、查询参数和识别别名;Driver 选择器、下载方式和等待策略不得作为业务配置入库。 +- Source 使用 `warehouse_resolution_mode`:`fixed` 直接给出 Warehouse;`inventory_match`(Crane)不预维护 Warehouse 清单。 +- 外部系统仓库映射保存在 `shipping_inventory_external_mappings`,精确 `source + warehouse` 优先,随后回退 Source 默认映射;仅供内部服务使用,不决定调拨。 ### 5.2 快照复用规则 -1. `ensure_inventory(mode=auto)` 在库存源**已稳定**后,优先 `find_latest_ready_snapshot(source_code, site_id, warehouse_id)` +1. `ensure_inventory(mode=auto)` 在库存源**已稳定**后,优先 `find_latest_ready_snapshot(source_code, warehouse_id)`;动态 Source 初始 Warehouse 可为空。 2. 未过期快照 → `link_snapshot_to_task(reason=reuse_latest)` → 映射/匹配 -3. 过期或缺失 → 触发 RPA(单 task trigger 或定时 batch trigger) +3. 过期或缺失 → 标记缺库存,等待排程导出或用户明确 `retry_rpa` 4. `retry_rpa` **强制跳过**快照缓存 5. 人工上传仍可覆盖;终态任务不可 relink @@ -4483,18 +4666,45 @@ API 层 ### 5.4 审计字段 -- `shipping_inventory_files`:`warehouse_id`、`site_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`、`identity_status` -- `shipping_task_inventory_links`:`link_reason`、`matched_source_code`、`matched_site_id`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`、身份校验字段 +- `shipping_inventory_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`、`identity_status` +- `shipping_task_inventory_links`:`link_reason`、`matched_source_code`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`、身份校验字段 ### 5.5 订单解析阶段库存源判定(2026-07) > 详细方案见 [`inventory_source_plan.md`](./inventory_source_plan.md)。 -1. **`parse_notice` 内 adjudicate**:读取任务 `destination_*` 与 YAML `match`/`match_aliases`,产出 `InventorySourceAdjudication`(写入线索/候选)。 +1. **`parse_notice` 内 adjudicate**:读取任务/订单行事实并评估已发布通用路由规则,产出 `InventorySourceAdjudication`(写入线索/候选)。 2. **先解析复核,再定库存源**:低置信度先 `checkpoint=parse_review`(含重新解析);解析通过(人工确认或高置信度自动过)后,若源未稳定再进 `inventory_source_review`。RPA 等后续步骤仍要求 `inventory_source_status ∈ {resolved, user_confirmed}`。 - - **问题清单**:`ui_state.summary.issues` 汇总当前检查点原因 + parse warnings;解析复核阶段可提示「确认后再选库存源」;存量 `pending_parse_review_after_source` 仍兼容旧顺序。 -3. **独立字段为真相源**:`inventory_source_code`、`inventory_site_id`、`inventory_warehouse_id` 等存于 `shipping_tasks` 列,gate 不读 `step_payload_json`。 -4. **用户只确认 source_code**:`confirm_inventory_source` 根据编码回填 site/warehouse;路由指纹变更时要求重确认(`SHIPPING.INVENTORY_SOURCE_CHANGED`)。 + - **问题清单**:`ui_state.summary.issues` 汇总当前检查点原因 + parse warnings;解析复核阶段提示「确认后再选库存源」。不保留“先库存源、后解析复核”的旧顺序或延后标记。 +3. **独立字段为真相源**:`inventory_source_code`、`inventory_connector_type`、`inventory_warehouse_id` 存于 `shipping_tasks` 列,gate 不读 `step_payload_json`。 +4. **用户只确认 source_code**:`confirm_inventory_source` 固化 Source;fixed 模式回填 Warehouse,动态模式在库存行 `reservation_id + part_number` 匹配后回填。 5. **硬 Gate**:`inventory_rpa_workflow`、`inventory_workflow`、`fulfillment_workflow`、`progress_workflow` 入口均调用 `assert_inventory_source_gate`。 -6. **快照复用键**:`find_latest_ready_snapshot(source_code, site_id, warehouse_id)`;link 时做 identity check。 -7. **迁移**:`b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields`。 +6. **快照复用键**:`find_latest_ready_snapshot(source_code, warehouse_id)`;link 时做 identity check。 +7. **迁移**:`2b3c4d5e6f7a_add_shipping_inventory_configuration`、`3c4d5e6f7a8b_remove_shipping_inventory_site_id`、`4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency`。 + +### 5.6 Bill-to / Ship-to 客户主数据匹配(2026-07) + +订单 Schema 仍是全局唯一的一组业务字段,不按 EML/PDF 或库存源拆分。当前客户相关头字段为: + +| 字段 | 责任 | +| --- | --- | +| `bill_to_customer` / `bill_to_customer_code` / `bill_to_source_system` | 保存账款客户原文名称、外部编码及其明确来源系统 | +| `ship_to_customer` / `ship_to_code` / `ship_to_source_system` | 保存送货对象原文名称、外部站点编码及其明确来源系统 | +| `ship_to_address` | 保存逐字送货地址证据,供站点复核 | + +`customer_short_code` 不属于订单解析字段。简称只能从 `ShippingCustomer.short_code` 派生,并在匹配确认时写入快照。 + +匹配顺序: + +1. Bill-to:`source_system + ShippingCustomerExternalRef.legacy_customer_key` → 标准名称 → 已审核名称别名。 +2. Ship-to:`source_system + ShippingCustomerSiteIdentifier(external_code)` → `ShippingCustomerSite.site_code` → 站点标准名称 → 已审核站点名称别名。 +3. 结果按角色写入 `shipping_order_customer_matches`,状态为 `unmatched / unique_candidate / ambiguous / confirmed`;Ship-to 人工确认必须同时校验站点属于所选启用客户。 +4. Candidate API 返回 `customer_matches` 供界面展示原文、标准客户、简称、站点与状态;确认接口为 `POST /api/workspace/shipping-order-extractions/{extraction_id}/customer-matches/{role}/confirm`,并校验 Extraction 所属 Intake 的用户权限。 +5. 唯一候选不绕过既有客户质量门禁。Task 建立后仍由客户确认链决定是否绑定业务归属客户和生成业务编号。 + +#### Dify 手工配置要求 + +- 调用动态订单契约时按字段配置抽取上述 7 个字段,每个非空值必须提供可在 EML 正文或附件中逐字命中的 evidence quote。 +- 不输出 HXOPS 客户/站点主数据 ID,不输出客户简称,不根据名称猜测来源系统;原文没有 Code 或 Source System 时留空。 +- Dify 只负责候选抽取;后端负责 evidence 校验、EML/PDF 交叉裁决、客户主数据匹配、歧义判断与最终确认。 +- Reservation ID 使用普通文本规则;Dify 仍须按字段识别说明排除 Allocation ID、UUID 和内部主键,后端安全校验作为兜底。 diff --git a/docs/funclist.md b/docs/funclist.md index 9faefe39..1ce05ce2 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -68,26 +68,48 @@ | 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台与独立任务页共用解析卡,展示内部/客户/AWS 料号、Reservation、库存源线索、门禁与证据;Candidate 审核非编辑态同步展示关键行 | | 规范订单行双写与影子校验 | 已实现 | 默认 `WRITE_MODE=dual` + `READ_MODE=shadow`;解析/改单/回填/重解析经 `task_line_store` 同事务双写;历史回填与 `verify_shipping_task_lines` 支持干跑/续跑;shadow 对外仍读 JSON 并记 checksum;业务读路径统一走 store;观察窗口零差异后切 `READ_MODE=table`;`lines_json` 保留作回滚快照 | | 订单字段对账与冲突复核 | 已实现 | Candidate→Task 字段级自动补空/冲突落库;未解决冲突阻断库存/匹配/导出;workspace 冲突查询与解决 API;改单支持 `expected_order_data_version` 与幂等键;工作台解析卡可解决冲突 | -| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | -| 订单解析阶段库存源判定 | 已实现(v2 单线索字段) | 订单行仅使用 `inventory_source_hint` 匹配库存源 `match_aliases`;正式路由结果独立写入任务库存源字段,连接器字段保持 `connector_type` / `inventory_connector_type` | +| 库存源/RPA Profile 数据库主数据 | 已实现 | 以 Inventory Source 为业务主键;Source 持久化 DBS 报表路径、查询参数与识别别名;RPA Profile 仅保存登录、密文凭据与连接级登录配置;YAML 不再作为运行时真相源 | +| 货代配置工作台 | 已实现 | 管理端仅保留“货代配置”入口;订单解析作为内部首个工作区,与库存文件解析方案、发货模板、库存站点和路由规则按业务链路集中维护。库存站点支持停用保存、异步测试导出、结构分析、解析方案确认绑定及独立启用门禁 | +| 发货模板可读配置 | 已实现 | 模板上传后读取工作表与首行表头供选择目标列;映射逐项展示字段说明和来源分组;文件名规则显式展示可用业务变量,默认推荐 `{business_no}.xlsx` | +| 通用库存源路由规则 | 已实现 | 可配置、版本化规则从订单事实产生 `source_code` 候选;Reservation ID 仅为首批兜底事实字段 | +| 库存文件优先匹配 | 已实现 | 正常货代流程按 `source_code` 匹配最新有效库存文件,不自动触发 RPA;RPA 仅由排程或用户手动刷新执行 | | 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | | 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 | +| 唯一订单 Schema 与动态字段基础 | 已实现 | 管理员以固定高度字段字典维护系统标识、版本显示名称、位置、格式和识别规则;两个名称不受“纳入当前版本”开关限制,未纳入字段配置可保存但不进入发布契约;系统标识可重命名且历史快照保留旧值,位置/类型与已发布版本保持安全门禁;管理端提供分页版本历史、严格只读快照、任意版本间服务端字段级差异、追加式配置审计时间线、版本实际使用统计和单次解析证据链;历史发布/退役版本可复制为新草稿,URL 可按业务版本号恢复;新版本移除下游引用字段时阻断发布 | +| Schema 驱动 Dify 订单解析 | 已实现 | Tool 返回 published 动态字段契约;Dify 按稳定 field_id 提交多 Document Observation;后端完成类型校验、原文核验、跨文档裁决和类型化值持久化 | +| 动态订单字段驱动库存源路由 | 已实现 | 路由条件选择 published 订单稳定 field_id;运行时从 Task 当前 Extraction 的类型化 FieldValue 读取;系统事实仅保留受控枚举 | +| 可复用库存解析 Profile | 已实现 | 管理端通过订单字段和库存标准字段结构化选择器版本化维护表头、列映射和 match_keys;多个 published 版本可并存,库存源显式迁移版本;引用中版本不可退役,正常库存源解析无需 LLM | +| 库存字段目录 | 已实现 | 作为“库存映射”的子功能以空目录启动,字段名称、说明、格式、用途和顺序完全由用户维护;程序只控制匹配、数量、仓库识别和一般信息四种用途。解析方案、库存行、匹配键和发货模板全程使用库存字段目录 ID;未引用字段可物理删除,当前配置引用字段禁止删除、退役或改变能力用途 | +| 库存样本结构识别与方案复用 | 已实现 | 管理员上传 `.xls/.xlsx/.csv` 后由后端分析工作表、候选表头、真实栏位、少量样例、类型和空值率;同名用户字段可确定性预填,陌生表头由管理员选择或 Dify 给候选,不内置固定业务字段词典;已发布方案按实际使用的匹配/数量表头判断完全一致或兼容,确认只写审计、不自动绑定库存站点 | +| 库存站点测试导出 | 已实现 | 停用库存站点可发起异步 RPA 测试导出;测试文件仅用于结构识别和解析方案确认,不进入正式库存快照、订单匹配或发货导出;只能确认本次推荐的已发布方案,站点配置变更或启用后旧测试自动失效 | +| 库存站点启用验证与仓库映射门禁 | 已实现 | 启用前按用户字段用途复核至少一个匹配字段、唯一数量字段及动态仓唯一仓库识别字段,验证发货模板库存字段可由解析方案提供;固定仓要求精确或默认仓库映射,动态仓要求覆盖样例仓库;只提示缺失映射,绝不自动臆造 | +| 正式库存文件结构漂移门禁 | 已实现 | 每次 RPA 正式导出及缓存快照重读均用已绑定库存文件解析方案复核/解析格式、工作表、表头和核心栏位;完全一致放行,非关键栏位变化记录差异后放行,关键变化阻断快照和库存匹配;正式库存站点运行期不再自动猜列或接收 LLM 映射覆盖 | +| 陌生表头 LLM 候选解释(Dify 手工配置) | 已文档化 | 默认关闭;用户明确声明对话附件为库存文件且后端无精确方案时,可对脱敏真实表头给出本次临时候选;管理员也可在库存文件解析方案草稿中主动请求候选。Dify 不能发布方案、绑定库存站点、创建仓库映射、调用旧库存映射 Tool 或放行结构漂移 | +| 对话临时库存文件受控解析 | 已实现 | 用户上传 `.xls/.xlsx/.csv` 表格时必须先明确声明为库存文件,系统不会按后缀猜测用途;后端创建当前用户和当前聊天会话隔离的临时文件并确定性检查结构与库存最低特征。跨回合时由 HXOPS 数据库恢复最新待确认会话号,不依赖 Dify 隐式记忆;普通消息不会因此自动进入确认。无完全匹配方案时 Dify 只能基于真实表头、类型/空值率和字段目录提交受控候选映射,用户明确确认后仅锁定本次临时质量审计;不创建正式库存快照、不修改库存站点、不执行订单匹配。管理员可将确认会话沉淀为解析方案草稿,仍需走既有发布门禁 | +| 版本化发货 Excel 模板 | 已实现 | xlsx 存私有 MinIO,管理端通过后端白名单结构化配置稳定订单字段/库存字段/系统事实映射并发布;支持从已保存模板创建新草稿版本,无需重复上传,只有 Excel 结构变化时才替换文件;已回写 AWS PVMI V1 草稿,支持上海业务时区导出日期及订单信息字段重复写入每条货品明细;订单与库存按 Profile match_keys 关联,多库存源共享模板,生成时保存不可变 Artifact 与版本/checksum 审计 | +| 发货 Excel 批次 ZIP 下载 | 已实现 | 工作台支持按批次或显式勾选当前查询任务下载每票当前有效 Artifact;显式选择最多 100 票并在刷新后剔除不可见任务,服务端重新执行权限校验、同名消歧、checksum 校验并附 manifest,纠错失效或损坏票据不静默混入 | | 订单料号领域模型升级 | 已实现 | 主字段为内部料号 `part_number`;可选 `customer_part_number` / `aws_part_number`;三种料号必须原子化且禁止 `/`;当前字段模型不接受旧 `sku / vendor_part_number / customer_sku` | | 后端与 Dify 字段级交叉裁决 | 已实现 | 两侧输出不可变 Observation;后端统一验证 evidence、评分并生成规范投影;一致标记 consensus,高可信冲突或分差不足写 Candidate 阻断冲突;Observation 历史只追加不覆盖 | +| Bill-to/Ship-to 客户角色匹配 | 已实现 | 订单模板解析账款客户、送货对象、外部编码、来源系统和地址原文;后端优先按外部编码匹配标准客户/送货站点,名称与审核别名回退;客户简称仅由 Bill-to 主数据派生,Candidate 展示角色匹配状态并提供权限受控确认接口 | | 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 | | 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 | -| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | -| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | -| 库存 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 * * *` | +| Warehouse 统一解析与 Excel 真相源 | 已实现 | 固定 Source 取配置 Warehouse;Crane 从 `reservation_id + part_number` 命中库存行取 Warehouse;未解析时禁止生成 Excel | +| 库存快照 TTL 复用 | 已实现 | 按 `source_code` 复用最新有效文件,不再使用 `site_id`;动态多仓按 `run_no + source_code` 幂等 | +| 库存 RPA 批量导出(DBS/Crane) | 已实现 | 排程以 `source_codes` 为目标,按 RPA Profile 分组登录且每个结果独立归档 Source | +| 库存每日定时导出排程 | 已实现 | 排程生产库存文件;正常任务仅消费文件,手动刷新才执行按需导出 | +| 库存源至外部系统仓库映射 | 已实现 | 维护精确与 Source 默认映射;当前仅后台维护和后端内部 Service,不开发 Tool API 或调拨逻辑 | | 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | | 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` | | 客户主数据与识别证据 | 已实现 | 工作台「货代发货 → 客户主数据」二级目录(仅管理员可见);维护标准客户、唯一简码、名称别名、邮箱/域名、模板指纹、审核与停用管理 | +| 客户删除资格预检 | 已实现 | 管理员可查询业务单、业务流水、外部来源、导入与影子识别审计引用;仅识别证据允许作为未来永久删除的级联数据,前端不得以业务单数自行判断 | +| 客户受控永久删除 | 已实现 | 管理员在预检无阻断时输入当前简码和删除原因;后端锁定客户并重算引用,任一新增或既有引用均返回冲突,成功后保留快照审计并级联删除识别证据 | +| 客户受控合并 | 已实现 | 管理员预览历史保留与未来配置迁移后,输入源简码和原因归并至启用目标客户;历史业务/编号/审计不改写,识别证据和来源键迁移,源客户标记为 merged 并不可再用于新任务 | | 期初客户导入与对账 | 已实现 | 标准 Excel 模板、上传暂存、预检查重、冲突决策、单事务发布、来源键幂等重导和 CSV 对账 | | 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 | | 客户人工确认与 Gate | 已实现 | `customer_review`;业务用户从标准客户主数据中确认,客户未稳定时阻断库存源、RPA、匹配、Excel 和上传 | | 货代业务编号 | 已实现 | 客户确认后按 `Asia/Shanghai` 原子生成 `WYC26071501` 类业务号;每客户每日 `01-99`,修订继承、强制新建重新编号 | -| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认、历史回填和“原号作废 + 新号替代”纠错审计 | +| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认和“原号作废 + 新号替代”纠错审计 | +| 客户治理闭环 | 已实现 | 客户与识别证据关键变更记录快照时间线;简码、状态、自动匹配授权必须填写原因。自动确认在总开关外再受有效人工标注样本量(默认 20)与准确率(默认 98%)门禁约束,未达标保持 `customer_review`;客户主数据页展示时间线和降级原因 | | 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) | ### 排程平台任务契约中心(schedule) diff --git a/docs/openapi/agent_runtime_context_tools.dify.json b/docs/openapi/agent_runtime_context_tools.dify.json index 9ebedb8a..c6434e67 100644 --- a/docs/openapi/agent_runtime_context_tools.dify.json +++ b/docs/openapi/agent_runtime_context_tools.dify.json @@ -77,6 +77,8 @@ "refs.run_purpose", "refs.schedule_task_id", "refs.task_no", + "refs.temporary_inventory_asset_no", + "refs.temporary_inventory_session_no", "schema_version", "scope" ] diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json index 878c4356..82b1e6f7 100644 --- a/docs/openapi/shipping_notice_tools.dify.json +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -15,7 +15,7 @@ "post": { "operationId": "get_order_extraction_context", "summary": "读取点击发送后完整订单抽取所需的邮件正文与附件文本", - "description": "仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,并返回 input_snapshot_hash、documents 与固定输出契约;禁止让 LLM 传 user_id。", + "description": "仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,并返回 input_snapshot_hash、documents 与当前 published 动态 Schema 契约;禁止让 LLM 传 user_id。", "parameters": [], "requestBody": { "required": true, @@ -54,7 +54,7 @@ "post": { "operationId": "submit_order_extraction", "summary": "提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单", - "description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、内部料号/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,订单行 inventory_source_hint 是可选路由线索并独立持久化。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。", + "description": "只接受同一快照和同一 Schema checksum。Dify 必须逐字段返回稳定 field_id 与 observations[];每个 Observation 包含 value、document_id、逐字 quote 和可选 confidence。HXOPS 验证原文、执行类型/validator/证据策略与跨 Document 裁决后,才按 field_code 投影给下游。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。", "parameters": [], "requestBody": { "required": true, @@ -78,19 +78,28 @@ "items": { "type": "object", "required": [ + "schema_version_id", + "schema_checksum", "source_intake_no", "primary_document_id", "classification", "classification_confidence", - "field_confidence", - "lines", - "evidence" + "header_fields", + "lines" ], "properties": { "source_intake_no": { "type": "string", "description": "来源 Intake 编号,必须来自上下文" }, + "schema_version_id": { + "type": "integer", + "description": "context.contract.schema_version_id,必须原样回传" + }, + "schema_checksum": { + "type": "string", + "description": "context.contract.checksum,必须原样回传" + }, "primary_document_id": { "type": "integer", "description": "主来源 Document ID,必须来自上下文" @@ -113,91 +122,116 @@ "minimum": 0, "maximum": 1 }, - "field_confidence": { - "type": "object", - "required": [ - "part_number", - "qty" - ], - "properties": { - "part_number": { - "type": "number", - "minimum": 0, - "maximum": 1 + "header_fields": { + "type": "array", + "description": "Header scope 动态字段;仅可使用 context.contract.fields 中的稳定 field_id", + "items": { + "type": "object", + "required": [ + "field_id", + "observations" + ], + "properties": { + "field_id": { + "type": "string", + "description": "动态字段契约中的稳定 field_id,禁止传 field_code 或显示名称" + }, + "observations": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "value", + "document_id", + "quote" + ], + "properties": { + "value": { + "description": "从证据原文提取的字段值,类型必须符合动态字段契约" + }, + "document_id": { + "type": "integer", + "description": "证据来源 Document ID,必须来自抽取上下文" + }, + "quote": { + "type": "string", + "description": "证据原文中的逐字引用,HXOPS 将验证其确实存在" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "additionalProperties": false + } + } }, - "qty": { - "type": "number", - "minimum": 0, - "maximum": 1 - } + "additionalProperties": false } }, - "po_number": { - "type": "string", - "description": "可为空的 PO/订单号" - }, "lines": { "type": "array", "items": { "type": "object", "required": [ - "part_number", - "qty" + "fields" ], "properties": { - "part_number": { - "type": "string", - "description": "内部料号/主匹配料号" - }, - "qty": { - "type": "number", - "exclusiveMinimum": 0 - }, - "reservation_id": { - "type": "string", - "description": "可为空,缺失时 Task 停在补字段门禁" - }, - "inventory_source_hint": { - "type": "string", - "description": "可选库存来源提示;仅在原文有可靠证据时填写,不代表任务通知来源或已确认的库存连接器类型" - }, - "customer_part_number": { - "type": "string", - "description": "可选客户料号" - }, - "aws_part_number": { - "type": "string", - "description": "可选 AWS 料号" + "fields": { + "type": "array", + "description": "Line scope 动态字段;每项含 field_id 与 observations[]", + "items": { + "type": "object", + "required": [ + "field_id", + "observations" + ], + "properties": { + "field_id": { + "type": "string", + "description": "动态字段契约中的稳定 field_id,禁止传 field_code 或显示名称" + }, + "observations": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "value", + "document_id", + "quote" + ], + "properties": { + "value": { + "description": "从证据原文提取的字段值,类型必须符合动态字段契约" + }, + "document_id": { + "type": "integer", + "description": "证据来源 Document ID,必须来自抽取上下文" + }, + "quote": { + "type": "string", + "description": "证据原文中的逐字引用,HXOPS 将验证其确实存在" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "additionalProperties": false + } + } + }, + "additionalProperties": false + } } }, "additionalProperties": false } }, - "evidence": { - "type": "array", - "description": "至少分别提供内部料号与 Qty 原文证据,元素含 field 与非空 quote", - "items": { - "type": "object", - "required": [ - "field", - "quote" - ], - "properties": { - "field": { - "type": "string", - "description": "证据字段,如 lines[0].part_number 或 lines[0].qty" - }, - "quote": { - "type": "string", - "description": "原文片段,禁止改写" - }, - "document_id": { - "type": "integer", - "description": "证据来源 Document ID" - } - } - } - }, "conflicts": { "type": "array", "items": { @@ -233,6 +267,194 @@ } } }, + "/tools/create_temporary_inventory_session": { + "post": { + "operationId": "create_temporary_inventory_session", + "summary": "创建对话上传库存文件的临时分析会话", + "description": "仅在用户明确说明附件为库存文件的 temporary_inventory 分支调用。后端按会话用户校验资产归属并执行结构初检;不会创建生产库存快照、不会绑定库存站点、不会执行库存匹配。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent_runtime_context": { + "type": "string", + "description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改" + }, + "asset_no": { + "type": "string", + "description": "当前用户上传的 FileAsset 编号;必须是 xls、xlsx 或 csv" + } + }, + "required": [ + "agent_runtime_context", + "asset_no" + ] + } + } + } + }, + "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/get_temporary_inventory_session": { + "post": { + "operationId": "get_temporary_inventory_session", + "summary": "读取临时库存文件的脱敏结构分析和方案候选", + "description": "返回后端已分析的工作表、表头、字段目录和已发布方案候选,不返回样例库存值。Dify 不得读取文件路径、全量库存行,也不得据此直接宣称库存已可用于订单匹配。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent_runtime_context": { + "type": "string", + "description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改" + }, + "temporary_session_no": { + "type": "string", + "description": "create_temporary_inventory_session 返回的临时会话编号" + } + }, + "required": [ + "agent_runtime_context", + "temporary_session_no" + ] + } + } + } + }, + "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_temporary_inventory_mapping_suggestion": { + "post": { + "operationId": "submit_temporary_inventory_mapping_suggestion", + "summary": "保存对话临时库存的候选字段映射", + "description": "仅在没有 exact 已发布方案可复用时调用。HXOPS 校验字段目录、真实表头、重复列和核心字段完整性,只保存待用户确认的候选;不会发布方案、绑定库存站点、创建库存快照或执行订单匹配。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent_runtime_context": { + "type": "string", + "description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改" + }, + "temporary_session_no": { + "type": "string", + "description": "临时库存会话编号" + }, + "field_mapping": { + "type": "object", + "description": "库存字段目录 ID 到真实来源表头的映射;只能使用 get_temporary_inventory_session 返回的字段 ID 和表头", + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "agent_runtime_context", + "temporary_session_no", + "field_mapping" + ] + } + } + } + }, + "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/confirm_temporary_inventory_use": { + "post": { + "operationId": "confirm_temporary_inventory_use", + "summary": "确认当前对话临时库存文件使用", + "description": "仅在用户明确确认本次使用后调用。HXOPS 重新确定性解析文件并校验料号、预约号、库存数量;只锁定当前对话的临时会话审计,不接受任务编号,绝不创建生产库存快照、绑定库存站点、写入任务库存行或执行库存匹配。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent_runtime_context": { + "type": "string", + "description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改" + }, + "temporary_session_no": { + "type": "string", + "description": "临时库存会话编号" + }, + "selected_profile_id": { + "type": "integer", + "description": "仅 exact 已发布方案候选时由用户选择的方案 ID" + } + }, + "required": [ + "agent_runtime_context", + "temporary_session_no" + ] + } + } + } + }, + "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/parse_notice": { "post": { "operationId": "parse_notice", @@ -485,94 +707,11 @@ } } }, - "/tools/get_inventory_schema_preview": { - "post": { - "operationId": "get_inventory_schema_preview", - "summary": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)", - "description": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)", - "parameters": [], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" - } - }, - "required": [ - "task_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/apply_inventory_mapping": { - "post": { - "operationId": "apply_inventory_mapping", - "summary": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑", - "description": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑", - "parameters": [], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "task_id": { - "type": "string", - "description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501" - }, - "map_json": { - "type": "string", - "description": "Dify Tool 参数使用 JSON 字符串,内容含 part_number/reservation_id/available_qty,可选 aws_part_number;可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。" - } - }, - "required": [ - "task_id", - "map_json" - ] - } - } - } - }, - "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/confirm_inventory_source": { "post": { "operationId": "confirm_inventory_source", "summary": "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)", - "description": "库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。", + "description": "库存连接器门禁:稳定身份须具备 source_code、connector_type;fixed Source 同时具备 warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。", "parameters": [], "requestBody": { "required": true, @@ -587,7 +726,7 @@ }, "source_code": { "type": "string", - "description": "启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传" + "description": "启用配置中的库存源编码;Warehouse 由 fixed Source 配置或库存行匹配解析,禁止前端直传" } }, "required": [ @@ -679,17 +818,14 @@ }, "decision": { "type": "string", - "description": "confirm=确认继续;reject=驳回;retry_rpa=重新获取库存(清理旧库存解析状态并重新触发 RPA);rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存", + "description": "confirm=确认继续;reject=驳回;retry_rpa=按已发布解析方案重新获取库存;rematch=重新匹配;reparse=重新解析", "enum": [ "confirm", "confirm_parse", "reject", "retry_rpa", "rematch", - "reparse", - "confirm_inventory_mapping", - "correct_inventory_mapping", - "reparse_inventory" + "reparse" ] }, "comment": { @@ -722,7 +858,7 @@ "post": { "operationId": "get_task_status", "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。", + "description": "返回 inventory_source_code、inventory_connector_type、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, diff --git a/docs/prototype/shipping-inventory-config-prototype.html b/docs/prototype/shipping-inventory-config-prototype.html new file mode 100644 index 00000000..3f0a1b5b --- /dev/null +++ b/docs/prototype/shipping-inventory-config-prototype.html @@ -0,0 +1,317 @@ + + + + + + + HXOPS - 货代库存配置原型 + + + +
+
H
管理控制台
系统配置与管理 / 货代发货
+
帮助中心◐CH
+
+
+ +
+

货代库存配置

把登录配置、业务库存源、路由规则和外部系统仓库映射分开维护。

最后同步:今天 10:42
+
+
配置关系
连接配置 → 库存源 → 文件
货代连接配置只生产库存文件;正常发货只消费已导出的有效文件。
+
启用货代连接
4 个
按账号隔离登录会话
+
启用库存源
9 个
固定仓 8 个,动态仓 1 个
+
待发布路由规则
2 条
发布后才进入订单路由
+
+
+ +
+

货代连接配置

维护多个登录账号、入口地址及页面操作。用户名和密码只显示配置状态。

+
+
+ +
+
+
+
+
+
原型操作已保存(仅模拟)
+ + + diff --git a/docs/tec.md b/docs/tec.md index 9f475d9b..28c50ce7 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -33,6 +33,11 @@ - **期初数据导入**:使用客户导入批次和导入行暂存表保存原文件哈希、原始值、标准化值、校验结果、处理决定和发布结果;正式发布前完成简码冲突、疑似重复、公共域名和标识歧义检查。 - **渐进发布**:按 `off → shadow → manual_gate → auto_gate` 开启客户识别;影子阶段只记录候选不阻断生产,强规则质量达标后先启用人工 Gate,再开放有限自动确认。 - **技术栈说明**:该能力继续在现有 Flask + SQLAlchemy 事务内实现,以保证客户绑定、业务号生成、任务状态迁移和审计事件原子提交;本期不拆分独立 FastAPI 服务。 +- **新契约收口**:货代任务必须关联业务单;修订任务缺少父业务单时返回冲突,禁止隐式补建或历史客户回填。客户主数据页面归属 `features/shipping-notice`,后端管理员 API 继续承担权限边界。 +- **删除资格单一真相源**:`shipping_customer_lifecycle_service` 聚合业务单、编号流水、外部来源键、导入目标/结果、影子候选与人工真值引用,供删除和合并共用;禁止前端以 `case_count=0` 推断可删除。生命周期审计保存客户快照而非客户外键,避免审计记录本身永久阻断受控删除。 +- **受控永久删除**:`DELETE /api/admin/shipping-customers/{customer_id}` 仅管理员可调用,必须提交 `confirmation_short_code` 和 `reason`。服务层以 `SELECT ... FOR UPDATE` 锁定客户后重新计算生命周期影响;任一阻断引用返回 `409 SHIPPING.CUSTOMER_DELETE_BLOCKED`,成功删除写入仅保存客户快照的 `deleted` 生命周期事件。 +- **受控客户合并**:`POST /api/admin/shipping-customers/{source_id}/merge` 仅管理员可调用,固定顺序锁定源/目标客户,目标必须为启用客户。源客户状态改为 `merged` 并保留指向目标的关系;业务单、编号、流水、导入和影子审计不迁移,识别证据和外部来源键迁移至目标(重复证据受唯一约束去重)。合并审计只保存双方快照;merged 客户不能进入选客、自动裁决、人工标注或识别证据维护入口。 +- **质量门禁与可观测性**:`SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED` 仅是第一层开关;`customer_auto_resolution` 必须再以当前强规则唯一命中的人工真值样本计算有效样本量和准确率。低于 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES=20` 或 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY=0.98` 时返回降级状态并不调用客户确认/编号事务。`ShippingCustomerLifecycleEvent` 记录客户和证据关键变更快照;`/lifecycle-timeline` 与 `/governance-quality` 均由管理员 API 提供。 ### 2.x 多订单邮件 Candidate 架构 @@ -47,6 +52,18 @@ - `shipping_order_extraction_state` 是 HXOPS 领域 SSE,不由 Dify 正文推导;终态以 `request_id + session_id + intake_nos + user_id` 围栏读取 Intake submission 事实,并合并到对应 `ChatLog.payload` 供历史回放。 - 订单完整抽取无法提供可信阶段百分比,前端只展示不确定进度;新建、打开已有、待补充、非发货和缺流程字段均使用 HXOPS Tool 的真实计数。 +### 2.x 唯一订单 Schema 基础 + +- `ShippingOrderSchema` 固定使用逻辑编码 `SHIPPING_ORDER`,当前业务全局只允许一个逻辑 Schema。 +- `ShippingOrderField.id` 为永久稳定 UUID;`field_code/scope/value_type` 首次发布后冻结。 +- `ShippingOrderSchemaVersion` 使用 `draft -> published -> retired` 生命周期;草稿和发布版本均以完整 `definition_json` 为唯一配置真相,发布时冻结 SHA-256 checksum,同一 Schema 同时最多一个 published 版本。草稿保存/发布使用 `lock_version` 乐观锁,防止管理员静默覆盖。 +- `shipping_order_schema_audit_events` 是追加式配置审计表,记录版本/字段目录写操作的操作者、请求 ID、前后快照和变更摘要;删除草稿后保留审计快照并断开可空版本外键。 + - 版本差异使用纯函数按稳定 `field_id` 计算,`GET /versions/{id}/diff?against_version_id={id}` 返回字段和属性级结构化结果;审计时间线 `GET /audit-events` 只返回安全摘要、支持分页和版本过滤,避免传输完整审计快照。 + - `ShippingOrderExtraction` 以 `schema_version_id` 锁定运行契约,新增 `input_snapshot_json` 冻结参与裁决的输入文档;版本使用查询由 `(schema_version_id, created_at)` 索引支持。管理员审计 API 返回保存的 LLM、规范化、校验、Observation、Decision 和 FieldValue,不回读当前字段目录。 +- Schema 发布前反向检查 draft/published 路由规则、库存解析 Profile 与 Excel 模板;新版本不得移除仍被运行配置引用的稳定字段。 +- `ShippingOrderExtraction` 锁定 Schema 版本和输入快照;`Observation/Decision/FieldValue` 分别承载来源观察、后端裁决和类型化下游投影。 +- 阶段一仅建立配置与数据基础;现有固定订单解析链在阶段二切换为动态 Schema 后移除,不建设长期双读兼容。 + ### 2.x 发货通知字段契约与后端裁决 - 解析链采用 `结构保真正文 -> LLM 候选 JSON -> 后端 adjudicate -> validated lines -> 匹配硬闸门`;LLM 不是业务真相源。 @@ -58,13 +75,15 @@ - 裁决结果写入规范订单行的 `field_sources_json / evidence_json`,流程摘要写入 `ShippingTask.step_payload_json.parse_validation`;字段模型调整必须配套 Alembic 迁移。 - 规范订单行与内容指纹分别使用 `shipping-task-line-v2`、`shipping-content-v4`。生产尚无业务数据,因此不实现旧字段 alias、双版本读取或历史值猜测回填;dev/test 数据通过迁移或重建切换。 - `parse_notice`、人工确认和 `match_inventory` 三层重复执行关键门禁,防止脏值通过任一旁路进入后续履约。 +- 客户角色采用“解析原文”和“主数据解析”分层:动态 Schema 保存 Bill-to/Ship-to 名称、外部编码、来源系统及地址证据;`ShippingOrderCustomerMatch` 保存角色候选和确认快照;`ShippingCustomerExternalRef`、`ShippingCustomerSite`、`ShippingCustomerSiteIdentifier` 提供外部客户编码与送货站点匹配。LLM 不生成主数据 ID 或客户简称。 +- 客户匹配遵循外部编码优先、标准名称/已审核别名回退;Ship-to 必须落到启用站点并校验所属客户。Candidate 只展示候选,正式客户绑定和业务编号仍通过既有质量门禁。 - 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。 - 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。 - 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。 - `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。 - **订单行双写与切读**:业务读写经 `task_line_store`;`WRITE_MODE=dual` 同事务维护 `shipping_task_lines` 与 `lines_json`;`READ_MODE=shadow|table`(默认 shared 为 shadow);切 `table` 前须 `verify_shipping_task_lines` 全量零差异并完成观察窗口;回滚只改 `READ_MODE=json`,本期不删 `lines_json`。字段冲突表 `shipping_task_field_conflicts` 与 `order_data_version` 支撑并发安全编辑。 -- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;订单行仅保留 `inventory_source_hint` 作为可选路由线索,库存连接器配置/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)。 +- **库存源与库存文件分层**:`source_code` 是业务库存主键;通用、版本化的路由规则先产生 Source 候选,正常任务再按 Source 匹配最新 `ready`、未过期库存文件,禁止因文件缺失自动触发 RPA。RPA Profile 仅保存登录 URL、加密凭据和连接级登录配置;每个 Source 保存 DBS 的报表路径、查询参数和识别别名,不允许在业务配置中保存 selector 或下载策略。排程按 Profile 分组优化登录但每个结果独立归档到 Source。`connector_type` 只允许 `dbs` / `crane`,不再使用 `site_id`。固定 Source 使用配置 Warehouse;Crane 等动态 Source 按 `reservation_id + part_number` 从库存行解析 Warehouse。详见 [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 已有聊天路由能力 @@ -1145,3 +1164,13 @@ Dify - 聚合问答由目录 Agent 自己的 Dify Chatflow 实现。 - HXOPS 当前只负责配置、权限、会话与上下文注入,不直接编排多个子 Agent 的回答。 +- **版本化 Excel 模板与 Artifact**:`shipping_excel_templates` 保存私有 MinIO `bucket/key`、模板文件校验和及字段映射发布版本,`shipping_inventory_sources.excel_template_id` 决定新任务使用的模板;`shipping_export_artifacts` 保存每次生成文件及所锁定的 Schema、Extraction、库存解析 Profile、库存快照、输入/文件 checksum。导出运行时从 MinIO读取模板,不读取全局模板环境变量,也不回退空白工作簿。 +- **库存字段目录与确定性订单/库存关联**:库存字段目录独立于 DBS、Crane 和具体库存站点,初始化为空,所有字段由管理员创建。`field_code` 仅作为不展示的审计标识,不参与匹配、解析、仓库识别或导出。解析方案以 `inventory_field_id -> 原始表头` 保存实际列映射,以 `match_keys[].inventory_field_id` 将动态订单 `field_id` 与库存字段关联;库存快照行 JSON、结构兼容指纹和发货模板均直接使用库存字段 ID。字段用途只承担能力角色:至少一个 `match_identity`、恰好一个 `inventory_quantity`,动态仓方案恰好一个 `warehouse_identity`;`general` 字段数量不限。数组顺序和字段名称均不参与匹配,多命中仅在模板所需库存字段值一致时允许合并。 +- **库存站点启用**:库存站点首次保存一律保持停用,普通保存不承担状态切换;启用使用独立 API,后端返回连接、库存文件解析方案、发货模板、测试导出与解析验证及仓库映射等未完成项。数据库 CheckConstraint 继续保证启用站点绑定解析方案和 Excel 模板;测试导出确认记录必须与当前站点配置版本和已绑定方案一致,编辑站点后自动失效。启用时按已绑定方案实际映射的字段用途验证匹配栏位样例非空、唯一数量栏位为数值、发货模板库存字段引用完整和仓库映射覆盖;固定仓允许精确或默认映射,动态仓要求唯一仓库识别字段并覆盖样例仓库。解析方案新发布版本与旧 published 版本并存,站点显式迁移后旧版本方可退役。 +- **库存样本结构分析**:`shipping_inventory_structure_analyses` 保存受控库存样本的文件 checksum、工作表/候选表头、来源栏位、少量样例、类型/空值统计和规则建议,不保存正式库存明细。`POST /api/admin/shipping-notice/inventory-structure-analyses` 由后端校验实际 `.xls` / `.xlsx` / `.csv` 后生成分析;创建解析方案草稿时,工作表、表头和来源栏位必须来自该分析记录。 +- **对话临时库存文件**:用户在货代对话上传 `.xls` / `.xlsx` / `.csv` 表格后,系统先保留附件,只有用户明确声明其为库存文件才创建 `FileAsset -> shipping_temporary_inventory_sessions` 短生命周期会话;绝不依据后缀猜测库存或订单。会话同时绑定 `user_id + conversation_id + asset_id`,以 `source_kind=temporary_conversation` 保存结构审计。后端只向 Dify 返回不含样例库存值的结构预览与规则建议;不创建 `shipping_inventory_files`、不写任务库存关联、不绑定库存站点。跨聊天回合时,HXOPS 从数据库恢复当前会话最新、未过期且仍待确认的临时会话号,但不会自动路由或确认;Dify 只有识别到用户明确确认本次临时使用时,才可调用确认 Tool。所有 Tool 输出先按 `text` JSON 标准化,不能依赖 Dify 隐式会话记忆或假定的 Tool 顶层字段。Dify 仅可调用创建、读取、提交候选映射和经用户明确确认后的临时使用 Tool,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。 +- **方案复用**:结构分析与解析方案分别保存精确结构指纹和兼容指纹,均不包含库存业务数据或文件名。精确指纹覆盖格式、工作表、表头行、标准化列名及顺序;兼容判断验证既有方案实际使用的库存匹配与数量来源表头仍存在,并输出新增/缺少/顺序变化。后端不使用固定字段词典把“内部料号”猜成 `Supplier Sku`;仅当用户字段显示名称与真实表头标准化后完全相同时给出确定性预填,其他情况由管理员选择或 Dify 提供候选。管理员确认复用只写分析审计,不更新库存站点绑定。 +- **库存站点测试导出**:`shipping_inventory_configuration_test_runs` 保存专用 `configuration_test` RPA run、来源配置版本、分析记录和确认结果。测试回调走 `/api/shipping-notice/rpa/inventory-configuration-test-ready`,只创建 `source_kind=configuration_test` 的结构分析,不创建 `shipping_inventory_files`。确认方案时要求站点仍停用且配置版本未变化,成功后绑定解析方案并使测试记录追随新的配置版本;后续编辑站点自动使旧测试失效。 +- **正式库存结构漂移**:`inventory_structure_drift` 在 RPA 单票与批量回调正式解析前分析实际文件;只允许已绑定 published Profile 成为 `exact` 或 `compatible` 候选。兼容变化只限非关键栏位,差异写入快照 `schema_preview_json.structure_validation`;关键结构变化返回 `SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED` 并回滚本次快照与任务链接。解析参数固定来自 Profile,运行期不再根据文件表头调用规则猜测。 +- **管理端契约**:Profile 和 Excel 模板使用后端 `configuration-catalog` 返回的订单字段、库存标准字段、系统事实、row mode 和 formatter 结构化编辑,不以自由 JSON 作为日常维护入口;禁用 Source 可分步保存,启用时服务层与数据库双重校验绑定完整性。 +- **批次下载**:`POST /api/workspace/shipping-exports/archive` 只接收 `batch_no` 或 `task_nos[]`,后端重新做用户归属校验并选择仍与 Task 当前导出路径一致的最新 ready Artifact;ZIP 使用可溢写临时文件,含 `manifest.json`,同名追加任务号,单次最多 100 票。 diff --git a/docs/test_plan_matrix.md b/docs/test_plan_matrix.md index 0018f87e..cd7ad11b 100644 --- a/docs/test_plan_matrix.md +++ b/docs/test_plan_matrix.md @@ -40,7 +40,11 @@ | **发货通知** | **一附件多订单与部分成功** | 一个 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。 | | **发货通知** | **自动建单与流程字段门禁** | 分类、`part_number`/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;`inventory_source_hint` 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 `part_number`+Qty,Reservation 为空、库存源线索可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;库存源线索缺失不单独阻断。 | -| **发货通知** | **库存连接器 API 命名** | 连接器候选使用 `connector_type`,任务 API 使用 `inventory_connector_type`;不得返回旧 `inventory_source_type`。 | `test_shipping_notice_openapi_contract.py` | 获取动态 OpenAPI 与静态 Dify 快照 | 订单行仅保留可选 `inventory_source_hint` 且不暴露废弃路由字段;状态查询说明仅含 `inventory_connector_type`。 | +| **发货通知** | **库存连接器 API 命名** | 连接器候选使用 `connector_type`,任务 API 使用 `inventory_connector_type`;不得返回旧 `inventory_source_type`。 | `test_shipping_notice_openapi_contract.py` | 获取动态 OpenAPI 与静态 Dify 快照 | 订单行使用动态 `fields[]`,字段项明确 `field_id + observations[]` 且不暴露废弃固定路由字段;状态查询说明仅含 `inventory_connector_type`。 | +| **发货通知** | **任务级人工库存发布方案门禁** | 已有任务可人工上传 `.xls/.xlsx/.csv`,但必须按已确认库存站点的 published Profile 确定性解析。 | `test_shipping_notice_inventory_rpa_workflow.py` | 完全一致文件、关键表头漂移文件 | 一致文件直接进入 `ready_to_match` 且快照记录发布方案映射;漂移文件回滚文件、快照、任务链接和库存投影,不进入字段对齐或 LLM 映射。 | +| **发货通知** | **重新上传库存状态收敛** | 用户可重新选择正式库存文件,但不能重开任务级猜列或映射确认。 | `test_shipping_notice_tools.py`、前端 shipping decision/menu 单测 | 已有关联库存、已有匹配/导出结果、废弃映射动作 | `reparse_inventory` 停用当前 active link 并清理库存、匹配和导出派生结果,返回“选择库存文件/重新获取库存”;前端不生成 `confirm_inventory_mapping`、`correct_inventory_mapping`、`paste_inventory_json` 或 `edit_inventory_mapping`。 | +| **发货通知** | **动态订单匹配与重新匹配闭环** | accepted 动态订单字段、published 库存 Profile 和库存字段目录共同驱动匹配;不得停在门禁后形成不可达匹配代码。 | `test_shipping_notice_tools.py::test_contract_dynamic_order_shortage_and_rematch_recompute_inventory` | 订单数量 10、库存 5 后更新为 20 | 首次进入 `shortage_review` 并禁止导出/上传;库存更新后 `rematch` 同步变为 `fulfillable`、清空缺口并进入 `matched`。 | +| **发货通知** | **工作台状态筛选与四语言一致性** | 工作台全部可展示流程状态均可筛选,货代业务三棵文案树四语言键集合一致。 | `test_shipping_notice_query_service.py`、`shippingTaskStatuses.spec.ts`、`shippingI18nParity.spec.ts` | `shortage_review` 复合状态、12 个流程状态、四语言货代子树 | shortage 筛选按复核状态命中;筛选状态无遗漏/重复;货代配置、聊天和工作台四语言无缺键。 | | **发货通知** | **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;合法幂等重放不受影响。 | @@ -48,4 +52,23 @@ | **发货通知** | **Candidate 迁移往返** | 内容指纹、订单抽取状态与多 Candidate 唯一键迁移须可独立 upgrade/downgrade。 | `test_shipping_notice_candidate_migration.py` | 前一版本最小 schema;同 Document 多 Candidate | 新列/约束存在;安全场景完整降级;多 Candidate 场景明确拒绝降级。 | | **发货通知** | **订单行双写与切读** | dual 写同事务更新 JSON+规范表;shadow 对外仍读 JSON;table 读以规范表为准;回填/校验可运维。 | `test_shipping_task_line_store.py`;脚本 `backfill_shipping_task_lines.py` / `verify_shipping_task_lines.py` | dual/shadow/table 配置;非法 qty;人为 JSON 漂移 | dual 成功落两侧;shadow 打 mismatch 日志;table 忽略漂移;verify mismatch 退出码 1。 | | **发货通知** | **字段对账与冲突门禁** | Candidate 空字段可补齐;双方非空不同落冲突;未解决冲突阻断库存/RPA/匹配/导出;改单带版本。 | `test_shipping_task_field_reconciliation.py` | open_existing 补 Reservation;多行同字段冲突;行重建后冲突存活 | applied/conflicted 可区分;下游入口无副作用;resolve 后重算 Gate。 | +| **发货通知** | **唯一订单 Schema 发布门禁与版本治理** | 全局单 Schema;完整 JSON 定义是草稿/发布唯一真相;保存/发布使用乐观锁;发布事件追加审计。 | `test_shipping_order_schema.py`、`test_shipping_order_schema_version_governance_migration.py` | 动态字段、草稿、过期锁、连续发布、审计快照、迁移清理草稿、Profile/模板跨域字段引用、下游引用字段被新版本移除 | 契约 checksum 稳定;仅一个 published Schema 版本;过期锁返回 409;审计事件保留前后快照;字段退役和 Schema 发布均不可留下下游悬空引用。 | +| **发货通知** | **订单 Schema 历史版本浏览** | 版本列表分页加载,历史详情按需读取不可变快照,业务版本号可恢复 URL 查看位置。 | `test_admin_shipping_order_schema_history.py` | 管理员/普通用户权限、分页概要、指定版本定位、发布人展示、字段重命名后的历史快照 | 列表不返回完整定义;详情只读且保留当时 field_code/display_name;普通用户 403;`?version=V` 精确打开 V。 | +| **发货通知** | **订单 Schema 版本差异与配置审计** | 后端按稳定 `field_id` 计算任意两个版本的属性级差异;审计时间线安全分页展示追加事件。 | `test_shipping_order_schema_diff.py` | 系统标识重命名、集合顺序、纳入状态、版本过滤、管理员/普通用户权限 | 重命名为 modified 而非删除/新增;数组返回增删和顺序变化;差异/时间线拒绝普通用户;审计接口不回传完整前后快照。 | +| **发货通知** | **订单 Schema 运行追溯与历史复制** | 版本使用统计关联真实 `ShippingOrderExtraction`;单次解析展示锁定契约、冻结输入、LLM、裁决和值;不可变版本可复制为新草稿。 | `test_shipping_order_schema_runtime_audit.py`、`test_shipping_order_schema_runtime_audit_migration.py` | 多版本解析、状态分布、管理员/普通用户权限、Observation/Decision/Value 证据、字段改名、草稿源复制、迁移往返 | 使用统计不混入其他版本且可分页;审计详情不回读当前字段目录;输入/LLM/校验/证据完整;草稿不能作复制源;快照列和索引可 upgrade/downgrade。 | +| **发货通知** | **动态字段数据库约束** | Header/Line 的 Observation、Decision 和 Value 可审计且目标唯一。 | `test_shipping_order_schema.py` | 同一 Extraction 重复 Header FieldValue | 数据库唯一索引拒绝重复值。 | +| **发货通知** | **订单 Schema 迁移往返** | 阶段一新增表和 Task 当前解析引用可独立 upgrade/downgrade。 | `test_shipping_order_schema_migration.py` | SQLite 最小上一版本基线 | 核心表和列完整新增并完整移除。 | +| **发货通知** | **动态 Schema 订单解析** | published 契约驱动 EML/PDF 同字段 Observation 与后端裁决。 | `test_shipping_order_schema_runtime.py`、`test_shipping_notice_order_extraction.py` | 跨 Document 一致、冲突、缺证据、Schema checksum 漂移 | 一致值 corroborated;冲突/缺证据阻断;accepted 值生成类型化投影。 | +| **发货通知** | **动态字段库存路由** | 路由规则引用稳定订单 field_id,并从当前 Extraction 读取类型化值。 | `test_shipping_inventory_routing_engine.py`、`test_shipping_inventory_service.py` | Header/Line scope、系统事实、动态行值、非法字段 | 动态字段可命中 Source;作用域错误/退役字段被拒;无任意 fact path。 | +| **发货通知** | **库存站点停用保存与启用门禁** | 首次保存保持停用,普通保存不可直接启用;独立启用接口返回系统连接、库存文件解析方案、发货模板和测试导出等未完成项。 | `test_shipping_inventory_service.py::test_activation_is_a_separate_gate_and_reports_unfinished_steps` | 新建站点请求携带 `enabled=true`;缺解析方案、发货模板和测试证据 | 站点仍为停用;启用被阻断且返回准确缺失项;后续测试导出阶段补齐证据后才可放行。 | +| **发货通知** | **库存样本结构识别** | 后端读取 Excel/CSV 样本的工作表、候选表头、真实列名、少量样例和字段建议;解析方案草稿只能引用识别到的来源栏位。 | `test_inventory_structure_analysis.py` | 标题行、多工作表、真实库存表头、伪装 xlsx、浏览器伪造来源栏位 | 正确选中库存表头;返回类型与样例;无效文件被拒;虚构来源栏位不能创建草稿。 | +| **发货通知** | **库存文件解析方案复用** | 文件结构与核心库存栏位决定 exact/compatible/no-match;采用建议只写分析审计。 | `test_inventory_profile_matching.py` | 数据不同但表头相同、增加无关栏位、管理员采用推荐方案 | 相同结构为 exact;无关栏位为 compatible 且列出差异;不按文件名/数据内容判断;不自动绑定库存站点。 | +| **发货通知** | **库存站点测试导出隔离** | 停用站点的 RPA 测试回调只产生测试运行和结构分析,确认本次推荐的已发布方案后才绑定。 | `test_inventory_configuration_test.py` | 重复发起、成功/失败回调、确认绑定、无关方案、站点配置变化、站点启用 | 重复点击复用 run;不创建生产库存快照或任务链接;失败不绑定;仅兼容方案可确认;配置变化或启用后拒绝测试/确认。 | +| **发货通知** | **库存站点启用验证与仓库映射** | 启用前二次复核测试解析、模板字段和仓库映射,不能凭名称自动创建外部仓库。 | `test_inventory_configuration_test.py` | 固定仓无映射、补充精确映射、完整启用链路 | 无映射时返回 `warehouse_mapping`;补充已维护映射后缺失项消失;全部前置满足时仅独立启用接口可成功。 | +| **发货通知** | **正式库存文件结构漂移** | RPA 正式文件必须符合站点已绑定的解析方案,且不可回退到自动猜列或自动换工作表。 | `test_inventory_structure_drift.py` | 表头完全一致、增加无关栏位、关键栏位改名、多工作表 | 一致为 `exact`;无关栏位为 `compatible` 且记录差异;关键变化或指定工作表不存在返回 `SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED`。 | +| **发货通知** | **陌生表头 LLM 候选解释** | Dify 只在用户明确声明的临时库存分支无精确方案时,或管理员在解析方案草稿中显式请求时输出候选;不参与正式库存解析或状态推进。 | Dify 手工配置验收 | 陌生外文表头、低置信度候选、未声明用途、尝试触发发布/绑定/映射 | 未声明用途不进入候选节点;仅展示后端返回的真实表头候选及理由;候选不能调用旧库存映射 Tool、发布方案、绑定站点、创建仓库映射或解除漂移门禁。 | +| **发货通知** | **对话临时库存隔离与确认** | 用户明确声明 `.xls/.xlsx/.csv` 为库存文件后才进入临时会话;库存候选分类与可配置字段目录映射解耦,映射建议和确认均不触碰正式库存链路。跨回合确认由 HXOPS 数据库恢复待确认会话号,不依赖 Dify 隐式记忆。 | `test_temporary_inventory_session.py`、`test_shipping_notice_batches.py -k build_dify_chat_inputs`、前端上传/发送单测、Dify 手工配置验收 | 未声明表格、旧 `.xls`、跨会话读取、同资产重试、无库存特征、伪造字段映射、伪造 task_no、字段目录 ID 质量校验、待确认会话跨回合、过期/终态会话、未确认调用、确认后沉淀草稿 | 未声明不按后缀自动归类;`.xls/.xlsx/.csv` 均可进入受控结构分析;分类规则不生成正式映射;会话按用户+聊天+资产隔离且待确认幂等;临时确认按字段目录用途校验且始终为 conversation scope;仅未过期待确认会话号可恢复;零生产快照/任务库存链接/库存匹配写入;管理员只能创建草稿。 | +| **发货通知** | **共享库存文件解析方案** | 多库存站点共享版本化文件结构和订单匹配定义。 | `test_inventory_parsing_profile.py`、`test_shipping_inventory_service.py` | 结构化目录、published 绑定、禁用站点分步配置、多版本并存、退役引用、当前订单模板字段门禁 | 同方案可绑定多站点;新版本不破坏旧绑定;引用中版本不可退役;定义 checksum 不可变。 | +| **发货通知** | **版本化 Excel 模板与 Artifact** | 库存源选择 published 模板,按稳定动态字段与 Profile match_keys 生成并锁定完整输入版本。 | `test_shipping_excel_template.py`、`test_shipping_template_migrations.py` | MinIO 替身、真实 xlsx、反序库存、歧义多命中、Header/Line、多 Source、迁移往返、提交失败 | 模板不依赖本机磁盘;行序不影响匹配;冲突阻断且无孤立文件;Artifact 含模板、Schema、Profile、checksum。 | +| **发货通知** | **批次 ZIP 下载** | 工作台按批次或显式勾选任务集合下载每票当前可信 Artifact。 | `test_shipping_export_archive.py`、`exportSelection.spec.ts` | 同名、失效引用、缺失文件、损坏 checksum、越权、API attachment、选择去重/取消/可见范围/100 票上限 | 当前有效文件均包含且不覆盖;旧失效 Artifact 排除;manifest 完整;越权整体拒绝;返回 application/zip;显式选择不会携带筛选后不可见任务。 | diff --git a/docs/新人环境搭建与配置文档.md b/docs/新人环境搭建与配置文档.md index 5e384528..1c28db53 100644 --- a/docs/新人环境搭建与配置文档.md +++ b/docs/新人环境搭建与配置文档.md @@ -220,6 +220,18 @@ docker compose up -d --build 说明:生产环境禁止使用默认密码,首次上线后必须立即重置。 +本地初始化默认使用 `backend/local_test.db`。需要做 UI 验收、并行工作区或不希望接触现有本地数据时,应显式指定新的隔离文件: + +```powershell +$env:HXOPS_LOCAL_DATABASE_PATH = "$env:TEMP\hxops-ui-validation.db" +cd backend +python init_local_db.py +``` + +- 全新空库会按当前 SQLAlchemy 模型建表,并标记到当前 Alembic head。 +- 已带 Alembic 版本的本地库会执行正常迁移。 +- 已有业务表但没有 `alembic_version` 的未知旧库会被拒绝,脚本不会自动删除、覆盖或伪造迁移版本;请先备份并人工制定迁移方案。 + ### 6.4 企业微信登录(WECOM)配置 后端 `.env` 至少配置: diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index cd23cb28..a80faf0b 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -47,6 +47,8 @@ const WecomAuditsPage = () => import("@/features/admin/modules/wecom/pages/Wecom const ReportsPage = () => import("@/features/admin/modules/reports/ReportsPage.vue"); +const ShippingInventoryPage = () => + import("@/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue"); export const adminRoutes: RouteRecordRaw[] = [ { @@ -146,10 +148,10 @@ export const adminRoutes: RouteRecordRaw[] = [ }, { - path: "shipping-customers", - name: "AdminShippingCustomers", - redirect: "/workspace/shipping-notice/customers", - meta: { requiresAdmin: true, title: "货代客户主数据" }, + path: "shipping-notice", + name: "AdminShippingInventory", + component: ShippingInventoryPage, + meta: { requiresAdmin: true, adminModule: "shipping_inventory", title: "货代配置" }, }, { diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index 3a6c7d91..27cbb690 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -54,7 +54,7 @@ export const workspaceRoutes: RouteRecordRaw[] = [ { path: 'shipping-notice/customers', name: 'workspace-shipping-customers', - component: () => import('@/features/admin/modules/shipping-customers/ShippingCustomersPage.vue'), + component: () => import('@/features/shipping-notice/customers/ShippingCustomersPage.vue'), meta: { title: '货代客户主数据', requiresAdmin: true }, }, { diff --git a/frontend/src/config.ts b/frontend/src/config.ts index 85ed3d13..4df92245 100644 --- a/frontend/src/config.ts +++ b/frontend/src/config.ts @@ -63,6 +63,7 @@ export const config = { requests: true, // 审批权限 reports: true, // 数据报表 schedules: true, // 定时任务 + shipping_inventory: true, // 货代配置 } } }; diff --git a/frontend/src/constants/shippingNoticeActions.ts b/frontend/src/constants/shippingNoticeActions.ts index 519957a4..d4896e26 100644 --- a/frontend/src/constants/shippingNoticeActions.ts +++ b/frontend/src/constants/shippingNoticeActions.ts @@ -8,8 +8,6 @@ export const SHIPPING_ACTION_IDS = [ 'reject', 'reparse', 'replace_notice_file', - 'confirm_inventory_mapping', - 'correct_inventory_mapping', 'reparse_inventory', 'rematch', 'retry_rpa', @@ -21,8 +19,6 @@ export const SHIPPING_ACTION_IDS = [ 'download_excel', 'generate_excel', 'mark_manual_uploaded', - 'paste_inventory_json', - 'edit_inventory_mapping', 'match_inventory', 'refresh', ] as const; @@ -39,8 +35,6 @@ export const SHIPPING_INTERNAL_STATUS_TOKENS = [ 'upload_rpa_pending', 'rpa_exhausted', 'inv_unavail', - 'align_review', - 'map_infer', 'parse_review', 'shortage_review', 'low_confidence', diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index b0bd8a88..7e7dcf7d 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -1,11 +1,11 @@ /** * features/admin/api/admin.api.ts - * 用途:管理后台用户、部门、Agent、货代客户、权限、报表等 HTTP API。 + * 用途:管理后台用户、部门、Agent、权限、报表等 HTTP API。 * 依赖:requestJson、getAuthHeaders、各管理域类型。 - * 逻辑:JSON 接口统一走 requestJson;模板与对账二进制下载沿用认证 fetch 并抛 BusinessError。 + * 逻辑:JSON 接口统一走 requestJson;业务域专属 API 位于各自 feature 目录。 */ import { getAuthHeaders } from '@/shared/utils/auth'; -import { BusinessError, requestJson, resolveLocalizedErrorMessage } from '@/shared/api/client'; +import { requestJson } 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'; @@ -17,38 +17,17 @@ 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, - }); - } +/** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */ +export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise => { + const response = await fetch(`/api/admin/shipping-notice/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() }); + if (!response.ok) throw new Error(`HTTP ${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 filename = disposition.match(/filename="?([^";]+)"?/i)?.[1] || fallbackName; const objectUrl = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = objectUrl; @@ -57,90 +36,200 @@ const downloadAdminFile = async (url: string, fallbackName: string): Promise Promise.all([ + requestJson('/api/admin/shipping-notice/rpa-profiles', auth()), + requestJson('/api/admin/shipping-notice/sources', auth()), + requestJson('/api/admin/shipping-notice/routing-rules', auth()), + requestJson('/api/admin/shipping-notice/external-mappings', auth()), + requestJson('/api/admin/shipping-notice/snapshots', auth()), + requestJson('/api/admin/shipping-notice/export-records', auth()), + requestJson('/api/admin/shipping-notice/parsing-profiles', auth()), + requestJson('/api/admin/shipping-notice/excel-templates', auth()), +]); -/** 分页查询货代标准客户。 */ -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 type ShippingInventoryField = { + id: number; + display_name: string; + description: string; + value_type: 'text' | 'integer' | 'decimal' | 'date'; + usage_type: 'match_identity' | 'inventory_quantity' | 'warehouse_identity' | 'general'; + status: 'active' | 'retired'; + sort_order: number; }; -export const getShippingCustomer = (id: number) => - requestJson(`/api/admin/shipping-customers/${id}`, auth()); +/** 管理可供不同库存文件解析方案复用的统一库存业务字段。 */ +export const getShippingInventoryFields = () => requestJson( + '/api/admin/shipping-notice/inventory-fields?include_retired=true', auth(), +); +export const createShippingInventoryField = (payload: Omit) => requestJson( + '/api/admin/shipping-notice/inventory-fields', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const updateShippingInventoryField = (id: number, payload: Omit) => requestJson( + `/api/admin/shipping-notice/inventory-fields/${id}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const retireShippingInventoryField = (id: number) => requestJson( + `/api/admin/shipping-notice/inventory-fields/${id}/retire`, { method: 'POST', ...jsonAuth() }, +); +export const deleteShippingInventoryField = (id: number) => requestJson( + `/api/admin/shipping-notice/inventory-fields/${id}`, { method: 'DELETE', ...auth() }, +); -export const createShippingCustomer = (payload: Record) => - requestJson('/api/admin/shipping-customers', { - method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), - }); +/** 上传或更新版本化发货 Excel 模板;文件仅在创建草稿时提交。 */ +export const createShippingExcelTemplate = (payload: FormData) => requestJson( + '/api/admin/shipping-notice/excel-templates', { method: 'POST', body: payload, ...auth() }, +); +export const updateShippingExcelTemplate = (id: number, payload: Record) => requestJson( + `/api/admin/shipping-notice/excel-templates/${id}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const getShippingExcelTemplateLayout = (id: number) => requestJson<{ template_id: number; sheets: Record> }>( + `/api/admin/shipping-notice/excel-templates/${id}/layout`, auth(), +); +export const createShippingExcelTemplateVersion = (id: number) => requestJson( + `/api/admin/shipping-notice/excel-templates/${id}/new-version`, { method: 'POST', ...jsonAuth() }, +); +export const publishShippingExcelTemplate = (id: number) => requestJson( + `/api/admin/shipping-notice/excel-templates/${id}/publish`, { method: 'POST', ...jsonAuth() }, +); +export const retireShippingExcelTemplate = (id: number) => requestJson( + `/api/admin/shipping-notice/excel-templates/${id}/retire`, { method: 'POST', ...jsonAuth() }, +); +export const deleteShippingExcelTemplate = (id: number) => requestJson( + `/api/admin/shipping-notice/excel-templates/${id}`, { method: 'DELETE', ...auth() }, +); -export const updateShippingCustomer = (id: number, payload: Record) => - requestJson(`/api/admin/shipping-customers/${id}`, { - method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), - }); +/** 读取库存路由可选的 published 订单字段和受控系统事实。 */ +export const getShippingInventoryRoutingFields = () => requestJson<{ + order_fields: Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>; + system_facts: string[]; + order_schema_published: boolean; +}>('/api/admin/shipping-notice/routing-fields', auth()); -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 type ShippingInventoryConfigurationCatalog = { + order_fields: Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>; + order_schema_published: boolean; + routing_system_facts: string[]; + inventory_fields: ShippingInventoryField[]; + template_system_facts: string[]; + template_source_kinds: Array<'order_field' | 'inventory_field' | 'system_fact' | 'constant'>; + template_row_modes: Array<'header' | 'line'>; + template_formatters: string[]; }; -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), -}); +/** 读取 Profile 与模板结构化编辑器使用的后端权威白名单。 */ +export const getShippingInventoryConfigurationCatalog = () => + requestJson( + '/api/admin/shipping-notice/configuration-catalog', auth(), + ); -export const publishShippingCustomerImport = (batchId: number) => - requestJson(`/api/admin/shipping-customer-imports/${batchId}/publish`, { - method: 'POST', ...auth(), +/** 保存和发布可复用库存解析 Profile。 */ +export const saveShippingInventoryParsingProfile = (payload: Record, id?: number) => requestJson( + `/api/admin/shipping-notice/parsing-profiles${id ? `/${id}` : ''}`, + { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const publishShippingInventoryParsingProfile = (id: number) => requestJson( + `/api/admin/shipping-notice/parsing-profiles/${id}/publish`, { method: 'POST', ...jsonAuth() }, +); +export const retireShippingInventoryParsingProfile = (id: number) => requestJson( + `/api/admin/shipping-notice/parsing-profiles/${id}/retire`, { method: 'POST', ...jsonAuth() }, +); +export const deleteShippingInventoryParsingProfile = (id: number) => requestJson( + `/api/admin/shipping-notice/parsing-profiles/${id}`, { method: 'DELETE', ...auth() }, +); + +/** 上传库存样本,由后端分析工作表、表头、栏位样例和字段建议。 */ +export const createShippingInventoryStructureAnalysis = (file: File) => { + const form = new FormData(); + form.set('file', file); + return requestJson('/api/admin/shipping-notice/inventory-structure-analyses', { + method: 'POST', body: form, ...auth(), }); +}; +/** 用已分析的真实栏位创建库存文件解析方案草稿。 */ +export const createShippingInventoryParsingDraftFromAnalysis = (id: number, payload: Record) => requestJson( + `/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`, + { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +/** 确认复用后端推荐的已发布解析方案;库存站点绑定仍由后续测试流程确认。 */ +export const adoptShippingInventoryParsingProfile = (analysisId: number, profileId: number) => requestJson( + `/api/admin/shipping-notice/inventory-structure-analyses/${analysisId}/adopt-profile`, + { method: 'POST', body: JSON.stringify({ profile_id: profileId }), ...jsonAuth() }, +); +/** 列出已确认、可由管理员沉淀为库存文件解析方案草稿的对话临时库存会话。 */ +export const listShippingTemporaryInventorySessions = () => requestJson( + '/api/admin/shipping-notice/temporary-inventory-sessions', auth(), +); +/** 使用临时会话锁定的结构和映射创建草稿;前端提交的字段映射不会被接受。 */ +export const createShippingParsingDraftFromTemporarySession = (sessionNo: string, payload: Record) => requestJson( + `/api/admin/shipping-notice/temporary-inventory-sessions/${encodeURIComponent(sessionNo)}/create-profile-draft`, + { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); -export const downloadShippingCustomerImportTemplate = () => - downloadAdminFile('/api/admin/shipping-customers/import-template', 'shipping_customer_import_template.xlsx'); +/** 保存 RPA Profile;password 未传或为空时由服务端保留旧密文。 */ +export const saveShippingRpaProfile = (payload: Record, id?: number) => requestJson( + `/api/admin/shipping-notice/rpa-profiles${id ? `/${id}` : ''}`, + { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const deleteShippingRpaProfile = (id: number) => requestJson( + `/api/admin/shipping-notice/rpa-profiles/${id}`, { method: 'DELETE', ...auth() }, +); -export const downloadShippingCustomerReconciliation = (batchId: number, batchNo: string) => - downloadAdminFile( - `/api/admin/shipping-customer-imports/${batchId}/reconciliation`, - `${batchNo}_reconciliation.csv`, - ); +/** 保存 Inventory Source,服务端校验其 Driver 与 Profile 一致。 */ +export const saveShippingInventorySource = (payload: Record, id?: number) => requestJson( + `/api/admin/shipping-notice/sources${id ? `/${id}` : ''}`, + { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const deleteShippingInventorySource = (id: number) => requestJson( + `/api/admin/shipping-notice/sources/${id}`, { method: 'DELETE', ...auth() }, +); +/** 仅在站点完成测试和必需绑定后启用正式库存运行。 */ +export const activateShippingInventorySource = (id: number) => requestJson( + `/api/admin/shipping-notice/sources/${id}/activate`, { method: 'POST', ...jsonAuth() }, +); +/** 停用库存站点但保留其既有配置和审计记录。 */ +export const deactivateShippingInventorySource = (id: number) => requestJson( + `/api/admin/shipping-notice/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() }, +); +/** 对停用库存站点发起异步 RPA 测试导出,测试文件不会进入生产库存池。 */ +export const startShippingInventoryConfigurationTest = (id: number) => requestJson( + `/api/admin/shipping-notice/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() }, +); +/** 查询库存站点测试导出与结构识别的后端真实状态。 */ +export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson( + `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(), +); +/** 管理员确认测试结果使用的已发布解析方案,才更新停用库存站点绑定。 */ +export const confirmShippingInventoryConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson( + `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`, + { method: 'POST', body: JSON.stringify({ profile_id: profileId }), ...jsonAuth() }, +); -export const getShippingCustomerShadowReport = (limit = 100) => - requestJson(`/api/admin/shipping-customer-shadow-report?limit=${limit}`, auth()); +/** 保存路由规则草稿;规则发布需调用独立接口以生成审计快照。 */ +export const saveShippingInventoryRule = (payload: Record, id?: number) => requestJson( + `/api/admin/shipping-notice/routing-rules${id ? `/${id}` : ''}`, + { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); -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 }) }, - ); +/** 发布草稿规则,服务端会保存不可变定义快照。 */ +export const publishShippingInventoryRule = (id: number) => requestJson( + `/api/admin/shipping-notice/routing-rules/${id}/publish`, + { method: 'POST', ...jsonAuth() }, +); +export const retireShippingInventoryRule = (id: number) => requestJson( + `/api/admin/shipping-notice/routing-rules/${id}/retire`, { method: 'POST', ...jsonAuth() }, +); +export const deleteShippingInventoryRule = (id: number) => requestJson( + `/api/admin/shipping-notice/routing-rules/${id}`, { method: 'DELETE', ...auth() }, +); + +/** 保存精确或 Source 默认外部系统映射。 */ +export const saveShippingInventoryExternalMapping = (payload: Record, id?: number) => requestJson( + `/api/admin/shipping-notice/external-mappings${id ? `/${id}` : ''}`, + { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +export const deleteShippingInventoryExternalMapping = (id: number) => requestJson( + `/api/admin/shipping-notice/external-mappings/${id}`, { method: 'DELETE', ...auth() }, +); // Users export const listAdminUsers = () => requestJson('/api/admin/users', auth()); diff --git a/frontend/src/features/admin/api/shipping-order-schema.api.ts b/frontend/src/features/admin/api/shipping-order-schema.api.ts new file mode 100644 index 00000000..249afe21 --- /dev/null +++ b/frontend/src/features/admin/api/shipping-order-schema.api.ts @@ -0,0 +1,124 @@ +/** + * features/admin/api/shipping-order-schema.api.ts + * 用途:订单 Schema 管理 JSON API。 + * 依赖:shared/api/client、shared/utils/auth、订单 Schema DTO。 + * 逻辑:页面通过本模块加载状态、维护字段与草稿、发布不可变版本。 + */ +import { requestJson } from '@/shared/api/client'; +import { getAuthHeaders } from '@/shared/utils/auth'; +import type { + ShippingOrderField, + ShippingOrderFieldConfig, + ShippingOrderSchemaAuditEventPage, + ShippingOrderExtractionAudit, + ShippingOrderSchemaState, + ShippingOrderSchemaVersion, + ShippingOrderSchemaVersionDiff, + ShippingOrderSchemaVersionPage, + ShippingOrderSchemaVersionUsage, +} from '../types/shipping-order-schema.types'; + +const auth = () => ({ headers: getAuthHeaders() }); +const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); + +/** 读取唯一订单 Schema、字段目录和版本。 */ +export const getShippingOrderSchemaState = () => + requestJson('/api/admin/shipping-order-schema', auth()); + +/** 初始化全局唯一订单 Schema。 */ +export const initializeShippingOrderSchema = (payload: { display_name: string; description?: string }) => + requestJson('/api/admin/shipping-order-schema', { + method: 'POST', body: JSON.stringify(payload), ...jsonAuth(), + }); + +/** 创建稳定订单字段身份。 */ +export const createShippingOrderField = (payload: Pick) => + requestJson('/api/admin/shipping-order-schema/fields', { + method: 'POST', body: JSON.stringify(payload), ...jsonAuth(), + }); + +/** 更新字段系统标识;服务端仍锁定已发布字段的位置和数据格式。 */ +export const updateShippingOrderField = ( + fieldId: string, + payload: Pick, +) => requestJson(`/api/admin/shipping-order-schema/fields/${fieldId}`, { + method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(), +}); + +/** 退役不再被草稿或下游运行配置引用的字段。 */ +export const retireShippingOrderField = (fieldId: string) => + requestJson(`/api/admin/shipping-order-schema/fields/${fieldId}/retire`, { + method: 'POST', ...jsonAuth(), + }); + +/** 删除未使用字段;服务端按历史引用自动决定物理删除或归档。 */ +export const deleteShippingOrderField = (fieldId: string) => + requestJson<{ field_id: string; action: 'deleted' | 'archived' }>(`/api/admin/shipping-order-schema/fields/${fieldId}`, { + method: 'DELETE', ...auth(), + }); + +/** 创建下一 Schema 草稿,可复制指定版本。 */ +export const createShippingOrderSchemaDraft = (payload: { copy_from_version_id?: number; change_note?: string }) => + requestJson('/api/admin/shipping-order-schema/versions', { + method: 'POST', body: JSON.stringify(payload), ...jsonAuth(), + }); + +/** 分页读取版本历史概要,完整定义由详情接口按需加载。 */ +export const listShippingOrderSchemaVersions = (page = 1, pageSize = 20, versionNumber?: number) => + requestJson( + `/api/admin/shipping-order-schema/versions?page=${page}&page_size=${pageSize}${versionNumber ? `&version_number=${versionNumber}` : ''}`, + auth(), + ); + +/** 读取一个版本的完整不可变快照。 */ +export const getShippingOrderSchemaVersion = (versionId: number) => + requestJson(`/api/admin/shipping-order-schema/versions/${versionId}`, auth()); + +/** 比较两个已保存版本,字段级变更由服务端按稳定 field_id 计算。 */ +export const getShippingOrderSchemaVersionDiff = (versionId: number, againstVersionId: number) => + requestJson( + `/api/admin/shipping-order-schema/versions/${versionId}/diff?against_version_id=${againstVersionId}`, + auth(), + ); + +/** 分页读取只追加的配置审计事件,历史抽屉不读取事件完整快照。 */ +export const listShippingOrderSchemaAuditEvents = (page = 1, pageSize = 20) => + requestJson( + `/api/admin/shipping-order-schema/audit-events?page=${page}&page_size=${pageSize}`, + auth(), + ); + +/** 分页读取实际使用指定 Schema 版本的订单解析记录与状态汇总。 */ +export const getShippingOrderSchemaVersionUsage = (versionId: number, page = 1, pageSize = 20) => + requestJson( + `/api/admin/shipping-order-schema/versions/${versionId}/usage?page=${page}&page_size=${pageSize}`, + auth(), + ); + +/** 读取单次动态订单解析冻结输入、LLM 输出、裁决和证据的只读审计详情。 */ +export const getShippingOrderExtractionAudit = (extractionId: number) => + requestJson( + `/api/admin/shipping-order-schema/order-extractions/${extractionId}`, + auth(), + ); + +/** 整体保存草稿字段配置及每个字段的版本纳入状态。 */ +export const saveShippingOrderSchemaDraft = ( + versionId: number, + payload: { fields: ShippingOrderFieldConfig[]; change_note?: string; expected_lock_version: number }, +) => requestJson(`/api/admin/shipping-order-schema/versions/${versionId}`, { + method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(), +}); + +/** 删除错误草稿;发布版本由服务端拒绝删除。 */ +export const deleteShippingOrderSchemaDraft = (versionId: number) => + requestJson(`/api/admin/shipping-order-schema/versions/${versionId}`, { + method: 'DELETE', ...auth(), + }); + +/** 发布草稿并自动退役上一当前版本。 */ +export const publishShippingOrderSchemaDraft = (versionId: number, expectedLockVersion: number) => + requestJson( + `/api/admin/shipping-order-schema/versions/${versionId}/publish`, + { method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth() }, + ); diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue index e8b708a9..1609f284 100644 --- a/frontend/src/features/admin/components/AdminNav.vue +++ b/frontend/src/features/admin/components/AdminNav.vue @@ -10,7 +10,7 @@ import { useI18n } from 'vue-i18n'; import { useRoute, useRouter } from 'vue-router'; import { LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText, - Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow + Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow, Warehouse } from 'lucide-vue-next'; import type { Component } from 'vue'; import { config } from '@/config'; @@ -36,6 +36,7 @@ const iconMap: Record = { wecom: Link2, permissions: Users, platform_apps: AppWindow, + shipping_inventory: Warehouse, requests: ShieldCheck, reports: BarChart2, }; diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts index 2a39ea19..f4b3d783 100644 --- a/frontend/src/features/admin/constants/modules.ts +++ b/frontend/src/features/admin/constants/modules.ts @@ -15,7 +15,7 @@ export interface AdminModuleMeta { /** 已独立拆分的模块(全部 admin 模块均已拆分) */ export const STANDALONE_ADMIN_MODULES = new Set([ - 'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'reports', + 'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'platform_apps', 'shipping_inventory', 'reports', ]); export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [ @@ -31,6 +31,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [ { id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' }, { id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' }, { id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' }, + { id: 'shipping_inventory', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.nav.shippingInventory', configKey: 'shipping_inventory' }, { id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' }, ]; @@ -46,7 +47,6 @@ 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-inventory/ShippingInventoryPage.vue b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue new file mode 100644 index 00000000..a18747d8 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue @@ -0,0 +1,1219 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue b/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue new file mode 100644 index 00000000..05d8ae80 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-schema/ShippingOrderSchemaPage.vue @@ -0,0 +1,828 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaAuditTimeline.vue b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaAuditTimeline.vue new file mode 100644 index 00000000..837f5c05 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaAuditTimeline.vue @@ -0,0 +1,50 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue new file mode 100644 index 00000000..ad78cdb1 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaExtractionAuditDrawer.vue @@ -0,0 +1,45 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionDiffDrawer.vue b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionDiffDrawer.vue new file mode 100644 index 00000000..7360a424 --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionDiffDrawer.vue @@ -0,0 +1,67 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionHistoryDrawer.vue b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionHistoryDrawer.vue new file mode 100644 index 00000000..ae58772c --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionHistoryDrawer.vue @@ -0,0 +1,153 @@ + + + + + + diff --git a/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue new file mode 100644 index 00000000..f1edbe6d --- /dev/null +++ b/frontend/src/features/admin/modules/shipping-order-schema/components/SchemaVersionUsageDrawer.vue @@ -0,0 +1,46 @@ + + + + + + diff --git a/frontend/src/features/admin/types/admin.types.ts b/frontend/src/features/admin/types/admin.types.ts index 26b2cf7e..00972190 100644 --- a/frontend/src/features/admin/types/admin.types.ts +++ b/frontend/src/features/admin/types/admin.types.ts @@ -17,6 +17,7 @@ export type AdminModuleId = | 'permissions' | 'requests' | 'platform_apps' + | 'shipping_inventory' | 'reports'; export type AdminReportTableId = diff --git a/frontend/src/features/admin/types/shipping-order-schema.types.ts b/frontend/src/features/admin/types/shipping-order-schema.types.ts new file mode 100644 index 00000000..846a73e0 --- /dev/null +++ b/frontend/src/features/admin/types/shipping-order-schema.types.ts @@ -0,0 +1,173 @@ +/** + * features/admin/types/shipping-order-schema.types.ts + * 用途:订单 Schema 管理 API 的字段、版本和能力目录类型。 + * 依赖:无。 + * 逻辑:shipping-order-schema API 与管理页面共享这些稳定 DTO。 + */ +export interface ShippingOrderField { + id: string; + field_code: string; + scope: 'header' | 'line'; + value_type: 'string' | 'decimal' | 'integer' | 'date' | 'boolean' | 'enum'; + status: 'active' | 'retired'; + published_once: boolean; +} + +export interface ShippingOrderFieldConfig { + field_id: string; + enabled?: boolean; + field_code?: string; + scope?: ShippingOrderField['scope']; + value_type?: ShippingOrderField['value_type']; + display_name: string; + description?: string | null; + required: boolean; + aliases: string[]; + normalizer_key: string; + validator_keys: string[]; + enum_options: string[]; + evidence_policy: { + required: boolean; + source_precedence: string[]; + conflict_policy: string; + allow_single_source: boolean; + }; + relation_role?: string | null; + comparator_key: string; + extraction_instruction?: string | null; + sequence?: number; +} + +export interface ShippingOrderSchemaVersion { + id: number; + version: number; + status: 'draft' | 'published' | 'retired'; + checksum?: string | null; + lock_version: number; + change_note?: string | null; + source_version_id?: number | null; + published_at?: string | null; + retired_at?: string | null; + created_at?: string | null; + updated_at?: string | null; + created_by?: SchemaVersionActor | null; + published_by?: SchemaVersionActor | null; + field_count: number; + definition?: { fields: ShippingOrderFieldConfig[] }; +} + +export interface SchemaVersionActor { + id: number; + display_name: string; +} + +export interface ShippingOrderSchemaVersionPage { + items: ShippingOrderSchemaVersion[]; + page: number; + page_size: number; + total: number; +} + +export interface ShippingOrderSchemaFieldChange { + key: string; + kind: 'value' | 'set'; + before: unknown; + after: unknown; + added?: string[]; + removed?: string[]; + order_changed?: boolean; +} + +export interface ShippingOrderSchemaFieldDiff { + field_id: string; + change_type: 'added' | 'removed' | 'modified' | 'unchanged'; + before: ShippingOrderFieldConfig | null; + after: ShippingOrderFieldConfig | null; + changes: ShippingOrderSchemaFieldChange[]; +} + +export interface ShippingOrderSchemaVersionDiff { + base_version: ShippingOrderSchemaVersion; + compare_version: ShippingOrderSchemaVersion; + summary: Record<'added' | 'removed' | 'modified' | 'unchanged', number>; + fields: ShippingOrderSchemaFieldDiff[]; +} + +export interface ShippingOrderSchemaAuditEvent { + id: number; + event_type: string; + version: Pick | null; + actor: SchemaVersionActor | null; + change_summary: Record; + request_id?: string | null; + created_at?: string | null; +} + +export interface ShippingOrderSchemaAuditEventPage { + items: ShippingOrderSchemaAuditEvent[]; + page: number; + page_size: number; + total: number; +} + +export interface ShippingOrderExtractionSummary { + id: number; + task_id?: number | null; + intake_id?: number | null; + status: string; + input_snapshot_hash: string; + created_at?: string | null; + updated_at?: string | null; +} + +export interface ShippingOrderSchemaVersionUsage { + version: ShippingOrderSchemaVersion; + summary: { + total: number; + status_counts: Record; + first_used_at?: string | null; + last_used_at?: string | null; + }; + items: ShippingOrderExtractionSummary[]; + page: number; + page_size: number; + total: number; +} + +export interface ShippingOrderExtractionAudit { + extraction: ShippingOrderExtractionSummary; + schema_version: ShippingOrderSchemaVersion; + input_snapshot: Record; + raw_llm_output: unknown; + normalized_result: unknown; + validation_result: unknown; + lines: Array<{ id: number; position: number; line_key?: string | null }>; + observations: Array>; + decisions: Array>; + field_values: Array>; +} + +export interface ShippingOrderSchemaState { + schema: null | { + id: number; + schema_code: string; + display_name: string; + description?: string | null; + status: string; + }; + fields: ShippingOrderField[]; + versions: ShippingOrderSchemaVersion[]; + catalog: { + field_types: string[]; + field_scopes: string[]; + normalizers: string[]; + validators: string[]; + comparators: string[]; + relation_roles: string[]; + source_types: string[]; + conflict_policies: string[]; + type_normalizers: Record; + type_validators: Record; + type_comparators: Record; + }; +} diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 124759e6..c56dc01d 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -1,17 +1,17 @@ /** * features/chat/api/shipping.api.ts - * 用途:封装发货通知相关 HTTP API,包括任务/批次查询、库存上传、映射确认、人工决策与 Excel 导出。 + * 用途:封装发货通知相关 HTTP API,包括任务/批次查询、人工决策与 Excel 导出。 * 依赖:统一 requestJson / BusinessError、shipping.api.types 类型定义。 * 逻辑:上游由 useChatShipping 与 shipping/* handler 调用本文件;本文件统一请求工作台后端 `/api/workspace/*` 路由并抛出标准错误。 */ import { BusinessError, requestJson } from '@/shared/api/client'; +import { getAuthHeaders } from '@/shared/utils/auth'; import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter'; import type { ShippingBatchSummary, ShippingBatchUiState, ShippingConversationWorkspace, ShippingDecisionResponse, - ShippingInventoryUploadResponse, ShippingNoticeHeader, ShippingNoticeLine, ShippingNoticeUploadResponse, @@ -125,20 +125,16 @@ export const getWorkspaceShippingTaskUiState = (taskNo: string) => export const workspaceShippingExportUrl = (taskNo: string) => `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`; -/** - * 上传库存 Excel,并由后端完成解析与 schema preview 生成。 - * @param taskNo - 发货任务编号 - * @param file - 用户选择的库存文件 - * @returns 库存上传与解析结果 - */ -export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) { - const form = new FormData(); - form.append('file', file); - const body = await requestJson( - `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/upload-inventory`, - { method: 'POST', body: form }, - ); - return assertShippingOk(body); +/** 下载一个批次或显式任务集合的当前 ready 发货 Excel ZIP。 */ +export async function downloadWorkspaceShippingExportArchive(payload: { batch_no?: string; task_nos?: string[] }) { + const response = await fetch('/api/workspace/shipping-exports/archive', { + method: 'POST', headers: { 'Content-Type': 'application/json', ...getAuthHeaders() }, body: JSON.stringify(payload), + }); + if (!response.ok) throw new Error('Shipping export archive download failed'); + const disposition = response.headers.get('Content-Disposition') || ''; + const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]; + const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1]; + return { blob: await response.blob(), filename: encoded ? decodeURIComponent(encoded) : (plain || 'shipping_exports.zip') }; } /** @@ -169,20 +165,6 @@ export const confirmWorkspaceShippingCustomer = (taskNo: string, customerId: num jsonPost({ customer_id: customerId }), ); -/** - * 提交库存字段映射。 - * @param taskNo - 发货任务编号 - * @param columnMappingJson - 前端表单确认后的 map_json - * @returns 映射应用与库存解析结果 - */ -export async function applyWorkspaceShippingInventoryMapping(taskNo: string, columnMappingJson: Record) { - const body = await requestJson( - `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/apply-inventory-mapping`, - jsonPost({ map_json: columnMappingJson }), - ); - return assertShippingOk(body); -} - /** * 创建单个发货任务。 * @param params - 建单参数,可包含 source_type、conversation_id、raw_content @@ -681,7 +663,6 @@ export type { ShippingConversationWorkspaceSummary, ShippingCurrentStepProgress, ShippingDecisionResponse, - ShippingInventoryUploadResponse, ShippingMatchLineResult, ShippingNoticeHeader, ShippingNoticeLine, diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index c22de856..99ee148e 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -437,7 +437,7 @@ watch( :ref="bindShippingPickerRef" type="file" class="hidden" - accept=".xlsx,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv" + accept=".xls,.xlsx,.csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv" @change="emit('shipping-inventory-selected', $event)" /> diff --git a/frontend/src/features/chat/components/ChatMessageList.vue b/frontend/src/features/chat/components/ChatMessageList.vue index d4e5e7df..ba932750 100644 --- a/frontend/src/features/chat/components/ChatMessageList.vue +++ b/frontend/src/features/chat/components/ChatMessageList.vue @@ -9,7 +9,7 @@ import ChatThinkingBubble from './ChatThinkingBubble.vue'; import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue'; import ToolRunProgressCard from './ToolRunProgressCard.vue'; import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue'; -import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappingMessage.vue'; +import type { ShippingMessageHandlers } from './messages/shippingMessageHandlers'; import type { TrainingHandlers } from './messages/TrainingExamQuestionMessage.vue'; import type { ChatMessage } from '../types/chat.types'; import type { ToolRunProgress } from '../api/toolRunProgress.api'; @@ -34,7 +34,7 @@ const { isShippingNoticeAgent: boolean; handlers: ChatMessageBubbleHandlers; leaveHandlers: LeaveMessageHandlers; - shippingHandlers: ShippingMappingHandlers; + shippingHandlers: ShippingMessageHandlers; trainingHandlers: TrainingHandlers; shouldRenderMessage: (msg: ChatMessage) => boolean; shouldShowToolRunProgressAfterMessage: (msg: ChatMessage, index: number) => boolean; diff --git a/frontend/src/features/chat/components/ChatViewContent.vue b/frontend/src/features/chat/components/ChatViewContent.vue index 0a30156c..4be75f13 100644 --- a/frontend/src/features/chat/components/ChatViewContent.vue +++ b/frontend/src/features/chat/components/ChatViewContent.vue @@ -233,7 +233,7 @@ watch(() => page.currentAgentId, () => { :is-shipping-notice-agent="page.isShippingNoticeAgent" :handlers="page.messageBubbleHandlers" :leave-handlers="page.leaveMessageHandlers" - :shipping-handlers="page.shippingMappingHandlers" + :shipping-handlers="page.shippingMessageHandlers" :training-handlers="page.trainingHandlers" :should-render-message="page.shouldRenderMessage" :should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage" diff --git a/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue b/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue index fbe46f9b..21a38eb1 100644 --- a/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue +++ b/frontend/src/features/chat/components/ShippingBatchWorkspaceDrawer.vue @@ -337,12 +337,6 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => advice: t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'), }; } - if (reason === 'align_review' || reviewStatus === 'align_review') { - return { - title: t('chat.shippingNoticeUi.diagnosisAlignReviewTitle'), - advice: t('chat.shippingNoticeUi.diagnosisAlignReviewAdvice'), - }; - } if (reason === 'low_confidence' || reviewStatus === 'parse_review') { return { title: t('chat.shippingNoticeUi.diagnosisParseReviewTitle'), @@ -370,7 +364,7 @@ const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => : 'chat.shippingNoticeUi.diagnosisInventorySourceAdvice'), }; } - if (reason === 'map_infer' || processStatus === 'waiting_inventory') { + if (processStatus === 'waiting_inventory') { return { title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'), advice: t('chat.shippingNoticeUi.diagnosisInventoryWaitingAdvice'), @@ -392,9 +386,6 @@ const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') { return t('chat.shippingNoticeUi.suggestShortageActions'); } - if (reason === 'align_review' || reviewStatus === 'align_review') { - return t('chat.shippingNoticeUi.suggestConfirmMapping'); - } if (reason === 'low_confidence' || reviewStatus === 'parse_review') { return t('chat.shippingNoticeUi.suggestReviewParse'); } diff --git a/frontend/src/features/chat/components/ShippingNoticeCandidateReview.vue b/frontend/src/features/chat/components/ShippingNoticeCandidateReview.vue index 0c825d31..d5f07c4b 100644 --- a/frontend/src/features/chat/components/ShippingNoticeCandidateReview.vue +++ b/frontend/src/features/chat/components/ShippingNoticeCandidateReview.vue @@ -148,6 +148,11 @@ function displayCell(value: unknown): string { return text || '—'; } +/** 将客户匹配状态转换为面向业务用户的文案。 */ +function customerMatchStatus(status: string): string { + return t(`chat.shippingCustomerMatch.status.${status}`); +} + /** 对当前首个重复目标应用决策;强制新建时要求填写原因。 */ function resolveDuplicate(candidateNo: string, action: ShippingDuplicateAction): void { const candidate = candidates.value.find((item) => item.candidateNo === candidateNo); @@ -225,6 +230,36 @@ function submitForceCreate(candidateNo: string): void { +
+
+ {{ t('chat.shippingCustomerMatch.title') }} +
+ + + + + + + + + + + + + + + + + + + + + +
{{ t('chat.shippingCustomerMatch.role') }}{{ t('chat.shippingCustomerMatch.rawName') }}{{ t('chat.shippingCustomerMatch.standardName') }}{{ t('chat.shippingCustomerMatch.shortCode') }}{{ t('chat.shippingCustomerMatch.site') }}{{ t('chat.shippingCustomerMatch.statusLabel') }}
{{ t(`chat.shippingCustomerMatch.roles.${match.role}`) }}{{ displayCell(match.raw_name) }}{{ displayCell(match.standard_name) }}{{ displayCell(match.short_code) }}{{ displayCell(match.candidates?.find((item) => item.site_id === match.site_id)?.site_name) }}{{ customerMatchStatus(match.status) }}
+
void; getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] }; downloadInlineFile: (file: InlineDownloadFile) => void; - getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null; getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null; canOpenQueryPreview: (msg: ChatMessage) => boolean; getQueryPreviewSummary: (msg: ChatMessage) => string; @@ -83,7 +82,7 @@ const { isLatestAssistantMessage: boolean; handlers: ChatMessageBubbleHandlers; leaveHandlers: LeaveMessageHandlers; - shippingHandlers: ShippingMappingHandlers; + shippingHandlers: ShippingMessageHandlers; trainingHandlers: TrainingHandlers; }>(); @@ -752,13 +751,8 @@ function handleInlineDownload(file: InlineDownloadFile): void { :index="index" :handlers="leaveHandlers" /> - diff --git a/frontend/src/features/chat/components/messages/ShippingInventoryMappingMessage.vue b/frontend/src/features/chat/components/messages/ShippingInventoryMappingMessage.vue deleted file mode 100644 index f234eee0..00000000 --- a/frontend/src/features/chat/components/messages/ShippingInventoryMappingMessage.vue +++ /dev/null @@ -1,122 +0,0 @@ -/** - * features/chat/components/messages/ShippingInventoryMappingMessage.vue - * 用途:发货 Agent 库存 Excel 列映射表单消息 UI。 - * 依赖:chat.types、shipping.api.types、shipping.types。 - * 逻辑:ChatView 渲染 mapping 类型消息时挂载;通过 ShippingMappingHandlers 与 useChatShipping 交互。 - */ - - - diff --git a/frontend/src/features/chat/components/messages/shippingMessageHandlers.ts b/frontend/src/features/chat/components/messages/shippingMessageHandlers.ts new file mode 100644 index 00000000..0b53cf58 --- /dev/null +++ b/frontend/src/features/chat/components/messages/shippingMessageHandlers.ts @@ -0,0 +1,18 @@ +/** + * features/chat/components/messages/shippingMessageHandlers.ts + * 用途:定义发货通知订单复核与库存匹配消息共用的页面处理器契约。 + * 依赖:chat.types、shipping.api.types、shipping.types。 + * 逻辑:页面组合处理器后传给消息列表;不包含已下线的任务级库存列映射能力。 + */ +import type { ChatMessage } from '../../types/chat.types'; +import type { ShippingNoticeHeader, ShippingNoticeLine } from '../../types/shipping.api.types'; +import type { ShippingMatchResultPayload, ShippingParseReviewPayload } from '../../types/shipping.types'; + +export interface ShippingMessageHandlers { + getParseReviewPayload: (msg: ChatMessage) => ShippingParseReviewPayload | null; + getMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null; + updateHeader: (msg: ChatMessage, fields: Partial) => Promise; + updateLine: (msg: ChatMessage, lineIndex: number, patch: Partial) => Promise; + addLine: (msg: ChatMessage, line: Partial) => Promise; + removeLine: (msg: ChatMessage, lineIndex: number) => Promise; +} diff --git a/frontend/src/features/chat/composables/useChat.ts b/frontend/src/features/chat/composables/useChat.ts index fe83fcb1..2a831f34 100644 --- a/frontend/src/features/chat/composables/useChat.ts +++ b/frontend/src/features/chat/composables/useChat.ts @@ -532,7 +532,7 @@ export function useChat() { | { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string } | { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string } >, - context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string }, + context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }, hooks?: SendMessageLifecycleHooks, ): Promise => { const displayQuery = String( @@ -601,6 +601,8 @@ export function useChat() { task_id: context?.task_id || undefined, batch_no: context?.batch_no || undefined, shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined, + shipping_temporary_inventory_asset_no: context?.shipping_temporary_inventory_asset_no || undefined, + shipping_temporary_inventory_session_no: context?.shipping_temporary_inventory_session_no || undefined, display_query: context && Object.prototype.hasOwnProperty.call(context, 'display_query') ? context.display_query : undefined, diff --git a/frontend/src/features/chat/composables/useChatPage.ts b/frontend/src/features/chat/composables/useChatPage.ts index abf054aa..89d49d47 100644 --- a/frontend/src/features/chat/composables/useChatPage.ts +++ b/frontend/src/features/chat/composables/useChatPage.ts @@ -38,7 +38,7 @@ import { createChatPageMarkdownApi, createChatPageSendApi, createLeaveMessageHandlers, - createShippingMappingHandlers, + createShippingMessageHandlers, createShippingPickerRefHolder, createTrainingHandlers, useChatPageDialogs, @@ -287,7 +287,6 @@ export function useChatPage() { history, loadHistory, input, - chatScrollContainer, attachments: attachmentApi.attachments, selectedKb: agent.selectedKb, isUploadingAttachments: attachmentApi.isUploadingAttachments, @@ -395,7 +394,6 @@ export function useChatPage() { getSourceTitle, getSourceMeta, getSourceBrief, - getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload, getShippingMatchResultPayload: shipping.getShippingMatchResultPayload, canOpenQueryPreview: queryPreview.canOpen, getQueryPreviewSummary: queryPreview.getSummary, @@ -456,7 +454,7 @@ export function useChatPage() { shipping.shippingBindSend(() => sendApi.handleSend()); const leaveMessageHandlers = createLeaveMessageHandlers(leave); - const shippingMappingHandlers = createShippingMappingHandlers(shipping); + const shippingMessageHandlers = createShippingMessageHandlers(shipping); const trainingHandlers = createTrainingHandlers(training); const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef)); const shippingNoticePickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingNoticePickerRef)); @@ -588,7 +586,7 @@ export function useChatPage() { training, ...leave, leaveMessageHandlers, - shippingMappingHandlers, + shippingMessageHandlers, trainingHandlers, shippingPickerRefHolder, shippingNoticePickerRefHolder, diff --git a/frontend/src/features/chat/composables/useChatShipping.ts b/frontend/src/features/chat/composables/useChatShipping.ts index e72bfd77..abc815f9 100644 --- a/frontend/src/features/chat/composables/useChatShipping.ts +++ b/frontend/src/features/chat/composables/useChatShipping.ts @@ -24,24 +24,19 @@ import { createShippingActionsRefresher, createShippingConversationHelpers, createShippingDecisionHandlers, - createShippingMappingFormHandlers, createShippingMenuHandlers, createShippingParseReviewHandlers, createShippingSendHandlers, createShippingUploadHandlers, onNoticeBatchConversationChanging, findLatestShippingTaskId, - getShippingInventoryMappingPayload, getShippingMatchResultPayload, getShippingParseReviewPayload, - getShippingInventorySampleRowText, - hasShippingInventorySampleRows, - normalizeShippingHeaderForDisplay, sanitizeShippingConversationText, shippingActionButtonClass, } from '../shipping'; import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter'; -import { classifyShippingUploadFile } from '../shipping/shippingUploadPrompt'; +import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt'; import { extractExt } from '../constants/shipping'; import { getWorkspaceShippingConversationBatches, @@ -83,7 +78,6 @@ export interface UseChatShippingOptions { history: Ref; loadHistory: () => Promise; input: Ref; - chatScrollContainer: Ref; attachments: Ref; selectedKb: Ref; isUploadingAttachments: Ref; @@ -97,7 +91,7 @@ export interface UseChatShippingOptions { agentId: number, kb: string, files: ChatUploadFileSpec[], - context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string }, + context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }, hooks?: SendMessageLifecycleHooks, ) => Promise; startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise; @@ -235,7 +229,7 @@ export const resolveLatestShippingMessageRecoveryPayload = ( /** * 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。 * - * 核心逻辑:统一管理当前任务/批次上下文,组合上传、映射、决策、动作刷新等子模块,并对 ChatView 暴露稳定 API。 + * 核心逻辑:统一管理当前任务/批次上下文,组合上传、解析复核、匹配结果、决策与动作刷新等子模块,并对 ChatView 暴露稳定 API。 * @param options - 聊天页依赖与响应式状态集合 * @returns 发货通知聊天场景所需的状态、事件处理器和工具函数 */ @@ -253,7 +247,6 @@ export function useChatShipping(options: UseChatShippingOptions) { history, loadHistory, input, - chatScrollContainer, attachments, selectedKb, isUploadingAttachments, @@ -316,7 +309,6 @@ export function useChatShipping(options: UseChatShippingOptions) { const retryingShippingPendingTasks = ref(false); const activeShippingTaskDetail = ref(null); const shippingFocusReason = ref(''); - const shippingInventorySchemaPreviewCache = ref>({}); const autoResumedShippingTasks = ref>({}); const lastConversationSyncKey = ref(''); let shippingStatusPollTimer: ReturnType | null = null; @@ -628,7 +620,6 @@ export function useChatShipping(options: UseChatShippingOptions) { shippingWorkspaceOpen.value = false; retryingShippingPendingTasks.value = false; activeShippingTaskDetail.value = null; - shippingInventorySchemaPreviewCache.value = {}; lastConversationSyncKey.value = ''; }; @@ -753,25 +744,6 @@ export function useChatShipping(options: UseChatShippingOptions) { getActiveBatchTaskId, }); - const { - openShippingInventoryMappingFormForTask, - applyShippingInventoryMappingForm, - reuploadShippingInventoryFromMappingForm, - } = createShippingMappingFormHandlers({ - messages, - chatScrollContainer, - shippingInventorySchemaPreviewCache, - shippingInventoryPickerRef, - pendingShippingUploadTaskId, - resolvedShippingTaskId, - newLocalMessageId, - saveLocalMessageToBackend, - startChatTurn, - currentAgentId, - refreshShippingActions, - msg, - }); - /** * Dify SSE 完成后立即净化最后一条回复,并同步后端动作按钮。 * @@ -860,11 +832,9 @@ export function useChatShipping(options: UseChatShippingOptions) { history, isShippingNoticeAgent, currentAgentId, - shippingInventorySchemaPreviewCache, getActiveShippingTaskId, getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '', loadHistory, - openShippingInventoryMappingFormForTask, refreshShippingActions, startChatTurn, msg, @@ -1074,13 +1044,22 @@ export function useChatShipping(options: UseChatShippingOptions) { shippingBatchTasks, shippingInventorySelectionActive, shippingInventorySelectionTaskId, - shippingInventorySchemaPreviewCache, getActiveShippingTaskId, startChatTurn, refreshShippingActions, getParsedIntakeNos: shippingIntakes.getParsedIntakeNos, getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos, clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments, + sendTemporaryInventoryMessage: async (assetNo, fileName) => sendMessage( + `我已上传库存文件:${fileName},请先检查文件结构并说明下一步。`, + currentAgentId.value, + selectedKb.value, + [], + { + shipping_temporary_inventory_asset_no: assetNo, + display_query: `上传库存文件:${fileName}`, + }, + ), msg, t, }); @@ -1092,7 +1071,6 @@ export function useChatShipping(options: UseChatShippingOptions) { getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '', messages, sendShippingMenuMessage, - openShippingInventoryMappingFormForTask, openShippingInventoryPicker, openShippingNoticePicker, openShippingCustomerDialog, @@ -1272,21 +1250,20 @@ export function useChatShipping(options: UseChatShippingOptions) { const inputEl = event.target as HTMLInputElement | null; const files = inputEl?.files ? Array.from(inputEl.files) : []; if (!files.length) return false; - const noticeFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) === 'notice'); - const otherFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) !== 'notice'); + const noticeFiles = files.filter((file) => !isShippingSpreadsheetFile(file, extractExt)); + const spreadsheetFiles = files.filter((file) => isShippingSpreadsheetFile(file, extractExt)); if (noticeFiles.length) { void shippingIntakes.enqueueNoticeFiles(noticeFiles); } - // 同一次选择中的库存/其他文件直接落入本地附件,避免清空 input 后通用 handler 丢失 FileList - for (const file of otherFiles) { - const kind = classifyShippingUploadFile(file, extractExt); + // 表格附件先留在本地等待用户声明;不能因扩展名直接送订单或库存解析。 + for (const file of spreadsheetFiles) { attachments.value = [ ...attachments.value, { id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`, kind: 'local', file, - type: kind === 'inventory' ? 'document' : 'document', + type: 'document', uploadStatus: 'waiting', uploadProgress: 0, }, @@ -1455,14 +1432,8 @@ export function useChatShipping(options: UseChatShippingOptions) { queryShippingShortageDetails, resetShippingConversationState, resumeShippingTaskFromQuery, - normalizeShippingHeaderForDisplay, - getShippingInventoryMappingPayload, getShippingMatchResultPayload, getShippingParseReviewPayload, - hasShippingInventorySampleRows, - getShippingInventorySampleRowText, - applyShippingInventoryMappingForm, - reuploadShippingInventoryFromMappingForm, updateShippingParseReviewHeader, updateShippingParseReviewLine, addShippingParseReviewLine, diff --git a/frontend/src/features/chat/constants/shipping.ts b/frontend/src/features/chat/constants/shipping.ts index 32026788..11d71fa0 100644 --- a/frontend/src/features/chat/constants/shipping.ts +++ b/frontend/src/features/chat/constants/shipping.ts @@ -14,7 +14,6 @@ export const SHIPPING_MENU_ACTION_SPECS: Record< { id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' } > = { upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' }, - paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' }, retry_rpa: { id: 'retry_rpa', label: '重新获取库存', message: '重新获取库存', variant: 'secondary' }, confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' }, reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' }, @@ -23,8 +22,6 @@ export const SHIPPING_MENU_ACTION_SPECS: Record< export const SHIPPING_DECISION_ACTIONS = new Set([ 'confirm', - 'confirm_inventory_mapping', - 'correct_inventory_mapping', 'reparse_inventory', 'retry_rpa', 'reject', diff --git a/frontend/src/features/chat/page/useChatPageConversation.spec.ts b/frontend/src/features/chat/page/useChatPageConversation.spec.ts index 2a6325d7..be500abd 100644 --- a/frontend/src/features/chat/page/useChatPageConversation.spec.ts +++ b/frontend/src/features/chat/page/useChatPageConversation.spec.ts @@ -99,7 +99,6 @@ const createUploadContext = ( shippingBatchTasks: ref([]), shippingInventorySelectionActive: ref(false), shippingInventorySelectionTaskId: ref(''), - shippingInventorySchemaPreviewCache: ref({}), getActiveShippingTaskId: () => '', startChatTurn, refreshShippingActions: vi.fn(async () => undefined), diff --git a/frontend/src/features/chat/page/useChatPageHandlerBundles.ts b/frontend/src/features/chat/page/useChatPageHandlerBundles.ts index 3ebfd0af..cf2a1e06 100644 --- a/frontend/src/features/chat/page/useChatPageHandlerBundles.ts +++ b/frontend/src/features/chat/page/useChatPageHandlerBundles.ts @@ -1,8 +1,8 @@ /** - * 对话页:子组件 inject 用的 handlers 对象打包(请假表单、出货映射、消息气泡)。 + * 对话页:子组件 inject 用的 handlers 对象打包(请假表单、发货消息、消息气泡)。 */ import type { LeaveMessageHandlers } from '../components/messages/LeaveMessageBlock.vue'; -import type { ShippingMappingHandlers } from '../components/messages/ShippingInventoryMappingMessage.vue'; +import type { ShippingMessageHandlers } from '../components/messages/shippingMessageHandlers'; import type { TrainingHandlers } from '../components/messages/TrainingExamQuestionMessage.vue'; import type { useChatLeave } from '../composables/useChatLeave'; import type { useChatShipping } from '../composables/useChatShipping'; @@ -29,14 +29,8 @@ type LeaveHandlerSource = Pick< type ShippingHandlerSource = Pick< ReturnType, - | 'getShippingInventoryMappingPayload' - | 'normalizeShippingHeaderForDisplay' - | 'hasShippingInventorySampleRows' - | 'getShippingInventorySampleRowText' | 'getShippingParseReviewPayload' | 'getShippingMatchResultPayload' - | 'reuploadShippingInventoryFromMappingForm' - | 'applyShippingInventoryMappingForm' | 'updateShippingParseReviewHeader' | 'updateShippingParseReviewLine' | 'addShippingParseReviewLine' @@ -65,19 +59,11 @@ export function createLeaveMessageHandlers(leave: LeaveHandlerSource): LeaveMess }; } -/** 出货库存映射块 handlers(ShippingInventoryMappingMessage) */ -export function createShippingMappingHandlers(shipping: ShippingHandlerSource): ShippingMappingHandlers { +/** 发货通知订单复核与匹配消息 handlers。 */ +export function createShippingMessageHandlers(shipping: ShippingHandlerSource): ShippingMessageHandlers { return { - getPayload: shipping.getShippingInventoryMappingPayload, - normalizeHeader: shipping.normalizeShippingHeaderForDisplay, - hasSampleRows: shipping.hasShippingInventorySampleRows, - getSampleRowText: shipping.getShippingInventorySampleRowText, getParseReviewPayload: shipping.getShippingParseReviewPayload, getMatchResultPayload: shipping.getShippingMatchResultPayload, - reupload: shipping.reuploadShippingInventoryFromMappingForm, - apply: shipping.applyShippingInventoryMappingForm, - updateParseReviewHeader: shipping.updateShippingParseReviewHeader, - updateParseReviewLine: shipping.updateShippingParseReviewLine, updateHeader: shipping.updateShippingParseReviewHeader, updateLine: shipping.updateShippingParseReviewLine, addLine: shipping.addShippingParseReviewLine, diff --git a/frontend/src/features/chat/page/useChatPageMarkdown.spec.ts b/frontend/src/features/chat/page/useChatPageMarkdown.spec.ts index 47be9013..82d0883e 100644 --- a/frontend/src/features/chat/page/useChatPageMarkdown.spec.ts +++ b/frontend/src/features/chat/page/useChatPageMarkdown.spec.ts @@ -39,7 +39,6 @@ function createContext( getSourceTitle: () => '', getSourceMeta: () => '', getSourceBrief: () => '', - getShippingInventoryMappingPayload: () => null, getShippingMatchResultPayload: () => null, canOpenQueryPreview: () => false, getQueryPreviewSummary: () => '', diff --git a/frontend/src/features/chat/page/useChatPageMarkdown.ts b/frontend/src/features/chat/page/useChatPageMarkdown.ts index 758419ef..91cc3f48 100644 --- a/frontend/src/features/chat/page/useChatPageMarkdown.ts +++ b/frontend/src/features/chat/page/useChatPageMarkdown.ts @@ -79,7 +79,6 @@ export interface ChatPageMarkdownContext { getSourceTitle: ChatMessageBubbleHandlers['getSourceTitle']; getSourceMeta: ChatMessageBubbleHandlers['getSourceMeta']; getSourceBrief: ChatMessageBubbleHandlers['getSourceBrief']; - getShippingInventoryMappingPayload: ChatMessageBubbleHandlers['getShippingInventoryMappingPayload']; getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null; canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview']; getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary']; @@ -368,7 +367,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) { if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result' - || msgItem?.type === 'shipping-inventory-mapping' || msgItem?.type === 'shipping-parse-review' || msgItem?.type === 'shipping-match-result') { return true; @@ -459,7 +457,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) { openAssetImage: ctx.openAssetImage, getInlineDownloadFiles: safeExtractInlineDownloadFiles, downloadInlineFile, - getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload, getShippingMatchResultPayload: ctx.getShippingMatchResultPayload, canOpenQueryPreview: ctx.canOpenQueryPreview, getQueryPreviewSummary: ctx.getQueryPreviewSummary, diff --git a/frontend/src/features/chat/page/useChatPageSend.ts b/frontend/src/features/chat/page/useChatPageSend.ts index d0f866b9..e4e15e51 100644 --- a/frontend/src/features/chat/page/useChatPageSend.ts +++ b/frontend/src/features/chat/page/useChatPageSend.ts @@ -54,7 +54,7 @@ export interface ChatPageSendContext { agentId: number, kb: string, files: ChatUploadFileSpec[], - context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string }, + context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }, hooks?: SendMessageLifecycleHooks, ) => Promise; refreshHistoryAfterSend: () => Promise; @@ -75,7 +75,7 @@ export interface ChatPageSendContext { msg: { warning: (text: string) => void; info: (text: string) => void }; t: (key: string) => string; copiedIndex: Ref; - getChatContext?: () => { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string }; + getChatContext?: () => { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }; onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise; } diff --git a/frontend/src/features/chat/shipping/index.ts b/frontend/src/features/chat/shipping/index.ts index ea59f562..2029f638 100644 --- a/frontend/src/features/chat/shipping/index.ts +++ b/frontend/src/features/chat/shipping/index.ts @@ -7,7 +7,6 @@ export * from './shippingText'; export * from './shippingMenu'; export * from './shippingIntents'; -export * from './shippingMapping'; export * from './shippingTaskId'; export * from './shippingDownload'; export * from './shippingDecisionFormat'; @@ -18,7 +17,6 @@ export * from './shippingStepper'; export * from './shippingLocalMessages'; export * from './shippingConversation'; export * from './useChatShippingRefresh'; -export * from './useChatShippingMappingForm'; export * from './useChatShippingParseReview'; export * from './useChatShippingDecision'; export * from './useChatShippingMenuHandler'; diff --git a/frontend/src/features/chat/shipping/shippingDecisionFormat.spec.ts b/frontend/src/features/chat/shipping/shippingDecisionFormat.spec.ts index c01e1f71..a6c5c067 100644 --- a/frontend/src/features/chat/shipping/shippingDecisionFormat.spec.ts +++ b/frontend/src/features/chat/shipping/shippingDecisionFormat.spec.ts @@ -1,34 +1,24 @@ /** * features/chat/shipping/shippingDecisionFormat.spec.ts - * 用途:验证库存映射人工修正摘要使用 v2 系统字段名。 + * 用途:验证库存重新上传决策只输出业务引导,不再暴露任务级字段映射。 * 依赖:vitest、shippingDecisionFormat。 - * 逻辑:锁死建议映射展示中的 part_number,防止旧 sku 契约回流。 + * 逻辑:断言重新上传提示和任务编号完整,同时排除旧技术字段。 */ import { describe, expect, it } from 'vitest'; import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat'; describe('formatShippingDecisionAssistantMessage', () => { - it('renders part_number for inventory mapping suggestions', () => { + it('guides inventory reupload without legacy mapping terms', () => { const text = formatShippingDecisionAssistantMessage( - 'correct_inventory_mapping', - { - message: '请修正映射', - data: { - schema_preview: { - headers: ['Supplier Sku', 'COM ID', 'Qty Available'], - suggested_mapping: { - part_number: 'Supplier Sku', - reservation_id: 'COM ID', - available_qty: 'Qty Available', - }, - }, - }, - }, - 'SN-MAP-001', + 'reparse_inventory', + { message: '当前库存已解除关联。' }, + 'SN-REUPLOAD-001', '操作已完成', ); - expect(text).toContain('- part_number → Supplier Sku'); - expect(text).not.toContain('- sku →'); + expect(text).toContain('选择库存文件'); + expect(text).toContain('SN-REUPLOAD-001'); + expect(text).not.toContain('schema_preview'); + expect(text).not.toContain('map_json'); }); }); diff --git a/frontend/src/features/chat/shipping/shippingDecisionFormat.ts b/frontend/src/features/chat/shipping/shippingDecisionFormat.ts index 425003f9..c62cf1dd 100644 --- a/frontend/src/features/chat/shipping/shippingDecisionFormat.ts +++ b/frontend/src/features/chat/shipping/shippingDecisionFormat.ts @@ -2,7 +2,7 @@ * features/chat/shipping/shippingDecisionFormat.ts * 用途:决策 API 响应格式化为助手 Markdown 消息。 * 依赖:无;useChatShippingDecision 在 submit_decision 成功后调用。 - * 逻辑:按 decision 类型追加映射提示、下一步指引与任务编号尾注。 + * 逻辑:按 decision 类型追加业务提示与任务编号尾注。 */ /** * 将 submit_decision 结果格式化为本地 assistant 消息 Markdown。 @@ -14,34 +14,8 @@ export function formatShippingDecisionAssistantMessage( fallbackDoneMessage: string, ): string { const lines: string[] = [result.message || fallbackDoneMessage]; - if (decision === 'correct_inventory_mapping') { - const preview = (result.data?.schema_preview || {}) as Record; - const headers = Array.isArray(preview.headers) ? (preview.headers as unknown[]).filter(Boolean) : []; - const suggested = (preview.suggested_mapping || {}) as Record; - if (preview.header_row_index) { - lines.push('', `表头在第 ${preview.header_row_index} 行:${headers.join(' | ')}`); - } else if (headers.length) { - lines.push('', `当前表头:${headers.join(' | ')}`); - } - const mappingLines = [ - suggested.part_number ? `- part_number → ${suggested.part_number}` : null, - suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null, - suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null, - ].filter((line): line is string => Boolean(line)); - if (mappingLines.length) { - lines.push('', '建议列映射:', ...mappingLines); - } - lines.push( - '', - '如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。', - '也可点击「选择库存文件」重新上传。', - ); - } else if (decision === 'confirm_inventory_mapping') { - if (String(result.checkpoint || '').trim() === 'map_ok') { - lines.push('', '下一步:匹配库存与发货需求。'); - } - } else if (decision === 'reparse_inventory') { - lines.push('', '请重新上传或粘贴库存 Excel。'); + if (decision === 'reparse_inventory') { + lines.push('', '请点击「选择库存文件」重新上传。'); } lines.push('', `任务编号:${taskId}`); return lines.join('\n'); diff --git a/frontend/src/features/chat/shipping/shippingIntents.spec.ts b/frontend/src/features/chat/shipping/shippingIntents.spec.ts deleted file mode 100644 index 7f0de166..00000000 --- a/frontend/src/features/chat/shipping/shippingIntents.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * features/chat/shipping/shippingIntents.spec.ts - * 用途:验证发货聊天自然语言库存映射遵循 v2 字段契约。 - * 依赖:vitest、shippingIntents。 - * 逻辑:覆盖完整三字段映射与缺 Reservation 拒绝分支。 - */ -import { describe, expect, it } from 'vitest'; -import { parseShippingColumnMappingFromText } from './shippingIntents'; - -describe('parseShippingColumnMappingFromText', () => { - it('normalizes SKU wording to the v2 part_number key', () => { - expect(parseShippingColumnMappingFromText([ - 'SKU -> Supplier Sku', - 'Reservation ID -> COM ID', - 'Available Qty -> Qty Available', - ].join('\n'))).toEqual({ - part_number: 'Supplier Sku', - reservation_id: 'COM ID', - available_qty: 'Qty Available', - }); - }); - - it('rejects mappings that omit Reservation ID', () => { - expect(parseShippingColumnMappingFromText([ - 'part_number -> Supplier Sku', - 'available_qty -> Qty Available', - ].join('\n'))).toBeNull(); - }); -}); diff --git a/frontend/src/features/chat/shipping/shippingIntents.ts b/frontend/src/features/chat/shipping/shippingIntents.ts index 24ce422a..aedcc513 100644 --- a/frontend/src/features/chat/shipping/shippingIntents.ts +++ b/frontend/src/features/chat/shipping/shippingIntents.ts @@ -2,7 +2,7 @@ * features/chat/shipping/shippingIntents.ts * 用途:发货聊天用户输入意图识别,供 handleSend 前置拦截。 * 依赖:shippingMenu.resolveShippingNumericChoice、types/shipping.types。 - * 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载、列映射与切票。 + * 逻辑:useChatShippingSendHandler 调用;覆盖手工上传、库存上传、Excel 生成/下载与切票。 */ import { resolveShippingNumericChoice } from './shippingMenu'; import type { ShippingMenuAction } from '../types/shipping.types'; @@ -15,43 +15,6 @@ export interface ShippingTaskSwitchIntent { /** * 从自然语言文本解析库存列映射(part_number / reservation_id / available_qty → Excel 列名)。 */ -export function parseShippingColumnMappingFromText(content: string): Record | null { - const raw = String(content || '').trim(); - if (!raw) return null; - if (!/[→>=-]/.test(raw)) return null; - const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean); - const mapping: Record = {}; - const normalizeRight = (s: string) => String(s || '') - .replace(/[::]/g, '') - .replace(/列$/g, '') - .replace(/字段$/g, '') - .replace(/^\[|\]$/g, '') - .trim(); - const toKey = (left: string) => { - const s = left.toLowerCase(); - if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id'; - if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty'; - if (s.includes('part_number') || s.includes('part number') || s.includes('sku') || left.includes('料号') || left.includes('物料')) { - return 'part_number'; - } - return ''; - }; - for (const line of lines) { - const m = line.match(/^\s*(.+?)\s*(?:→|->|=>|=|:|:)\s*(.+?)\s*$/); - if (!m) continue; - const left = m[1]; - const right = m[2]; - if (!left || !right) continue; - const key = toKey(left.trim()); - if (!key) continue; - const col = normalizeRight(right); - if (!col) continue; - mapping[key] = col; - } - if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) return null; - return mapping; -} - export function isShippingManualUploadIntent(text: string): boolean { const normalized = text.trim(); if (!normalized) return false; diff --git a/frontend/src/features/chat/shipping/shippingMapping.ts b/frontend/src/features/chat/shipping/shippingMapping.ts deleted file mode 100644 index 9be586ff..00000000 --- a/frontend/src/features/chat/shipping/shippingMapping.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * features/chat/shipping/shippingMapping.ts - * 用途:库存列映射消息 payload 读取与字段对齐 Markdown 生成。 - * 依赖:shippingText.normalizeShippingHeaderForDisplay、chat.types、shipping.types。 - * 逻辑:ShippingInventoryMappingMessage 与 useChatShippingMappingForm 读取 mapping 消息数据。 - */ -import { normalizeShippingHeaderForDisplay } from './shippingText'; -import type { ChatMessage } from '../types/chat.types'; -import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types'; - -/** - * 从 shipping-inventory-mapping 类型消息中提取 taskId、schema_preview 与 form。 - */ -export function getShippingInventoryMappingPayload(chatMsg: ChatMessage): ShippingInventoryMappingFormPayload | null { - if (!chatMsg || chatMsg.type !== 'shipping-inventory-mapping') return null; - const payload = chatMsg.payload; - if (!payload || typeof payload !== 'object') return null; - const taskId = String((payload as ShippingInventoryMappingFormPayload).taskId || '').trim(); - const schemaPreview = (payload as ShippingInventoryMappingFormPayload).schema_preview; - const form = (payload as ShippingInventoryMappingFormPayload).form; - if (!taskId || !schemaPreview || !form) return null; - return payload as ShippingInventoryMappingFormPayload; -} - -export function hasShippingInventorySampleRows(chatMsg: ChatMessage): boolean { - const rows = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows; - return Array.isArray(rows) && rows.length > 0; -} - -export function getShippingInventorySampleRowText(chatMsg: ChatMessage): string { - const row = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows?.[0]; - return Array.isArray(row) ? row.map((cell) => String(cell)).join(' | ') : ''; -} - -/** - * 将 field_alignment API 响应转为 Markdown 表格文本,供发送给 Agent 确认。 - */ -export function buildShippingFieldAlignmentText(payload: { data?: { field_alignment?: Record } }): string { - const alignment = payload?.data?.field_alignment; - if (!alignment || typeof alignment !== 'object') return ''; - const invCols = (alignment as { inventory_columns?: { mapping?: Record } }).inventory_columns || {}; - const mapping = invCols.mapping || {}; - const rows: Array<[string, string]> = [ - ['part_number', normalizeShippingHeaderForDisplay(mapping?.part_number?.source_column) || '(未识别)'], - ['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别)'], - ['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'], - ]; - const lines: string[] = []; - const matchRule = String((alignment as { match_rule?: string }).match_rule || '').trim(); - if (matchRule) lines.push(`匹配规则:${matchRule}`); - lines.push('', '字段对齐表:', '', '|系统字段|库存列|', '|---|---|'); - for (const [k, v] of rows) { - lines.push(`|${k}|${v}|`); - } - const warnings = Array.isArray((alignment as { warnings?: unknown[] }).warnings) - ? (alignment as { warnings: unknown[] }).warnings.filter(Boolean) - : []; - if (warnings.length) { - lines.push('', '提示:', ...warnings.map((w) => `- ${String(w)}`)); - } - return lines.join('\n').trim(); -} diff --git a/frontend/src/features/chat/shipping/shippingMenu.ts b/frontend/src/features/chat/shipping/shippingMenu.ts index 21bd1e88..0c4ef841 100644 --- a/frontend/src/features/chat/shipping/shippingMenu.ts +++ b/frontend/src/features/chat/shipping/shippingMenu.ts @@ -30,7 +30,6 @@ export function classifyShippingMenuLine(desc: string): ShippingMenuAction | nul if (!normalized) return null; if (/已确认/.test(normalized)) return null; if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload'; - if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste'; if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa'; if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse'; if (/驳回|取消|reject/i.test(desc)) return 'reject'; @@ -78,11 +77,9 @@ export function normalizeApiShippingButtons( /** * 从用户文本与助手上下文识别 submit_decision 所需的 action id。 */ -export function resolveShippingDecisionFromText(text: string, assistantContext: string): string | null { +export function resolveShippingDecisionFromText(text: string, _assistantContext: string): string | null { const normalized = text.trim(); const direct: Record = { - 更正映射: 'correct_inventory_mapping', - 更正列映射: 'correct_inventory_mapping', 重新上传库存: 'reparse_inventory', 重新上传: 'reparse_inventory', 驳回: 'reject', @@ -92,9 +89,6 @@ export function resolveShippingDecisionFromText(text: string, assistantContext: }; if (direct[normalized]) return direct[normalized]; if (normalized === '确认') { - if (assistantContext.includes('字段对齐') || assistantContext.includes('field_alignment') || assistantContext.includes('库存字段对齐')) { - return 'confirm_inventory_mapping'; - } return 'confirm'; } return null; diff --git a/frontend/src/features/chat/shipping/shippingStepper.ts b/frontend/src/features/chat/shipping/shippingStepper.ts index c65fd1b2..deee1a8c 100644 --- a/frontend/src/features/chat/shipping/shippingStepper.ts +++ b/frontend/src/features/chat/shipping/shippingStepper.ts @@ -111,11 +111,9 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5; if (processStatus === 'matched') return 4; if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4; - if (reviewStatus === 'align_review' || pendingReason === 'align_review') return 3; if (processStatus === 'inventory_ready' || matchStatus) return 4; if ( processStatus === 'waiting_inventory' - || pendingReason === 'map_infer' || pendingReason === 'rpa_pending' || pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted' @@ -167,7 +165,6 @@ export function buildShippingWorkflowSteps( || pendingReason === 'inventory_source_unresolved' )) || (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted')) - || (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review')) || (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage')) || (index === 6 && processStatus === 'upload_failed') ) { diff --git a/frontend/src/features/chat/shipping/shippingText.ts b/frontend/src/features/chat/shipping/shippingText.ts index 88be23a5..d8bea34e 100644 --- a/frontend/src/features/chat/shipping/shippingText.ts +++ b/frontend/src/features/chat/shipping/shippingText.ts @@ -249,18 +249,6 @@ export function stripShippingActionListByButtons( export function sanitizeShippingConversationText(text: string, enabled: boolean): string { if (!enabled) return text; let result = sanitizeShippingRuntimeStatusText(String(text || '')) - .replace( - /已回到列映射步骤。?请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi, - '已回到库存字段确认步骤。请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。', - ) - .replace( - /请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi, - '请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。', - ) - .replace( - /根据\s*data\.schema_preview\.headers\s*与\s*sample_rows\s*推断\s*JSON[^。.\n]*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi, - '请根据库存表头和样例行确认字段对应关系。', - ) .replace(/通过\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传') .replace(/在\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传') .replace(/(?:Hxops|HXOPS|hxops)\s*聊天区/gi, '当前对话') @@ -278,12 +266,6 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean) .replace(/\bgenerate_excel\b/gi, '生成发货 Excel') .replace(/\bgenerate_shipment_excel\b/gi, '生成发货 Excel') .replace(/\bupload_to_freight\b/gi, '上传货代系统') - .replace(/\bapply_inventory_mapping\b/gi, '应用库存字段映射') - .replace(/\bget_inventory_schema_preview\b/gi, '读取库存表头预览') - .replace(/\bschema_preview(?:\.headers)?\b/gi, '库存表头预览') - .replace(/\bdata\.库存表头预览\b/gi, '库存表头预览') - .replace(/\bmap_json\b/gi, '字段映射') - .replace(/\bsample_rows\b/gi, '样例行') .replace(/\bretry_rpa\b/gi, '重新获取库存') .replace(/\bretry_upload\b/gi, '重试上传货代') .replace(/\bstructured\b/gi, '结构化内容') @@ -309,11 +291,3 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean) export function stripShippingActionsDirectiveComment(rawText: string): string { return String(rawText || '').replace(//gi, '').trim(); } - -/** - * 库存表头列名展示规范化(空格转 NBSP,避免 Markdown 表格换行)。 - */ -export function normalizeShippingHeaderForDisplay(raw: unknown): string { - const text = String(raw ?? '').replace(/\s+/g, ' ').trim(); - return text.replace(/ /g, '\u00A0'); -} diff --git a/frontend/src/features/chat/shipping/shippingTurnActions.ts b/frontend/src/features/chat/shipping/shippingTurnActions.ts index 346a134a..041bdfc5 100644 --- a/frontend/src/features/chat/shipping/shippingTurnActions.ts +++ b/frontend/src/features/chat/shipping/shippingTurnActions.ts @@ -133,17 +133,6 @@ export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record< return refs; } -export function buildShippingUploadInventoryTurn(taskNo: string, file: File) { - const task = String(taskNo || '').trim().toUpperCase(); - return { - actionType: 'shipping.upload_inventory', - displayText: `上传库存文件:${file.name}`, - payload: { task_no: task }, - files: [file], - refs: buildShippingTurnRefs(task), - }; -} - export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) { const task = String(taskNo || '').trim().toUpperCase(); return { @@ -155,16 +144,6 @@ export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) { }; } -export function buildShippingApplyMappingTurn(taskNo: string, mapping: Record) { - const task = String(taskNo || '').trim().toUpperCase(); - return { - actionType: 'shipping.apply_inventory_mapping', - displayText: `应用库存列映射(任务 ${task})`, - payload: { task_no: task, map_json: mapping }, - refs: buildShippingTurnRefs(task), - }; -} - export function buildShippingSwitchFocusTurn(batchNo: string, taskNo: string, displayText: string) { const batch = String(batchNo || '').trim(); const task = String(taskNo || '').trim().toUpperCase(); diff --git a/frontend/src/features/chat/shipping/shippingUploadPrompt.ts b/frontend/src/features/chat/shipping/shippingUploadPrompt.ts index c6cbeae0..706f8f1b 100644 --- a/frontend/src/features/chat/shipping/shippingUploadPrompt.ts +++ b/frontend/src/features/chat/shipping/shippingUploadPrompt.ts @@ -1,6 +1,6 @@ /** * features/chat/shipping/shippingUploadPrompt.ts - * 用途:库存/通知上传后发给 Dify 的提示语构建与附件类型分类。 + * 用途:通知上传后提示语构建、文件格式识别与临时库存声明判断。 * 依赖:无;useChatShippingUploadHandler 在上传成功后调用。 * 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。 */ @@ -9,40 +9,6 @@ import i18n from '@/i18n'; /** * 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。 */ -export function buildShippingInventoryUploadPrompt( - result: Record | null | undefined, - fileName?: string, -): string { - const checkpoint = String(result?.checkpoint || '').trim(); - const hasAlignment = Boolean(result?.data && typeof result.data === 'object' - && (result.data as { field_alignment?: unknown }).field_alignment - && typeof (result.data as { field_alignment?: unknown }).field_alignment === 'object'); - const suggestOk = Boolean((result?.data as { suggest_ok?: boolean } | undefined)?.suggest_ok); - const batchNo = String( - (result?.batch_no as string | undefined) - || ((result?.data as { batch_no?: string } | undefined)?.batch_no) - || ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no) - || '', - ).trim(); - const prefix = batchNo - ? (fileName - ? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatchWithFile', { fileName, batchNo })) - : String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixBatch', { batchNo }))) - : (fileName - ? String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefixWithFile', { fileName })) - : String(i18n.global.t('chat.shippingNoticePrompt.inventory.prefix'))); - if (checkpoint === 'map_infer') { - if (suggestOk) { - return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferSuggested', { prefix })); - } - return String(i18n.global.t('chat.shippingNoticePrompt.inventory.mapInferPending', { prefix })); - } - if (checkpoint === 'align_review' || hasAlignment) { - return String(i18n.global.t('chat.shippingNoticePrompt.inventory.alignReview', { prefix })); - } - return String(i18n.global.t('chat.shippingNoticePrompt.inventory.default', { prefix })); -} - /** * 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发画布 LLM 抽取 + parse_notice)。 */ @@ -94,13 +60,30 @@ export function buildShippingNoticeUploadPrompt( } /** - * 按扩展名判断附件是库存 Excel 还是发货通知文件。 + * 判断文件是否为后端当前可受控分析的表格格式。 + * 格式只是技术能力,不能据此推断文件一定是库存或订单。 */ -export function classifyShippingUploadFile( +export function isShippingSpreadsheetFile( file: File, extractExt: (name: string) => string, -): 'inventory' | 'notice' { +): boolean { const ext = extractExt(file.name || '').toLowerCase(); - if (['xlsx', 'xls', 'csv'].includes(ext)) return 'inventory'; - return 'notice'; + return ['xlsx', 'xls', 'csv'].includes(ext); +} + +/** + * 判断用户是否明确声明当前附件是库存文件。 + * 仅用于临时库存分支门禁;不能从文件名、表格后缀或模型猜测推导。 + */ +export function isTemporaryInventoryDeclaration(text: string): boolean { + const value = String(text || '').trim(); + if (!value) return false; + return [ + /这是.*库存(?:文件|表|excel|csv)?/i, + /(?:请|帮我|麻烦).*(?:分析|解析|识别).*(?:库存|stock)/i, + /(?:上传|附件|这个|该).*(?:库存文件|库存表|库存excel|库存csv)/i, + /(?:库存文件|库存表|库存excel|库存csv).*(?:分析|解析|识别|使用)/i, + /(?:this|the).*(?:is|are).*(?:inventory|stock)/i, + /(?:analyse|analyze|parse).*(?:inventory|stock)/i, + ].some((pattern) => pattern.test(value)); } diff --git a/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts b/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts index d5c39650..216e6125 100644 --- a/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingDecision.spec.ts @@ -2,7 +2,7 @@ * features/chat/shipping/useChatShippingDecision.spec.ts * 用途:验证发货通知决策处理器经 Chat Turn 发起,silent 模式不追加用户气泡。 * 依赖:vitest、vue refs、useChatShippingDecision。 - * 逻辑:mock startChatTurn,覆盖 silent/普通决策、显式 taskId 与 inventory_mapping 分支。 + * 逻辑:mock startChatTurn,覆盖 silent/普通决策与显式 taskId 分支。 */ import { computed, ref } from 'vue'; import { describe, expect, it, vi, beforeEach } from 'vitest'; @@ -26,11 +26,9 @@ const createContext = ( history: ref([{ conversation_id: 'conv-001' }]), isShippingNoticeAgent: computed(() => true), currentAgentId: computed(() => 42), - shippingInventorySchemaPreviewCache: ref({}), getActiveShippingTaskId: () => 'SN-FOCUS-001', getActiveShippingBatchNo: () => 'BATCH-001', loadHistory: vi.fn(async () => undefined), - openShippingInventoryMappingFormForTask: vi.fn(async () => true), refreshShippingActions: vi.fn(async () => undefined), startChatTurn: defaultStartChatTurn, msg: { @@ -115,21 +113,6 @@ describe('useChatShippingDecision', () => { expect(ctx.msg.warning).not.toHaveBeenCalled(); }); - it('submits confirm_inventory_mapping via submit_decision Chat Turn', async () => { - const ctx = createContext(); - const { executeShippingDecision } = createShippingDecisionHandlers(ctx); - - const ok = await executeShippingDecision('confirm_inventory_mapping', '确认'); - - expect(ok).toBe(true); - expect(ctx.startChatTurn).toHaveBeenCalledWith( - expect.objectContaining({ - actionType: 'shipping.submit_decision', - payload: { task_no: 'SN-FOCUS-001', decision: 'confirm_inventory_mapping' }, - }), - ); - }); - it('returns false when startChatTurn reports failure', async () => { const ctx = createContext({ startChatTurn: vi.fn(async () => false), diff --git a/frontend/src/features/chat/shipping/useChatShippingDecision.ts b/frontend/src/features/chat/shipping/useChatShippingDecision.ts index ff684404..b50fffe0 100644 --- a/frontend/src/features/chat/shipping/useChatShippingDecision.ts +++ b/frontend/src/features/chat/shipping/useChatShippingDecision.ts @@ -16,11 +16,9 @@ export interface ShippingDecisionContext { history: Ref; isShippingNoticeAgent: ComputedRef; currentAgentId: ComputedRef; - shippingInventorySchemaPreviewCache: Ref>; getActiveShippingTaskId: () => string; getActiveShippingBatchNo: () => string; loadHistory: () => Promise; - openShippingInventoryMappingFormForTask: (taskId: string) => Promise; refreshShippingActions: () => Promise; startChatTurn: (options: StartChatTurnOptions) => Promise; msg: { warning: (text: string) => void; success: (text: string) => void }; @@ -54,23 +52,9 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) { } }; - const afterDecisionTurn = async (decision: string, taskId: string, assistantMsg?: ChatMessage) => { - if (decision === 'correct_inventory_mapping' && assistantMsg?.payload && typeof assistantMsg.payload === 'object') { - const toolResult = (assistantMsg.payload as { tool_result?: { data?: { schema_preview?: unknown } } }).tool_result; - const preview = toolResult?.data?.schema_preview; - const key = String(taskId || '').trim().toUpperCase(); - if (key && preview && typeof preview === 'object') { - ctx.shippingInventorySchemaPreviewCache.value = { - ...ctx.shippingInventorySchemaPreviewCache.value, - [key]: preview, - }; - } - } + const afterDecisionTurn = async () => { await syncHistoryIfNeeded(); void ctx.refreshShippingActions(); - if (decision === 'correct_inventory_mapping') { - await ctx.openShippingInventoryMappingFormForTask(taskId); - } }; /** @@ -105,7 +89,8 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) { silent: options?.silent, hooks: { onAssistantMessageFinished: async (assistantMsg) => { - await afterDecisionTurn(decision, taskId, assistantMsg); + void assistantMsg; + await afterDecisionTurn(); }, }, }); diff --git a/frontend/src/features/chat/shipping/useChatShippingMappingForm.spec.ts b/frontend/src/features/chat/shipping/useChatShippingMappingForm.spec.ts deleted file mode 100644 index 8e8d3528..00000000 --- a/frontend/src/features/chat/shipping/useChatShippingMappingForm.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * features/chat/shipping/useChatShippingMappingForm.spec.ts - * 用途:验证库存人工列映射严格使用 v2 料号与 Reservation 契约。 - * 依赖:vitest、Vue refs、shipping.api、useChatShippingMappingForm。 - * 逻辑:覆盖表单预填、完整映射提交和缺 Reservation 本地阻断。 - */ -import { computed, ref } from 'vue'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { createShippingMappingFormHandlers, type ShippingMappingFormContext } from './useChatShippingMappingForm'; -import type { ChatMessage } from '../types/chat.types'; - -const { getWorkspaceShippingTask } = vi.hoisted(() => ({ - getWorkspaceShippingTask: vi.fn(), -})); - -vi.mock('@/features/chat/api/shipping.api', () => ({ - getWorkspaceShippingTask, -})); - -const createContext = ( - overrides: Partial = {}, -): ShippingMappingFormContext => ({ - messages: ref([]), - chatScrollContainer: ref(null), - shippingInventorySchemaPreviewCache: ref({ - 'SN-MAP-001': { - headers: ['Supplier Sku', 'COM ID', 'Qty Available'], - suggested_mapping: { - part_number: 'Supplier Sku', - reservation_id: 'COM ID', - available_qty: 'Qty Available', - }, - }, - }), - shippingInventoryPickerRef: ref(null), - pendingShippingUploadTaskId: ref(''), - resolvedShippingTaskId: ref(''), - newLocalMessageId: () => 'local-mapping-1', - saveLocalMessageToBackend: vi.fn(async () => undefined), - startChatTurn: vi.fn(async () => true), - currentAgentId: computed(() => 42), - refreshShippingActions: vi.fn(async () => undefined), - msg: { warning: vi.fn() }, - ...overrides, -}); - -describe('useChatShippingMappingForm', () => { - beforeEach(() => { - getWorkspaceShippingTask.mockReset(); - getWorkspaceShippingTask.mockResolvedValue({ - lines: [{ part_number: 'D4-A08AR12000002', reservation_id: '3000092917', qty: 10 }], - }); - }); - - it('prefills and submits the v2 inventory mapping fields', async () => { - const ctx = createContext(); - const handlers = createShippingMappingFormHandlers(ctx); - - expect(await handlers.openShippingInventoryMappingFormForTask('sn-map-001')).toBe(true); - const message = ctx.messages.value[0]; - expect(message.payload).toMatchObject({ - order: { line_count: 1, part_numbers: ['D4-A08AR12000002'] }, - form: { - part_number: 'Supplier Sku', - reservation_id: 'COM ID', - available_qty: 'Qty Available', - }, - }); - - await handlers.applyShippingInventoryMappingForm(message); - - expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({ - actionType: 'shipping.apply_inventory_mapping', - payload: { - task_no: 'SN-MAP-001', - map_json: { - part_number: 'Supplier Sku', - reservation_id: 'COM ID', - available_qty: 'Qty Available', - }, - }, - })); - }); - - it('blocks submission when the Reservation ID mapping is missing', async () => { - const ctx = createContext(); - const handlers = createShippingMappingFormHandlers(ctx); - await handlers.openShippingInventoryMappingFormForTask('SN-MAP-001'); - const message = ctx.messages.value[0]; - const payload = message.payload as { form: { reservation_id: string } }; - payload.form.reservation_id = ''; - - await handlers.applyShippingInventoryMappingForm(message); - - expect(ctx.startChatTurn).not.toHaveBeenCalled(); - expect(ctx.msg.warning).toHaveBeenCalledWith('请先选择内部料号列、Reservation ID 列与可用数量列'); - }); -}); diff --git a/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts b/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts deleted file mode 100644 index 5cc89505..00000000 --- a/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts +++ /dev/null @@ -1,174 +0,0 @@ -/** - * features/chat/shipping/useChatShippingMappingForm.ts - * 用途:管理库存列映射表单的打开、提交和重新上传交互。 - * 依赖:shipping.api、shippingMapping、chat.types、Vue nextTick。 - * 逻辑:由 useChatShipping 调用本文件;本文件负责把 schema preview 渲染成聊天卡片,并把表单提交回后端映射接口。 - */ -import { nextTick } from 'vue'; -import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api'; -import { buildShippingApplyMappingTurn } from './shippingTurnActions'; -import { getShippingInventoryMappingPayload } from './shippingMapping'; -import type { StartChatTurnOptions } from '../types/chat-turn.types'; -import type { ChatMessage } from '../types/chat.types'; -import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types'; -import type { Ref } from 'vue'; - -export interface ShippingMappingFormContext { - messages: Ref; - chatScrollContainer: Ref; - shippingInventorySchemaPreviewCache: Ref>; - shippingInventoryPickerRef: Ref; - pendingShippingUploadTaskId: Ref; - resolvedShippingTaskId: Ref; - newLocalMessageId: (prefix: string) => string; - saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise; - startChatTurn: (options: StartChatTurnOptions) => Promise; - currentAgentId: import('vue').ComputedRef; - refreshShippingActions: () => Promise; - msg: { warning: (text: string) => void }; -} - -/** - * 创建库存列映射表单处理器。 - * - * 核心逻辑:按任务号打开或复用映射卡片,提交 map_json 到后端,并在成功后刷新动作按钮。 - * @param ctx - 库存映射表单上下文 - * @returns 打开、应用和重传库存映射表单的处理函数 - */ -export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) { - const scrollToLastShippingInventoryMapping = async (): Promise => { - const container = ctx.chatScrollContainer.value; - if (!container) return false; - let idx = -1; - for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) { - if ((ctx.messages.value[i] as ChatMessage)?.type === 'shipping-inventory-mapping') { - idx = i; - break; - } - } - if (idx < 0) return false; - await nextTick(); - await nextTick(); - const el = container.querySelector(`[data-msg-index="${idx}"]`) as HTMLElement | null; - if (!el) return false; - el.scrollIntoView({ behavior: 'smooth', block: 'start' }); - return true; - }; - - const openShippingInventoryMappingFormForTask = async (taskId: string): Promise => { - const id = String(taskId || '').trim().toUpperCase(); - if (!id) return false; - const existingIdx = (() => { - for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) { - const chatMsg = ctx.messages.value[i] as ChatMessage; - if (chatMsg?.type !== 'shipping-inventory-mapping') continue; - const payload = getShippingInventoryMappingPayload(chatMsg); - if (payload?.taskId?.trim().toUpperCase() === id) return i; - } - return -1; - })(); - if (existingIdx >= 0) { - return scrollToLastShippingInventoryMapping(); - } - const schemaPreview = ctx.shippingInventorySchemaPreviewCache.value[id]; - if (!schemaPreview || typeof schemaPreview !== 'object') { - ctx.msg.warning('未找到表头预览,请重新上传库存文件后再点击“修改映射”'); - return false; - } - const detail = await getWorkspaceShippingTask(id).catch(() => null); - const rawLines = Array.isArray((detail as { lines?: unknown[] } | null)?.lines) - ? (detail as { lines: unknown[] }).lines - : []; - const partNumbers = [...new Set( - rawLines - .map((line) => String((line as Record)?.part_number || '').trim()) - .filter(Boolean), - )].slice(0, 40); - const suggested = (schemaPreview as { suggested_mapping?: Record }).suggested_mapping || {}; - const mappingMsg: ChatMessage = { - role: 'assistant', - type: 'shipping-inventory-mapping', - content: [ - '请用下拉框选择库存列映射(必须从表头中选择)。', - `任务编号:${id}`, - ].filter(Boolean).join('\n'), - payload: { - taskId: id, - schema_preview: schemaPreview, - order: { line_count: rawLines.length, part_numbers: partNumbers }, - form: { - part_number: String(suggested?.part_number || '').trim(), - available_qty: String(suggested?.available_qty || '').trim(), - reservation_id: String(suggested?.reservation_id || '').trim(), - }, - applying: false, - } as ShippingInventoryMappingFormPayload, - local_id: ctx.newLocalMessageId('shipping-assistant'), - local_only: true, - }; - ctx.messages.value.push(mappingMsg); - await ctx.saveLocalMessageToBackend(mappingMsg); - await scrollToLastShippingInventoryMapping(); - return true; - }; - - const applyShippingInventoryMappingForm = async (msgObj: ChatMessage) => { - const payload = getShippingInventoryMappingPayload(msgObj); - if (!payload) return; - if (payload.applying) return; - const taskId = String(payload.taskId || '').trim(); - if (!taskId) { - ctx.msg.warning('未找到任务编号'); - return; - } - const mapping: Record = { - part_number: String(payload.form?.part_number || '').trim(), - available_qty: String(payload.form?.available_qty || '').trim(), - reservation_id: String(payload.form?.reservation_id || '').trim(), - }; - if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) { - ctx.msg.warning('请先选择内部料号列、Reservation ID 列与可用数量列'); - return; - } - payload.applying = true; - try { - const turn = buildShippingApplyMappingTurn(taskId, mapping); - const ok = await ctx.startChatTurn({ - agentId: ctx.currentAgentId.value, - inputType: 'form_submit', - displayText: turn.displayText, - actionType: turn.actionType, - payload: turn.payload, - refs: turn.refs, - hooks: { - onAssistantMessageFinished: async () => { - ctx.resolvedShippingTaskId.value = taskId; - void ctx.refreshShippingActions(); - }, - }, - }); - if (!ok) ctx.msg.warning('应用映射失败'); - } catch (e: unknown) { - const errorMessage = e instanceof Error ? e.message : '应用映射失败'; - ctx.msg.warning(errorMessage); - } finally { - payload.applying = false; - await ctx.saveLocalMessageToBackend(msgObj); - } - }; - - const reuploadShippingInventoryFromMappingForm = (msgObj: ChatMessage) => { - const payload = getShippingInventoryMappingPayload(msgObj); - if (!payload) return; - const taskId = String(payload.taskId || '').trim(); - if (!taskId) return; - ctx.pendingShippingUploadTaskId.value = taskId; - ctx.shippingInventoryPickerRef.value?.click(); - }; - - return { - openShippingInventoryMappingFormForTask, - applyShippingInventoryMappingForm, - reuploadShippingInventoryFromMappingForm, - }; -} diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts index 34e3cbb1..49a08a26 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts @@ -38,7 +38,6 @@ const createContext = ( getActiveShippingBatchNo: () => 'BATCH-001', messages: ref([]), sendShippingMenuMessage: vi.fn(async () => undefined), - openShippingInventoryMappingFormForTask: vi.fn(async () => true), openShippingInventoryPicker: vi.fn((_taskId?: string) => true), openShippingNoticePicker: vi.fn((_taskId?: string) => true), executeShippingDecision: vi.fn(async () => true), diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts index 4c50a90c..33b788cc 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts @@ -20,7 +20,6 @@ export interface ShippingMenuHandlerContext { getActiveShippingBatchNo: () => string; messages: Ref; sendShippingMenuMessage: (message: string) => Promise; - openShippingInventoryMappingFormForTask: (taskId: string) => Promise; openShippingInventoryPicker: (taskId?: string) => boolean; openShippingNoticePicker: (taskId?: string) => boolean; openShippingCustomerDialog: (taskId: string) => Promise; @@ -208,15 +207,6 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone')); return; } - if (action.id === 'edit_inventory_mapping') { - const taskId = resolveTaskId(); - if (!taskId) { - ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId')); - return; - } - await ctx.openShippingInventoryMappingFormForTask(taskId); - return; - } if (action.id === 'upload_inventory_file') { ctx.openShippingInventoryPicker(resolveTaskId()); return; @@ -225,10 +215,6 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { ctx.openShippingNoticePicker(resolveTaskId()); return; } - if (action.id === 'paste_inventory_json') { - ctx.msg.info(ctx.t('chat.shippingNoticePasteHint')); - return; - } if (action.id === 'reparse_inventory') { if (chatMsg?.shipping_actions_used) return; const taskId = resolveTaskId(); diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts index 326a34a9..76af2181 100644 --- a/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts @@ -82,6 +82,40 @@ describe('useChatShippingSendHandler', () => { expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting'); }); + it('keeps a spreadsheet pending until the user explicitly declares it as inventory', async () => { + const attachment = { + id: 'spreadsheet', kind: 'local' as const, + file: new File(['sheet'], 'unknown.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), + type: 'document' as const, uploadStatus: 'waiting' as const, uploadProgress: 0, + }; + const ctx = createContext({ attachments: ref([attachment]) }); + const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx); + + const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', ''); + + expect(consumed).toBe(true); + expect(ctx.handleShippingAutoUploadFile).not.toHaveBeenCalled(); + expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled(); + expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeSpreadsheetIntentRequired'); + expect(ctx.attachments.value).toHaveLength(1); + }); + + it('routes a declared xls spreadsheet to the isolated temporary inventory path', async () => { + const attachment = { + id: 'legacy-spreadsheet', kind: 'local' as const, + file: new File(['sheet'], 'inventory.xls', { type: 'application/vnd.ms-excel' }), + type: 'document' as const, uploadStatus: 'waiting' as const, uploadProgress: 0, + }; + const ctx = createContext({ attachments: ref([attachment]), shippingAutoFlowRequested: ref(false) }); + const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx); + + const consumed = await tryHandleShippingAttachmentAutoFlow('这是库存文件,请分析', '这是库存文件,请分析', '这是库存文件,请分析'); + + expect(consumed).toBe(true); + expect(ctx.handleShippingAutoUploadFile).toHaveBeenCalledWith(attachment.file); + expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled(); + }); + it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => { const completionOrder: string[] = []; const attachment = { diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts index 3376b0f0..f53ca889 100644 --- a/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.ts @@ -1,7 +1,7 @@ /** * features/chat/shipping/useChatShippingSendHandler.ts - * 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本、列映射和附件自动流程。 - * 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。 + * 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。 + * 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。 * 逻辑:已预处理 Intake 通过普通聊天接口进入现有 Dify Chatflow;其他业务动作经 Chat Turn / handleShippingMenuAction。 */ import { @@ -9,7 +9,7 @@ import { getWorkspaceShippingTask, } from '@/features/chat/api/shipping.api'; import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping'; -import { buildShippingApplyMappingTurn, buildShippingSwitchFocusTurn } from './shippingTurnActions'; +import { buildShippingSwitchFocusTurn } from './shippingTurnActions'; import { downloadWorkspaceShippingExcelFile } from './shippingDownload'; import { isShippingDownloadExcelIntent, @@ -17,10 +17,9 @@ import { isShippingInventoryUploadIntent, isShippingManualUploadIntent, parseShippingTaskSwitchIntent, - parseShippingColumnMappingFromText, } from './shippingIntents'; import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu'; -import { classifyShippingUploadFile } from './shippingUploadPrompt'; +import { isShippingSpreadsheetFile, isTemporaryInventoryDeclaration } from './shippingUploadPrompt'; import { extractExt } from '../constants/shipping'; import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils'; import type { SendMessageLifecycleHooks } from '../composables/useChat'; @@ -52,7 +51,7 @@ export interface ShippingSendHandlerContext { agentId: number, kb: string, files: ChatUploadFileSpec[], - context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string }, + context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }, hooks?: SendMessageLifecycleHooks, ) => Promise; buildFileSpecsForSend: () => Promise; @@ -270,7 +269,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { return true; } } - if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false; if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false; if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false; if (ctx.isShippingNoticeBatchSubmitting?.()) { @@ -285,8 +283,15 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { ctx.msg.warning('当前仅支持本地附件触发自动流程'); return true; } - const kind = classifyShippingUploadFile(first.file, extractExt); - if (kind === 'inventory') { + if (isShippingSpreadsheetFile(first.file, extractExt)) { + if (!isTemporaryInventoryDeclaration(trimmed)) { + // 仅附件或自动建议时必须先澄清;有其他明确文本则交回普通对话,不把表格擅自归类。 + if (!trimmed || requestedAutoFlow) { + ctx.msg.info(ctx.t('chat.shippingNoticeSpreadsheetIntentRequired')); + return true; + } + return false; + } ctx.attachments.value = []; if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (localFiles.length > 1) { @@ -300,6 +305,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { } return true; } + if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false; if (!trimmed || requestedAutoFlow) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; @@ -355,9 +361,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (menuChoice === 'upload') { if (ctx.openShippingInventoryPicker()) return true; - } else if (menuChoice === 'paste') { - ctx.msg.info(ctx.t('chat.shippingNoticePasteHint')); - return true; } else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) { const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice]; await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice); @@ -372,34 +375,6 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true; } - if (assistantCtx.includes('schema_preview') || assistantCtx.includes('列映射') || assistantCtx.includes('字段对齐')) { - const mapping = parseShippingColumnMappingFromText(content); - if (mapping) { - const taskId = ctx.getActiveShippingTaskId(); - if (!taskId) { - ctx.msg.warning('未找到任务编号,请先上传库存文件'); - return true; - } - ctx.resolvedShippingTaskId.value = taskId; - if (typeof textOrEvent !== 'string') ctx.input.value = ''; - ctx.attachments.value = []; - const turn = buildShippingApplyMappingTurn(taskId, mapping); - await ctx.startChatTurn({ - agentId: ctx.currentAgentId.value, - inputType: 'form_submit', - displayText: `${content.trim()}\n任务编号:${taskId}`, - actionType: turn.actionType, - payload: turn.payload, - refs: turn.refs, - hooks: { - onAssistantMessageFinished: async () => { - void ctx.refreshShippingActions(); - }, - }, - }); - return true; - } - } if (isShippingManualUploadIntent(content)) { const taskId = ctx.getActiveShippingTaskId(); if (!taskId) { @@ -415,6 +390,7 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { if (isShippingInventoryUploadIntent(content, assistantCtx)) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (ctx.openShippingInventoryPicker()) return true; + return true; } if (isShippingGenerateExcelIntent(content)) { const taskId = ctx.getActiveShippingTaskId(); diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts index 6d9c6914..b3b2514e 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts @@ -14,8 +14,8 @@ import { type ShippingUploadHandlerContext, } from './useChatShippingUploadHandler'; -const { createWorkspaceShippingTask } = vi.hoisted(() => ({ - createWorkspaceShippingTask: vi.fn(), +const { uploadFileAsset } = vi.hoisted(() => ({ + uploadFileAsset: vi.fn(), })); const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({ @@ -25,8 +25,8 @@ const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({ }), })); -vi.mock('@/features/chat/api/shipping.api', () => ({ - createWorkspaceShippingTask, +vi.mock('@/shared/api/file-assets.api', () => ({ + uploadFileAsset, })); vi.mock('./shippingNoticeBatchIdempotency', () => ({ @@ -52,18 +52,18 @@ const createContext = ( shippingBatchTasks: ref([]), shippingInventorySelectionActive: ref(false), shippingInventorySelectionTaskId: ref(''), - shippingInventorySchemaPreviewCache: ref({}), getActiveShippingTaskId: () => 'SN-ACTIVE-001', startChatTurn: vi.fn(async () => true), refreshShippingActions: vi.fn(async () => undefined), msg: { warning: vi.fn() }, t: (key: string) => key, + sendTemporaryInventoryMessage: vi.fn(async () => undefined), ...overrides, }); describe('useChatShippingUploadHandler', () => { beforeEach(() => { - createWorkspaceShippingTask.mockReset(); + uploadFileAsset.mockReset(); computeNoticeFilesContentFingerprint.mockReset(); computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => { const content = await files[0]?.text(); @@ -72,6 +72,34 @@ describe('useChatShippingUploadHandler', () => { resetShippingNoticeBatchSubmitStateForTests(); }); + it('stores an explicitly declared conversation inventory Excel as a temporary asset without creating a shipping task', async () => { + uploadFileAsset.mockResolvedValue({ asset_no: 'FAS-TEMP-001' }); + const sendTemporaryInventoryMessage = vi.fn(async () => undefined); + const ctx = createContext({ sendTemporaryInventoryMessage }); + const { handleShippingAutoUploadFile } = createShippingUploadHandlers(ctx); + const file = new File(['inventory'], 'inventory.xlsx', { + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + }); + + await handleShippingAutoUploadFile(file); + + expect(uploadFileAsset).toHaveBeenCalledWith(file); + expect(sendTemporaryInventoryMessage).toHaveBeenCalledWith('FAS-TEMP-001', 'inventory.xlsx'); + }); + + it('accepts a legacy xls inventory file for the isolated temporary upload path', async () => { + uploadFileAsset.mockResolvedValue({ asset_no: 'FAS-TEMP-XLS' }); + const sendTemporaryInventoryMessage = vi.fn(async () => undefined); + const ctx = createContext({ sendTemporaryInventoryMessage }); + const { handleShippingAutoUploadFile } = createShippingUploadHandlers(ctx); + const file = new File(['legacy inventory'], 'inventory.xls', { type: 'application/vnd.ms-excel' }); + + await handleShippingAutoUploadFile(file); + + expect(uploadFileAsset).toHaveBeenCalledWith(file); + expect(sendTemporaryInventoryMessage).toHaveBeenCalledWith('FAS-TEMP-XLS', 'inventory.xls'); + }); + it('opens inventory picker for explicit taskId instead of current active task', () => { const inventoryClick = vi.fn(); const ctx = createContext({ @@ -86,6 +114,22 @@ describe('useChatShippingUploadHandler', () => { expect(inventoryClick).toHaveBeenCalledTimes(1); }); + it('uploads a task-selected inventory file through the formal task Chat Turn, not the temporary path', async () => { + const ctx = createContext({ pendingShippingUploadTaskId: ref('SN-TASK-001') }); + const { handleShippingInventorySelected } = createShippingUploadHandlers(ctx); + const file = new File(['inventory'], 'task-inventory.xls', { type: 'application/vnd.ms-excel' }); + const event = { target: { files: [file], value: 'chosen' } } as unknown as Event; + + await handleShippingInventorySelected(event); + + expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({ + actionType: 'shipping.upload_inventory', + payload: { task_no: 'SN-TASK-001' }, + files: [file], + })); + expect(ctx.sendTemporaryInventoryMessage).not.toHaveBeenCalled(); + }); + it('replaces notice on locked pending task via Chat Turn', async () => { const ctx = createContext({ pendingShippingNoticeTaskId: ref('SN-TARGET-200'), diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts index 8a3dc90b..c8e04fbf 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts @@ -1,18 +1,15 @@ /** * features/chat/shipping/useChatShippingUploadHandler.ts * 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。 - * 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。 - * 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。 + * 依赖:shipping.api、file-assets.api、shippingUploadPrompt、shipping 常量、chat.types。 + * 逻辑:发货通知建批和单票覆盖经 Chat Turn;对话上传库存文件先成为私有临时资产,再进入 Dify 受控分析分支。 */ import { computed } from 'vue'; -import { - createWorkspaceShippingTask, - type ShippingTaskSummary, -} from '@/features/chat/api/shipping.api'; +import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api'; +import { uploadFileAsset } from '@/shared/api/file-assets.api'; import { extractExt } from '../constants/shipping'; -import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions'; +import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions'; import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency'; -import { classifyShippingUploadFile } from './shippingUploadPrompt'; import type { StartChatTurnOptions } from '../types/chat-turn.types'; import type { ChatMessage } from '../types/chat.types'; import type { PendingAttachment } from '../types/shipping.types'; @@ -113,7 +110,6 @@ export interface ShippingUploadHandlerContext { shippingBatchTasks: Ref; shippingInventorySelectionActive: Ref; shippingInventorySelectionTaskId: Ref; - shippingInventorySchemaPreviewCache: Ref>; getActiveShippingTaskId: () => string; startChatTurn: (options: StartChatTurnOptions) => Promise; refreshShippingActions: () => Promise; @@ -122,12 +118,13 @@ export interface ShippingUploadHandlerContext { getParsedIntakeNos?: () => string[]; getSelectedCandidateNos?: () => string[]; clearConsumedNoticeAttachments?: () => void; + sendTemporaryInventoryMessage: (assetNo: string, fileName: string) => Promise; } /** * 创建发货通知上传处理器。 * - * 核心逻辑:识别附件属于发货通知还是库存文件,分别触发建单/建批或库存上传,并维护 task/batch 本地上下文。 + * 核心逻辑:通知附件触发建单/建批;临时库存文件只能由发送层在用户明确声明后调用,避免根据后缀误判业务类型。 * @param ctx - 上传处理上下文 * @returns 自动上传、文件选择器和建议提示相关处理函数 */ @@ -138,28 +135,17 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) }; const runInventoryUploadChatTurn = async (taskId: string, file: File) => { - const turn = buildShippingUploadInventoryTurn(taskId, file); + const normalizedTaskId = String(taskId || '').trim().toUpperCase(); const ok = await ctx.startChatTurn({ agentId: ctx.currentAgentId.value, inputType: 'upload_followup', - displayText: turn.displayText, - actionType: turn.actionType, - payload: turn.payload, - files: turn.files, - refs: turn.refs, + displayText: `上传库存文件:${file.name}`, + actionType: 'shipping.upload_inventory', + payload: { task_no: normalizedTaskId }, + files: [file], + refs: buildShippingTurnRefs(normalizedTaskId), hooks: { onAssistantMessageFinished: async (assistantMsg) => { - const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object' - ? assistantMsg.payload as { schema_preview?: unknown; task_no?: string } - : {}; - const key = String(payload.task_no || taskId || '').trim().toUpperCase(); - const preview = payload.schema_preview; - if (key && preview && typeof preview === 'object') { - ctx.shippingInventorySchemaPreviewCache.value = { - ...ctx.shippingInventorySchemaPreviewCache.value, - [key]: preview, - }; - } syncBatchContextFromTurnMessage(assistantMsg); void ctx.refreshShippingActions(); }, @@ -271,25 +257,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) } }; - const syncBatchContextFromNoticeResponse = (result: Record | null | undefined) => { - const batchNo = String( - (result?.batch_no as string | undefined) - || ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no) - || '', - ).trim(); - const focusTaskNo = String( - ((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no) - || (result?.task_id as string | undefined) - || '', - ).trim(); - const batchSummary = ((result?.data as { batch?: unknown } | undefined)?.batch) || null; - if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo; - if (focusTaskNo) ctx.resolvedShippingTaskId.value = focusTaskNo; - if (batchSummary && typeof batchSummary === 'object') { - ctx.shippingBatchSummary.value = batchSummary; - } - }; - const runReplaceNoticeChatTurn = async (taskId: string, file: File) => { const turn = buildShippingReplaceNoticeTurn(taskId, file); const ok = await ctx.startChatTurn({ @@ -377,32 +344,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) }; const handleShippingAutoUploadFile = async (file: File) => { - const kind = classifyShippingUploadFile(file, extractExt); - if (kind === 'inventory') { - let taskId = ctx.getActiveShippingTaskId(); - if (!taskId) { - const created = await createWorkspaceShippingTask({ - source_type: 'manual', - conversation_id: String(ctx.conversationId.value || '').trim() || undefined, - }); - syncBatchContextFromNoticeResponse(created as unknown as Record); - taskId = String(created.task_id || '').trim(); - if (!taskId) { - ctx.msg.warning('自动创建发货任务失败'); - return; - } - } - await uploadInventoryForTask(taskId, file); - return; - } - const pendingNoticeTaskId = String(ctx.pendingShippingNoticeTaskId.value || '').trim().toUpperCase(); - ctx.pendingShippingNoticeTaskId.value = ''; - const targetTaskId = pendingNoticeTaskId || String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase(); - if (targetTaskId) { - await handleReplaceNoticeForCurrentTask(targetTaskId, file); - return; - } - await runNoticeBatchChatTurn([file]); + // 调用方已验证用户明确声明库存;此处只创建隔离的临时资产,绝不建单或写正式库存。 + const asset = await uploadFileAsset(file); + await ctx.sendTemporaryInventoryMessage(asset.asset_no, file.name); }; const handleShippingAutoUploadNoticeBatch = async (files: File[]) => { @@ -476,8 +420,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) | Extract | undefined; if (!first) return ''; - const kind = classifyShippingUploadFile(first.file, extractExt); - if (kind === 'inventory') return ctx.t('chat.shippingNoticePrompt.notice.autoInventoryAction'); + if (['xlsx', 'xls', 'csv'].includes(extractExt(first.file.name || '').toLowerCase())) { + return ctx.t('chat.shippingNoticePrompt.notice.autoSpreadsheetAction'); + } return ctx.t('chat.shippingNoticePrompt.notice.autoNoticeAction'); }); diff --git a/frontend/src/features/chat/shipping/useShippingNoticeIntakes.spec.ts b/frontend/src/features/chat/shipping/useShippingNoticeIntakes.spec.ts index f1d501cd..ef1ce35f 100644 --- a/frontend/src/features/chat/shipping/useShippingNoticeIntakes.spec.ts +++ b/frontend/src/features/chat/shipping/useShippingNoticeIntakes.spec.ts @@ -6,11 +6,21 @@ */ import { describe, expect, it } from 'vitest'; import { + isOrderExtractionEligibleIntake, resolveShippingOrderExtractionStatus, + shouldRestoreShippingNoticeIntake, shouldPollShippingNoticeIntake, } from './useShippingNoticeIntakes'; describe('shipping notice order extraction state', () => { + it('does not resubmit consumed intakes for a new order extraction turn', () => { + expect(isOrderExtractionEligibleIntake({ + intakeNo: 'SNI-CONSUMED', + parseStatus: 'consumed', + parseSummary: undefined, + })).toBe(false); + }); + it('keeps polling after preprocessing is parsed while order extraction is active', () => { expect(shouldPollShippingNoticeIntake({ parseStatus: 'parsed', @@ -32,4 +42,14 @@ describe('shipping notice order extraction state', () => { expect(resolveShippingOrderExtractionStatus('extracting', 'completed')).toBe('completed'); expect(resolveShippingOrderExtractionStatus(undefined, 'not_started')).toBe('not_started'); }); + + it('restores only in-progress and retryable parsing attachments into the input area', () => { + expect(shouldRestoreShippingNoticeIntake('queued')).toBe(true); + expect(shouldRestoreShippingNoticeIntake('parsing')).toBe(true); + expect(shouldRestoreShippingNoticeIntake('parse_failed')).toBe(true); + + // Parsed files are already persisted in the user message bubble. + expect(shouldRestoreShippingNoticeIntake('parsed')).toBe(false); + expect(shouldRestoreShippingNoticeIntake('consumed')).toBe(false); + }); }); diff --git a/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts b/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts index e0025b34..e022b86c 100644 --- a/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts +++ b/frontend/src/features/chat/shipping/useShippingNoticeIntakes.ts @@ -3,7 +3,7 @@ * 用途:发货通知选择即上传、创建 intake 与批量状态轮询编排。 * 依赖:file-assets.api、shipping.api、shipping.types、shippingNoticeAttachmentIntegrity。 * 逻辑:useChatShipping / useChatAttachments 在货代 Agent 下委托本 composable 管理预解析附件; - * 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐)。 + * 完整性判定委托 shippingNoticeAttachmentIntegrity(与后端契约对齐);会话刷新仅恢复未提交的处理中或解析失败附件。 */ import { computed, onBeforeUnmount, ref, type Ref } from 'vue'; import { uploadFileAsset } from '@/shared/api/file-assets.api'; @@ -34,6 +34,18 @@ const TERMINAL_PARSE = new Set(['parsed', 'failed', 'parse_failed', 'consumed', const ACTIVE_PARSE = new Set(['waiting', 'queued', 'parsing', 'created']); const ACTIVE_ORDER_EXTRACTION = new Set(['extracting']); +/** + * 判断服务端 Intake 是否应恢复到输入栏。 + * AI 触发时机:无;页面刷新或重新打开会话时调用。 + * 已解析文件已作为用户消息附件固化在对话气泡中,不能再次显示在输入栏;仅恢复仍在处理中的文件和可手动重试的解析失败文件。 + * @param parseStatus - 服务端返回的预解析状态 + * @returns 是否恢复为待发送附件卡片 + */ +export function shouldRestoreShippingNoticeIntake(parseStatus: string | null | undefined): boolean { + const status = String(parseStatus || '').trim().toLowerCase(); + return ACTIVE_PARSE.has(status) || status === 'parse_failed'; +} + /** 判断 Intake 是否仍需轮询上传预处理或订单抽取状态。 */ export function shouldPollShippingNoticeIntake( item: Pick, @@ -42,6 +54,15 @@ export function shouldPollShippingNoticeIntake( || ACTIVE_ORDER_EXTRACTION.has(String(item.orderExtractionStatus || '').trim().toLowerCase()); } +/** 判断附件是否仍可作为新一轮完整订单抽取的输入。 */ +export function isOrderExtractionEligibleIntake( + item: Pick, +): boolean { + return item.parseStatus === 'parsed' + && Boolean(item.intakeNo) + && !isShippingNoticeAttachmentParseIncomplete(item.parseSummary); +} + /** 保留刚点击发送的本地 extracting,直到服务端进入真实抽取状态或返回终态。 */ export function resolveShippingOrderExtractionStatus(localStatus?: string, remoteStatus?: string | null): string | undefined { const local = String(localStatus || '').trim().toLowerCase(); @@ -135,6 +156,7 @@ function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNo fieldAdjudication: remote.field_adjudication && typeof remote.field_adjudication === 'object' ? remote.field_adjudication : null, + customerMatches: Array.isArray(remote.customer_matches) ? remote.customer_matches : [], businessSummary: remote.business_summary || {}, duplicate, duplicateResolution: remote.duplicate_resolution @@ -376,12 +398,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption const getParsedIntakeNos = () => noticeAttachments.value - .filter( - (item) => - item.parseStatus === 'parsed' - && item.intakeNo - && !isShippingNoticeAttachmentParseIncomplete(item.parseSummary), - ) + .filter(isOrderExtractionEligibleIntake) .map((item) => String(item.intakeNo)); /** 点击发送后立即展示订单识别阶段,并启动 Intake 状态轮询。 */ @@ -420,8 +437,7 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption const restoreForConversation = async (conversationId?: string | null) => { const { items } = await listActiveShippingNoticeIntakes(conversationId); const restored: ShippingNoticePendingAttachment[] = items - .filter((item) => !TERMINAL_PARSE.has(String(item.parse_status || '').toLowerCase()) || item.parse_status === 'parsed') - .filter((item) => item.parse_status !== 'consumed') + .filter((item) => shouldRestoreShippingNoticeIntake(item.parse_status)) .map((item) => ({ id: `restored_${item.intake_no}`, kind: 'shipping_notice' as const, diff --git a/frontend/src/features/chat/types/chat.types.ts b/frontend/src/features/chat/types/chat.types.ts index 7d5bdff2..ca69f641 100644 --- a/frontend/src/features/chat/types/chat.types.ts +++ b/frontend/src/features/chat/types/chat.types.ts @@ -68,7 +68,7 @@ export interface ChatMessage { content: string; /** 用户提交时固化的附件展示快照;助手消息不使用此字段。 */ attachments?: ChatMessageAttachment[]; - type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result'; + type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result'; retriever_resources?: RetrieverResource[]; attribution_parts?: string[]; chat_log_id?: number; diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts index 7a7d96c0..e56a3a14 100644 --- a/frontend/src/features/chat/types/shipping.api.types.ts +++ b/frontend/src/features/chat/types/shipping.api.types.ts @@ -21,7 +21,6 @@ export type InventorySourceMethod = export interface ShippingInventorySourceCandidate { source_code: string; display_name?: string | null; - site_id?: string | null; warehouse_id?: string | null; connector_type?: string | null; match_score?: number | null; @@ -100,7 +99,6 @@ export interface ShippingTaskSummary { warehouse_hint?: string | null; inventory_source_code?: string | null; inventory_connector_type?: string | null; - inventory_site_id?: string | null; inventory_warehouse_id?: string | null; inventory_source_status?: InventorySourceStatus | null; inventory_source_method?: InventorySourceMethod | null; @@ -241,6 +239,32 @@ export interface ShippingFieldAdjudication { conflicts?: Array>; } +export interface ShippingOrderCustomerMatchCandidate { + customer_id: number; + standard_name: string; + short_code: string; + site_id?: number | null; + site_name?: string | null; + site_code?: string | null; + matched_by?: string[]; +} + +export interface ShippingOrderCustomerMatch { + id: number; + extraction_id: number; + role: 'bill_to' | 'ship_to'; + raw_name?: string | null; + status: 'unmatched' | 'unique_candidate' | 'ambiguous' | 'confirmed' | string; + customer_id?: number | null; + site_id?: number | null; + source_system?: string | null; + external_code?: string | null; + standard_name?: string | null; + short_code?: string | null; + candidates?: ShippingOrderCustomerMatchCandidate[]; + resolution_method?: string | null; +} + export interface ShippingFieldConflict { id: number; task_id: number; @@ -507,6 +531,7 @@ export interface ShippingNoticeCandidateResponse { field_confidence?: Record; evidence?: ShippingFieldEvidenceItem[]; field_adjudication?: ShippingFieldAdjudication | null; + customer_matches?: ShippingOrderCustomerMatch[]; business_summary?: Record | null; duplicate?: ShippingDuplicateResult | null; duplicate_resolution?: { diff --git a/frontend/src/features/chat/types/shipping.types.ts b/frontend/src/features/chat/types/shipping.types.ts index 2abab821..9873bb05 100644 --- a/frontend/src/features/chat/types/shipping.types.ts +++ b/frontend/src/features/chat/types/shipping.types.ts @@ -5,11 +5,11 @@ * 逻辑:附件 composable、shipping/* composable 与 Chat 消息组件统一引用本文件类型。 */ -import type { ShippingFieldAdjudication } from './shipping.api.types'; +import type { ShippingFieldAdjudication, ShippingOrderCustomerMatch } from './shipping.api.types'; export type ShippingActionVariant = 'primary' | 'secondary' | 'danger'; -export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject'; +export type ShippingMenuAction = 'upload' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject'; export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom'; @@ -79,6 +79,7 @@ export interface ShippingNoticeCandidate { fieldConfidence?: Record; evidence?: Array>; fieldAdjudication?: ShippingFieldAdjudication | null; + customerMatches?: ShippingOrderCustomerMatch[]; businessSummary: Record; duplicate?: ShippingDuplicateResult; duplicateResolution?: ShippingDuplicateResolution; @@ -180,23 +181,6 @@ export type ChatUploadFileSpec = | { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string } | { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string }; -/** 库存 Excel 表头预览(后端 schema_preview 字段) */ -export interface ShippingSchemaPreview { - header_row_index?: number; - headers?: string[]; - sample_rows?: unknown[][]; - suggested_mapping?: Record; -} - -/** 库存列映射表单消息 payload(type=shipping-inventory-mapping) */ -export interface ShippingInventoryMappingFormPayload { - taskId: string; - schema_preview: ShippingSchemaPreview; - order: { line_count: number; part_numbers: string[] }; - form: { part_number: string; available_qty: string; reservation_id: string }; - applying?: boolean; -} - export interface ShippingParseReviewPayload { taskId: string; checkpoint: string; diff --git a/frontend/src/features/chat/utils/attachmentCard.utils.spec.ts b/frontend/src/features/chat/utils/attachmentCard.utils.spec.ts index bbe1d464..12c3d390 100644 --- a/frontend/src/features/chat/utils/attachmentCard.utils.spec.ts +++ b/frontend/src/features/chat/utils/attachmentCard.utils.spec.ts @@ -70,7 +70,9 @@ describe('attachment card utils', () => { }); it('preserves shipping parsing, failure and duplicate attention states', () => { - expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' })).state).toBe('processing'); + expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'parsing' }))).toEqual({ + state: 'processing', labelKey: 'chat.attachment.parsing', + }); expect(getAttachmentCardStatus(shippingAttachment({ parseStatus: 'failed' }))).toEqual({ state: 'failed', labelKey: 'chat.attachment.parseFailed', }); @@ -83,7 +85,9 @@ describe('attachment card utils', () => { allowedActions: [], }, })).state).toBe('attention'); - expect(getAttachmentCardStatus(shippingAttachment()).state).toBe('ready'); + expect(getAttachmentCardStatus(shippingAttachment())).toEqual({ + state: 'ready', labelKey: 'chat.attachment.parseSucceeded', + }); }); it('shows the order extraction lifecycle separately from attachment parsing', () => { diff --git a/frontend/src/features/chat/utils/attachmentCard.utils.ts b/frontend/src/features/chat/utils/attachmentCard.utils.ts index 660ee597..4ff08a3d 100644 --- a/frontend/src/features/chat/utils/attachmentCard.utils.ts +++ b/frontend/src/features/chat/utils/attachmentCard.utils.ts @@ -67,7 +67,7 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme if (attachment.uploadStatus === 'uploading') return { state: 'uploading', labelKey: 'chat.attachment.uploading' }; if (attachment.uploadStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.uploadFailed' }; if (attachment.parseStatus === 'queued' || attachment.parseStatus === 'parsing') { - return { state: 'processing', labelKey: 'chat.attachment.processing' }; + return { state: 'processing', labelKey: 'chat.attachment.parsing' }; } if (attachment.parseStatus === 'failed') return { state: 'failed', labelKey: 'chat.attachment.parseFailed' }; const extractionStatus = String(attachment.orderExtractionStatus || '').trim().toLowerCase(); @@ -92,7 +92,7 @@ export function getAttachmentCardStatus(attachment: PendingAttachment): Attachme } } if (attachment.parseStatus === 'parsed' || attachment.parseStatus === 'consumed') { - return { state: 'ready', labelKey: 'chat.attachment.ready' }; + return { state: 'ready', labelKey: 'chat.attachment.parseSucceeded' }; } return { state: 'pending', labelKey: 'chat.attachment.pending' }; } @@ -129,9 +129,7 @@ function getSnapshotAttachmentName(attachment: PendingAttachment): string { return basename.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 255) || 'attachment'; } -/** - * 鐢熸垚鍙寔涔呭寲鐨勯檮浠跺揩鐓?ID锛屼紭鍏堝鐢ㄥ緟鍙戦€侀檮浠剁殑鏈湴鏍囪瘑锛岄伩鍏嶅紩鍏?File 鎴栧唴閮ㄨ祫浜ф寚閽堛€? - */ +/** 生成可持久化的附件快照 ID,避免引入 File 或内部资产指针。 */ function getSnapshotAttachmentId(attachment: PendingAttachment, index: number): string { const candidate = String(attachment.id || '') .replace(/[\u0000-\u001f\u007f]/g, '') diff --git a/frontend/src/features/shipping-notice/api/customer-master.api.ts b/frontend/src/features/shipping-notice/api/customer-master.api.ts new file mode 100644 index 00000000..cb32b0ed --- /dev/null +++ b/frontend/src/features/shipping-notice/api/customer-master.api.ts @@ -0,0 +1,180 @@ +/** + * features/shipping-notice/api/customer-master.api.ts + * 用途:货代客户主数据的管理 API,归属货代发货业务域。 + * 依赖:requestJson、认证请求头、客户主数据类型。 + * 逻辑:页面位于货代发货工作台,但所有写操作仍调用管理员受保护的后端契约。 + */ + +import { getAuthHeaders } from '@/shared/utils/auth'; +import { BusinessError, requestJson, resolveLocalizedErrorMessage } from '@/shared/api/client'; +import type { + ShippingCustomerIdentifier, + ShippingCustomerImportBatch, + ShippingCustomerLifecycleImpact, + ShippingCustomerLifecycleTimeline, + DeleteShippingCustomerRequest, + DeleteShippingCustomerResult, + MergeShippingCustomerRequest, + MergeShippingCustomerResult, + ShippingCustomerMergeImpact, + ShippingCustomerPage, + ShippingCustomerRow, + ShippingCustomerShadowItem, + ShippingCustomerShadowReport, + ShippingIdentifierFormState, +} from '../types/customer-master.types'; + +const auth = () => ({ headers: getAuthHeaders() }); +const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); + +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 getShippingCustomerLifecycleImpact = (id: number) => + requestJson(`/api/admin/shipping-customers/${id}/lifecycle-impact`, auth()); + +/** 查询客户创建、变更、证据及归并的不可变治理时间线。 */ +export const getShippingCustomerLifecycleTimeline = (id: number) => + requestJson(`/api/admin/shipping-customers/${id}/lifecycle-timeline`, auth()); + +/** 受控删除误建客户;服务端在提交时重新检查全部生命周期阻断引用。 */ +export const deleteShippingCustomer = (id: number, payload: DeleteShippingCustomerRequest) => + requestJson(`/api/admin/shipping-customers/${id}`, { + method: 'DELETE', ...jsonAuth(), body: JSON.stringify(payload), + }); + +/** 预览客户归并时保留的历史引用和可迁移的未来识别配置。 */ +export const getShippingCustomerMergeImpact = (sourceId: number, targetId: number) => + requestJson( + `/api/admin/shipping-customers/${sourceId}/merge-impact?target_customer_id=${targetId}`, + auth(), + ); + +/** 归并重复客户;后端锁定双方并保留历史业务与业务号快照。 */ +export const mergeShippingCustomer = (sourceId: number, payload: MergeShippingCustomerRequest) => + requestJson(`/api/admin/shipping-customers/${sourceId}/merge`, { + method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), + }); + +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, reason: string) => + requestJson(`/api/admin/shipping-customers/${id}/deactivate`, { + method: 'POST', ...jsonAuth(), body: JSON.stringify({ reason }), + }); + +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 createShippingCustomerExternalRef = ( + customerId: number, + payload: { source_system: string; customer_code: string }, +) => requestJson(`/api/admin/shipping-customers/${customerId}/external-refs`, { + method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), +}); + +export const createShippingCustomerSite = ( + customerId: number, + payload: { site_name: string; site_code: string; address?: string; city?: string; country?: string; remark?: string }, +) => requestJson(`/api/admin/shipping-customers/${customerId}/sites`, { + method: 'POST', ...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(), + }); + +/** 下载需要管理员权限的二进制文件,并保持统一 BusinessError 契约。 */ +const downloadCustomerMasterFile = 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); +}; + +export const downloadShippingCustomerImportTemplate = () => + downloadCustomerMasterFile('/api/admin/shipping-customers/import-template', 'shipping_customer_import_template.xlsx'); + +export const downloadShippingCustomerReconciliation = (batchId: number, batchNo: string) => + downloadCustomerMasterFile( + `/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 }) }, + ); diff --git a/frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue b/frontend/src/features/shipping-notice/customers/ShippingCustomersPage.vue similarity index 76% rename from frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue rename to frontend/src/features/shipping-notice/customers/ShippingCustomersPage.vue index 6bb138d4..52618291 100644 --- a/frontend/src/features/admin/modules/shipping-customers/ShippingCustomersPage.vue +++ b/frontend/src/features/shipping-notice/customers/ShippingCustomersPage.vue @@ -1,5 +1,5 @@ + + +