diff --git a/.env.dev b/.env.dev index f8220b2f..dfd12de8 100644 --- a/.env.dev +++ b/.env.dev @@ -1,4 +1,4 @@ -# ============================================================================= +# ============================================================================= # Development — docker compose / deploy_compose.sh dev # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments @@ -104,8 +104,8 @@ SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true # 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决 SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true diff --git a/.env.prod b/.env.prod index 45794208..26fea92f 100644 --- a/.env.prod +++ b/.env.prod @@ -1,4 +1,4 @@ -# ============================================================================= +# ============================================================================= # Production — docker compose env_file + deploy_compose.sh prod # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments @@ -118,8 +118,8 @@ SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true # 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享) -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true # 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥) SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 diff --git a/.env.test b/.env.test index 7b3805c7..155991c7 100644 --- a/.env.test +++ b/.env.test @@ -1,4 +1,4 @@ -# ============================================================================= +# ============================================================================= # Test — docker compose / deploy_compose.sh test # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments @@ -117,8 +117,8 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true diff --git a/backend/app/__init__.py b/backend/app/__init__.py index b30deefb..2967773d 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -80,8 +80,12 @@ def create_app(config_name='default'): _transfer_capabilities.register_transfer_capabilities() # onhand/inbound RPA 回调 sink 注册(幂等):/api/freight-rpa/onhand-*、/api/freight-rpa/ - # inbound-* 端点经 callback_sinks.dispatch_sink 分发到业务处理器;未注册的 kind 仍显式 - # 404(FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。 + # inbound-* 端点经 callback_sinks.dispatch_sink 分发到业务处理器;文件/报表事实类 + # 回调(inbound-batch-ready / onhand 归档终态 commit 后)经 reports.dispatch. + # dispatch_report_fact 分发到 register_report_handler 注册的处理函数 + # (Task 7:inbound→in_transit_transfer.handle_inbound_report、 + # onhand→shipping_notice.handle_onhand_report,均由 rpa_sinks 两个注册函数内注册); + # 未注册的 kind 仍显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。 from app.services.shipping_notice.rpa_sinks import register_inbound_sinks, register_onhand_sinks register_onhand_sinks() diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index fb29c652..752c03a7 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -23,7 +23,7 @@ import app.api.admin.shipping_order_extraction # noqa: F401 import app.api.admin.announcements # noqa: F401 import app.api.admin.shipping_customers # noqa: F401 import app.api.admin.shipping_identity_rules # noqa: F401 -import app.api.admin.shipping_inventory # noqa: F401 +import app.api.admin.shipping_notice_admin # noqa: F401 import app.api.admin_freight_rpa # noqa: F401 import app.api.admin.shipping_order_schema # noqa: F401 import app.api.admin.shipping_field_assets # noqa: F401 diff --git a/backend/app/api/admin/shipping_inventory.py b/backend/app/api/admin/shipping_inventory.py deleted file mode 100644 index 2bf6437f..00000000 --- a/backend/app/api/admin/shipping_inventory.py +++ /dev/null @@ -1,589 +0,0 @@ -""" -api/admin/shipping_inventory.py - -用途:提供库存源、路由规则及外部系统映射的管理 API。 -依赖:admin blueprint、require_admin、shipping_inventory_service。 -逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成; - RPA Profile CRUD 已迁至 api/admin_freight_rpa.py(/api/admin/freight-rpa/rpa-profiles)。 -""" - -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//clone', methods=['POST']) -@require_admin -def clone_shipping_excel_template(template_id: int): - """复制已有模板为使用新编码的独立 v1 草稿。""" - return _ok(excel_template.clone_as_new_template( - template_id, request.get_json(silent=True) or {}, 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/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//receipt-report-config', methods=['GET']) -@require_admin -def get_shipping_receipt_report_config(source_id: int): - """读取站点独立收料报表配置;库存配置和收料配置永不混写。""" - return _ok(shipping_inventory_service.get_receipt_report_config(source_id)) - - -@admin_bp.route('/shipping-notice/sources//receipt-report-config', methods=['PUT']) -@require_admin -def save_shipping_receipt_report_config(source_id: int): - """保存独立收料报表配置,并由服务记录可追溯的前后快照审计。""" - return _ok(shipping_inventory_service.save_receipt_report_config( - source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), - )) - - -@admin_bp.route('/shipping-notice/sources//bind-parsing-profile', methods=['POST']) -@require_admin -def bind_shipping_inventory_source_parsing_profile(source_id: int): - """直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。""" - payload = request.get_json(silent=True) or {} - rows = shipping_inventory_service.bind_source_parsing_profile( - [source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(), - reason=str(payload.get('reason') or ''), operation='direct', - ) - return _ok(rows[0]) - - -@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST']) -@require_admin -def bulk_bind_shipping_inventory_source_parsing_profile(): - """原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。""" - payload = request.get_json(silent=True) or {} - source_ids = payload.get('source_ids') - if not isinstance(source_ids, list): - source_ids = [] - return _ok(shipping_inventory_service.bind_source_parsing_profile( - source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(), - reason=str(payload.get('reason') or ''), operation='bulk', - )) - - -@admin_bp.route('/shipping-notice/sources//parsing-binding-audits', methods=['GET']) -@require_admin -def list_shipping_inventory_source_parsing_binding_audits(source_id: int): - """返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。""" - return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id)) - - -@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/source-validation-batches', methods=['POST']) -@require_admin -def start_shipping_inventory_validation_batch(): - """为多个停用且已绑定发布解析方案的站点发起批量测试验证。""" - from app.services.shipping_notice import inventory_configuration_test - - payload = request.get_json(silent=True) or {} - return _ok(inventory_configuration_test.start_batch_test_export( - payload.get('source_ids') or [], actor_id=_actor_id(), - ), status=202) - - -@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET']) -@require_admin -def get_latest_active_shipping_inventory_validation_batch(): - """恢复最近未结束的批量验证,避免页面刷新后丢失进度。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_latest_active_validation_batch()) - - -@admin_bp.route('/shipping-notice/source-validation-batches/', methods=['GET']) -@require_admin -def get_shipping_inventory_validation_batch(batch_id: int): - """读取批量验证汇总进度及每个站点的独立测试结果。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_validation_batch(batch_id)) - - -@admin_bp.route('/shipping-notice/source-validation-batches//retry-failed', methods=['POST']) -@require_admin -def retry_failed_shipping_inventory_validation_batch(batch_id: int): - """只重试批次中失败或配置已过期的站点,不重复导出成功项。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202) - - -@admin_bp.route('/shipping-notice/sources//test-export/latest', methods=['GET']) -@require_admin -def get_latest_shipping_inventory_configuration_test(source_id: int): - """读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_latest_test_run(source_id)) - - -@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 - return _ok({ - 'order_fields': order_fields, - '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, - ) - 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, - '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/movement-fields', methods=['GET']) -@require_admin -def list_movement_fields(): - """标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。""" - from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS - - return _ok([ - { - 'code': field.code, 'value_type': str(field.value_type), - 'required': bool(field.required), 'is_identity': bool(field.is_identity), - } - for field in MOVEMENT_FIELDS - ]) - - -@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//sample-replacement-preview/', methods=['POST']) -@require_admin -def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int): - """比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。""" - return _ok(inventory_structure_analysis.preview_profile_sample_replacement( - profile_id, analysis_id, request.get_json(silent=True) or {}, - )) - - -@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_notice_admin.py b/backend/app/api/admin/shipping_notice_admin.py new file mode 100644 index 00000000..2904d458 --- /dev/null +++ b/backend/app/api/admin/shipping_notice_admin.py @@ -0,0 +1,141 @@ +""" +api/admin/shipping_notice_admin.py + +用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话、异动字段目录。 +依赖:admin blueprint、require_admin、excel_template、异动字段契约、临时会话服务。 +逻辑:货代 RPA 管理路由(sources / onhand / inbound-report-config / rpa-profiles)已迁至 + api/admin_freight_rpa.py 的 /api/admin/freight-rpa/;本文件不再注册那些路径。 + 临时会话只改路径段 temporary-onhand-sessions,仍挂在 /shipping-notice/。 +""" + +from __future__ import annotations + +import json + +from flask import g, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.response import ok +from app.services.shipping_notice import excel_template + + +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//clone', methods=['POST']) +@require_admin +def clone_shipping_excel_template(template_id: int): + """复制已有模板为使用新编码的独立 v1 草稿。""" + return _ok(excel_template.clone_as_new_template( + template_id, request.get_json(silent=True) or {}, 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/movement-fields', methods=['GET']) +@require_admin +def list_movement_fields(): + """标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。""" + from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS + + return _ok([ + { + 'code': field.code, 'value_type': str(field.value_type), + 'required': bool(field.required), 'is_identity': bool(field.is_identity), + } + for field in MOVEMENT_FIELDS + ]) + + +@admin_bp.route('/shipping-notice/temporary-onhand-sessions', methods=['GET']) +@require_admin +def list_confirmed_shipping_temporary_inventory_sessions(): + """列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。""" + from app.services.shipping_notice import onhand_temporary_session + + return _ok(onhand_temporary_session.list_confirmed_temporary_inventory_sessions()) + + +@admin_bp.route('/shipping-notice/temporary-onhand-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 onhand_temporary_session + + return _ok(onhand_temporary_session.create_parsing_profile_draft_from_temporary_session( + session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) diff --git a/backend/app/api/admin_freight_rpa.py b/backend/app/api/admin_freight_rpa.py index c1a3b1da..e209f06b 100644 --- a/backend/app/api/admin_freight_rpa.py +++ b/backend/app/api/admin_freight_rpa.py @@ -1,21 +1,26 @@ """ api/admin_freight_rpa.py -用途:货代 RPA 凭据(RPA Profile)管理 API——批次 R 自 /api/admin/shipping-notice/rpa-profiles - 迁移至 /api/admin/freight-rpa/rpa-profiles(批次 S 再统一 onhand/inbound 子域命名空间)。 -依赖:admin blueprint、require_admin、shipping_inventory_service(服务层留原地,仅路由搬家)。 -逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成; - 与 admin/shipping_inventory.py 的 sources/receipt-report-config 路由解耦(批次 S 再迁)。 +用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、入站报表配置、RPA Profile)。 +依赖:admin blueprint、require_admin、shipping_onhand_admin_service、onhand 解析/字段/结构分析服务、订单 Schema。 +逻辑:路由只做鉴权与 JSON 参数;业务校验与事务留在服务层。 + rpa-profiles 与本批迁入的 sources/onhand 路由同文件注册,不保留 /shipping-notice/ 双路由。 + Excel 模板、temporary-onhand-sessions、movement-fields 仍在 admin/shipping_notice_admin.py。 """ from __future__ import annotations -from flask import g, request +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.admin import shipping_onhand_admin_service +from app.services.shipping_notice import onhand_field_catalog +from app.services.shipping_notice import onhand_parsing_profile +from app.services.shipping_notice import onhand_structure_analysis +from app.services.shipping_notice.order_schema import service as order_schema_service def _actor_id() -> int | None: @@ -32,26 +37,469 @@ def _ok(data, *, status: int = 200): @require_admin def list_shipping_rpa_profiles(): """列出脱敏后的 RPA Profile 配置。""" - return _ok(shipping_inventory_service.list_profiles()) + return _ok(shipping_onhand_admin_service.list_profiles()) @admin_bp.route('/freight-rpa/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) + return _ok(shipping_onhand_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) @admin_bp.route('/freight-rpa/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)) + return _ok(shipping_onhand_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id)) @admin_bp.route('/freight-rpa/rpa-profiles/', methods=['DELETE']) @require_admin def delete_shipping_rpa_profile(profile_id: int): """删除没有库存源引用的错误连接配置。""" - shipping_inventory_service.delete_profile(profile_id) + shipping_onhand_admin_service.delete_profile(profile_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/sources', methods=['GET']) +@require_admin +def list_shipping_inventory_sources(): + """列出库存业务来源。""" + return _ok(shipping_onhand_admin_service.list_sources()) + + +@admin_bp.route('/freight-rpa/sources', methods=['POST']) +@require_admin +def create_shipping_inventory_source(): + """保存停用的库存站点基础配置;正式启用由独立接口控制。""" + return _ok(shipping_onhand_admin_service.save_source( + request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False, + ), status=201) + + +@admin_bp.route('/freight-rpa/sources/', methods=['PUT']) +@require_admin +def update_shipping_inventory_source(source_id: int): + """更新库存站点业务配置;不能借由普通保存绕过启用门禁。""" + return _ok(shipping_onhand_admin_service.save_source( + request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id, + allow_enable_transition=False, + )) + + +@admin_bp.route('/freight-rpa/sources//inbound-report-config', methods=['GET']) +@require_admin +def get_shipping_inbound_report_config(source_id: int): + """读取站点独立收料报表配置;库存配置和收料配置永不混写。""" + return _ok(shipping_onhand_admin_service.get_receipt_report_config(source_id)) + + +@admin_bp.route('/freight-rpa/sources//inbound-report-config', methods=['PUT']) +@require_admin +def save_shipping_inbound_report_config(source_id: int): + """保存独立收料报表配置,并由服务记录可追溯的前后快照审计。""" + return _ok(shipping_onhand_admin_service.save_receipt_report_config( + source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + )) + + +@admin_bp.route('/freight-rpa/sources//bind-parsing-profile', methods=['POST']) +@require_admin +def bind_shipping_inventory_source_parsing_profile(source_id: int): + """直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。""" + payload = request.get_json(silent=True) or {} + rows = shipping_onhand_admin_service.bind_source_parsing_profile( + [source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(), + reason=str(payload.get('reason') or ''), operation='direct', + ) + return _ok(rows[0]) + + +@admin_bp.route('/freight-rpa/sources/bulk-bind-parsing-profile', methods=['POST']) +@require_admin +def bulk_bind_shipping_inventory_source_parsing_profile(): + """原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。""" + payload = request.get_json(silent=True) or {} + source_ids = payload.get('source_ids') + if not isinstance(source_ids, list): + source_ids = [] + return _ok(shipping_onhand_admin_service.bind_source_parsing_profile( + source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(), + reason=str(payload.get('reason') or ''), operation='bulk', + )) + + +@admin_bp.route('/freight-rpa/sources//parsing-binding-audits', methods=['GET']) +@require_admin +def list_shipping_inventory_source_parsing_binding_audits(source_id: int): + """返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。""" + return _ok(shipping_onhand_admin_service.get_source_parsing_binding_audits(source_id)) + + +@admin_bp.route('/freight-rpa/sources//activate', methods=['POST']) +@require_admin +def activate_shipping_inventory_source(source_id: int): + """仅在库存站点完成测试与必需绑定后启用正式运行。""" + return _ok(shipping_onhand_admin_service.activate_source(source_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/sources//deactivate', methods=['POST']) +@require_admin +def deactivate_shipping_inventory_source(source_id: int): + """停用库存站点而不删除已有配置和运行审计。""" + return _ok(shipping_onhand_admin_service.deactivate_source(source_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/sources/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_source(source_id: int): + """删除无运行/路由引用的错误库存源。""" + shipping_onhand_admin_service.delete_source(source_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/sources//test-export', methods=['POST']) +@require_admin +def start_shipping_inventory_configuration_test(source_id: int): + """为停用库存站点发起异步测试导出,不产生生产库存快照。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches', methods=['POST']) +@require_admin +def start_shipping_inventory_validation_batch(): + """为多个停用且已绑定发布解析方案的站点发起批量测试验证。""" + from app.services.shipping_notice import onhand_configuration_test + + payload = request.get_json(silent=True) or {} + return _ok(onhand_configuration_test.start_batch_test_export( + payload.get('source_ids') or [], actor_id=_actor_id(), + ), status=202) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches/latest-active', methods=['GET']) +@require_admin +def get_latest_active_shipping_inventory_validation_batch(): + """恢复最近未结束的批量验证,避免页面刷新后丢失进度。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_latest_active_validation_batch()) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches/', methods=['GET']) +@require_admin +def get_shipping_inventory_validation_batch(batch_id: int): + """读取批量验证汇总进度及每个站点的独立测试结果。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_validation_batch(batch_id)) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches//retry-failed', methods=['POST']) +@require_admin +def retry_failed_shipping_inventory_validation_batch(batch_id: int): + """只重试批次中失败或配置已过期的站点,不重复导出成功项。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202) + + +@admin_bp.route('/freight-rpa/sources//test-export/latest', methods=['GET']) +@require_admin +def get_latest_shipping_inventory_configuration_test(source_id: int): + """读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_latest_test_run(source_id)) + + +@admin_bp.route('/freight-rpa/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 onhand_configuration_test + + return _ok(onhand_configuration_test.get_test_run(source_id, run_no)) + + +@admin_bp.route('/freight-rpa/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 onhand_configuration_test + + payload = request.get_json(silent=True) or {} + return _ok(onhand_configuration_test.confirm_test_profile( + source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(), + )) + + +@admin_bp.route('/freight-rpa/onhand/snapshots', methods=['GET']) +@require_admin +def list_shipping_inventory_snapshots(): + """列出库存快照的管理端只读记录。""" + return _ok(shipping_onhand_admin_service.list_snapshots()) + + +@admin_bp.route('/freight-rpa/onhand/snapshots//download', methods=['GET']) +@require_admin +def download_shipping_inventory_snapshot(snapshot_id: int): + """下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。""" + path, filename = shipping_onhand_admin_service.get_snapshot_download(snapshot_id) + return send_file(path, as_attachment=True, download_name=filename) + + +@admin_bp.route('/freight-rpa/onhand/export-records', methods=['GET']) +@require_admin +def list_shipping_inventory_export_records(): + """列出 RPA 导出结果;失败后应修复配置并重新创建运行。""" + return _ok(shipping_onhand_admin_service.list_export_records()) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['GET']) +@require_admin +def list_shipping_inventory_rules(): + """列出库存源路由规则及条件。""" + return _ok(shipping_onhand_admin_service.list_rules()) + + +@admin_bp.route('/freight-rpa/onhand/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 + return _ok({ + 'order_fields': order_fields, + 'order_schema_published': published, + }) + + +@admin_bp.route('/freight-rpa/onhand/fields', methods=['GET']) +@require_admin +def list_shipping_inventory_fields(): + """列出库存统一业务字段;管理工作区可查看已停用字段。""" + return _ok(onhand_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true')) + + +@admin_bp.route('/freight-rpa/onhand/fields', methods=['POST']) +@require_admin +def create_shipping_inventory_field(): + """创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。""" + return _ok(onhand_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/fields/', methods=['PUT']) +@require_admin +def update_shipping_inventory_field(field_id: int): + """更新库存业务字段的名称、说明、格式和展示顺序。""" + return _ok(onhand_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/fields//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_field(field_id: int): + """停用无引用的扩展库存字段,核心字段始终由服务层保护。""" + return _ok(onhand_field_catalog.retire_field(field_id)) + + +@admin_bp.route('/freight-rpa/onhand/fields/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_field(field_id: int): + """删除未被配置引用的扩展库存字段。""" + onhand_field_catalog.delete_field(field_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/onhand/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, + ) + 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, + 'inventory_fields': onhand_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('/freight-rpa/onhand/parsing-profiles', methods=['GET']) +@require_admin +def list_shipping_inventory_parsing_profiles(): + """列出可复用库存解析 Profile 版本。""" + return _ok(onhand_parsing_profile.list_profiles()) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['POST']) +@require_admin +def create_shipping_inventory_parsing_profile(): + """创建库存解析 Profile 草稿。""" + return _ok(onhand_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles/', methods=['PUT']) +@require_admin +def update_shipping_inventory_parsing_profile(profile_id: int): + """更新库存解析 Profile 草稿。""" + return _ok(onhand_parsing_profile.save_draft( + request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id, + )) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles//sample-replacement-preview/', methods=['POST']) +@require_admin +def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int): + """比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。""" + return _ok(onhand_structure_analysis.preview_profile_sample_replacement( + profile_id, analysis_id, request.get_json(silent=True) or {}, + )) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles//publish', methods=['POST']) +@require_admin +def publish_shipping_inventory_parsing_profile(profile_id: int): + """发布库存解析 Profile。""" + return _ok(onhand_parsing_profile.publish(profile_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_parsing_profile(profile_id: int): + """退役无库存源引用的已发布解析 Profile。""" + return _ok(onhand_parsing_profile.retire(profile_id)) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_parsing_profile(profile_id: int): + """删除从未发布的解析 Profile 草稿。""" + onhand_parsing_profile.delete_draft(profile_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses', methods=['POST']) +@require_admin +def create_shipping_inventory_structure_analysis(): + """上传库存样本并返回后端分析出的工作表、表头、栏位和建议。""" + return _ok(onhand_structure_analysis.create_sample_upload( + request.files.get('file'), actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses/', methods=['GET']) +@require_admin +def get_shipping_inventory_structure_analysis(analysis_id: int): + """读取库存样本结构分析结果,供管理端继续配置解析方案。""" + return _ok(onhand_structure_analysis.get_analysis(analysis_id)) + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses//create-profile-draft', methods=['POST']) +@require_admin +def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int): + """使用确认后的真实表头和匹配键创建库存文件解析方案草稿。""" + return _ok(onhand_structure_analysis.create_profile_draft( + analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/freight-rpa/onhand/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(onhand_structure_analysis.adopt_published_profile( + analysis_id, int(payload.get('profile_id') or 0), + )) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['POST']) +@require_admin +def create_shipping_inventory_rule(): + """创建草稿路由规则。""" + return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules/', methods=['PUT']) +@require_admin +def update_shipping_inventory_rule(rule_id: int): + """更新草稿规则;已发布规则由服务层拒绝原地修改。""" + return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id)) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules//publish', methods=['POST']) +@require_admin +def publish_shipping_inventory_rule(rule_id: int): + """发布草稿规则并写入不可变定义快照。""" + return _ok(shipping_onhand_admin_service.publish_rule(rule_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_rule(rule_id: int): + """归档已发布规则,保留其审计版本但停止新路由使用。""" + return _ok(shipping_onhand_admin_service.retire_rule(rule_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_rule(rule_id: int): + """删除从未发布的草稿规则。""" + shipping_onhand_admin_service.delete_draft_rule(rule_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['GET']) +@require_admin +def list_shipping_inventory_external_mappings(): + """列出库存源到外部系统仓库映射。""" + return _ok(shipping_onhand_admin_service.list_external_mappings()) + + +@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['POST']) +@require_admin +def create_shipping_inventory_external_mapping(): + """创建精确或 Source 默认外部系统映射。""" + return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/external-mappings/', methods=['PUT']) +@require_admin +def update_shipping_inventory_external_mapping(mapping_id: int): + """更新外部系统映射,不参与任何调拨动作。""" + return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id)) + + +@admin_bp.route('/freight-rpa/onhand/external-mappings/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_external_mapping(mapping_id: int): + """删除错误的外部系统仓库映射。""" + shipping_onhand_admin_service.delete_external_mapping(mapping_id) return '', 204 diff --git a/backend/app/api/freight_rpa.py b/backend/app/api/freight_rpa.py index 06e27528..22d1f10b 100644 --- a/backend/app/api/freight_rpa.py +++ b/backend/app/api/freight_rpa.py @@ -75,7 +75,7 @@ def onhand_ready(): 【AI 触发时机】:非 Agent 入口;库存 Worker 完成单任务导出后调用。 核心逻辑:dispatch_sink('onhand-ready') 分发到组合根注册的业务 sink - (inventory_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写), + (onhand_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写), envelope = 裸业务 tool_response dict(与旧 /rpa/inventory-ready 逐字一致)。 """ return jsonify(dispatch_sink('onhand-ready', **_payload())) @@ -112,7 +112,7 @@ def onhand_batch_progress(): 【AI 触发时机】:非 Agent 入口;Worker 每完成一个站点导出后调用(非终态,以 batch-ready 为准)。 核心逻辑:dispatch_sink('onhand-batch-progress') 分发;实时回写排程 run 计数 - (inventory_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。 + (onhand_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。 """ return jsonify(dispatch_sink('onhand-batch-progress', **_payload())) @@ -172,7 +172,7 @@ def inbound_batch_ready(): 【AI 触发时机】:非 Agent 入口;收料 Worker 完成报表导出并落 drop 目录后调用。 核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根注册的业务 sink - (receipt_report_storage.ingest_receipt_callback:委托 freight_rpa.inbound.report_archive + (inbound_report_storage.ingest_receipt_callback:委托 freight_rpa.inbound.report_archive 原样归档,终态 commit 后由域内业务桥推进在途调拨并归集排程终态)——独立归档文件, 绝不进入库存回调或库存匹配链路;envelope = {'success': True, 'data': ...}(旧端点逐字一致)。 """ @@ -186,7 +186,7 @@ def inbound_unit_progress(): 【AI 触发时机】:非 Agent 入口;收料 Worker 领取单元后调用(awaiting_rpa → processing)。 核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_receipt_unit_processing - (Task 11 已随排程壳平移改名,现住 schedule.freight_inbound_rpa_finalize);本路由同时是收料 + (Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize);本路由同时是收料 超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08), Worker 上报全程 404,勿再从任何路由文件删除。 """ @@ -200,7 +200,7 @@ def inbound_batch_progress(): 【AI 触发时机】:非 Agent 入口;收料 Worker 每完成一笔导出后调用(非终态)。 核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_receipt_batch_progress - (Task 11 已随排程壳平移改名,现住 schedule.freight_inbound_rpa_finalize),回写排程 run 计数 + (Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize),回写排程 run 计数 (对齐 onhand-batch-progress 语义)。 """ return jsonify(dispatch_sink('inbound-batch-progress', **_payload())) diff --git a/backend/app/api/in_transit_transfer/__init__.py b/backend/app/api/in_transit_transfer/__init__.py index d6422ada..041a91e3 100644 --- a/backend/app/api/in_transit_transfer/__init__.py +++ b/backend/app/api/in_transit_transfer/__init__.py @@ -186,13 +186,13 @@ def requery_items_api(matching_no: str): @in_transit_transfer_bp.route("/sources/inbound-files", methods=["POST"]) @require_transfer_permission def download_source_inbound_files_api(): - """按选中来源打包下载各自最新归档入站文件(ShippingReceiptReport RPA 产物,zip);记录访问审计。""" + """按选中来源打包下载各自最新归档入站文件(ShippingInboundReport RPA 产物,zip);记录访问审计。""" import io import zipfile from pathlib import Path as _Path from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile from app.services.file_assets.storage import file_asset_storage from app.services.in_transit_transfer.audit import build_transfer_audit_event from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition @@ -210,15 +210,15 @@ def download_source_inbound_files_api(): if not code: continue report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) .filter( - ShippingReceiptReportFile.unit_run.has(source_code=code), + FreightRpaInboundReportFile.unit_run.has(source_code=code), # 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径, # 单一事实来源见 inbound_file_gate。 usable_inbound_file_condition(), ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()) .first() ) if report is None: @@ -761,11 +761,11 @@ def transfer_sources_api(): 供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天 (业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。 """ - from app.models import ShippingInventorySource + from app.models import FreightRpaSource from app.services.in_transit_transfer.source_file_status import resolve_source_file_status - rows = ShippingInventorySource.query.filter_by(enabled=True).order_by( - ShippingInventorySource.connector_type, ShippingInventorySource.source_code, + rows = FreightRpaSource.query.filter_by(enabled=True).order_by( + FreightRpaSource.connector_type, FreightRpaSource.source_code, ).all() return _ok([ { @@ -782,7 +782,7 @@ def transfer_sources_api(): @in_transit_transfer_bp.route("/sources//retry-rpa", methods=["POST"]) @require_transfer_permission def retry_source_rpa_api(source_code: str): - """对指定来源重新触发一次入站 RPA 抓取(复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留)。 + """对指定来源重新触发一次入站 RPA 抓取(复用货代 ShippingInboundReport trigger 链路,shipping_notice 域术语保留)。 【AI 触发时机】来源入站文件不可用需要恢复时调用:解析失败(parse_failed)先 本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。 @@ -847,7 +847,7 @@ def retry_sources_rpa_batch_api(): 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用; 逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器; - 合并单文件后 Worker 单次登录串行导出全部来源(与 ShippingReceiptReport RPA 排程路径同效率)。 + 合并单文件后 Worker 单次登录串行导出全部来源(与 ShippingInboundReport RPA 排程路径同效率)。 请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与 fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。 diff --git a/backend/app/api/internal/jobs.py b/backend/app/api/internal/jobs.py index d68cac47..f31718de 100644 --- a/backend/app/api/internal/jobs.py +++ b/backend/app/api/internal/jobs.py @@ -19,12 +19,12 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot from app.services.schedule.job_registry import get_platform_job, run_platform_job from app.services.schedule.schedule_contract import normalize_job_key from app.services.schedule.scheduler_service import _generate_run_no -from app.services.schedule.freight_onhand_rpa_finalize import ( +from app.services.schedule.freight_rpa_onhand_finalize import ( apply_deferred_schedule_run_state, recover_stale_awaiting_rpa_schedule_runs, should_defer_schedule_run_finalization, ) -from app.services.schedule.freight_inbound_rpa_finalize import ( +from app.services.schedule.freight_rpa_inbound_finalize import ( apply_deferred_receipt_schedule_run_state, recover_stale_receipt_rpa_schedule_runs, should_defer_receipt_schedule_run, diff --git a/backend/app/api/schedule/runs.py b/backend/app/api/schedule/runs.py index 8694b2d9..a3d30d6b 100644 --- a/backend/app/api/schedule/runs.py +++ b/backend/app/api/schedule/runs.py @@ -18,11 +18,11 @@ from app.api.schedule.blueprint import schedule_admin_bp from app.core.auth.jwt import get_current_user from app.core.decorators import require_admin from app.core.errors import ConflictError, NotFoundError -from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun +from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundReportFile, FreightRpaInboundUnitRun from app.services.schedule.query_service import get_run, list_runs, serialize_run from app.services.schedule.queue_service import enqueue_manual_schedule_run -from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download -from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download +from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download +from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger @@ -144,17 +144,17 @@ def get_schedule_run_receipt_raw_zip(run_id: int): ) -@schedule_admin_bp.route('/receipt-report-files//resend', methods=['POST']) +@schedule_admin_bp.route('/inbound-report-files//resend', methods=['POST']) @require_admin def resend_receipt_report_file(file_id: int): """管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。""" - report_file = db.session.get(ShippingReceiptReportFile, file_id) + report_file = db.session.get(FreightRpaInboundReportFile, file_id) if report_file is None or report_file.archive_deleted_at is not None: raise NotFoundError('Receipt report file not found') user = get_current_user() outcome = deliver_inbound_file(report_file.id, force=True) append_shipping_audit_event( - event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file', + event_type='shipping_inbound_report_notification_resent', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None), owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success', after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)}, @@ -165,7 +165,7 @@ def resend_receipt_report_file(file_id: int): return jsonify({'success': True, 'data': outcome}) -@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET']) +@schedule_admin_bp.route('/inbound-rpa-units', methods=['GET']) @require_admin def list_receipt_rpa_units(): """管理员查看收料单元运行事实,供失败单元填写原因后人工重试。""" @@ -178,15 +178,15 @@ def list_receipt_rpa_units(): except (TypeError, ValueError): from app.core.errors import ValidationError raise ValidationError('limit is invalid') - query = ShippingReceiptRpaUnitRun.query.order_by( - ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(), + query = FreightRpaInboundUnitRun.query.order_by( + FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(), ) if status: - query = query.filter(ShippingReceiptRpaUnitRun.status == status) + query = query.filter(FreightRpaInboundUnitRun.status == status) units = query.limit(limit).all() user = get_current_user() append_shipping_audit_event( - event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection', + event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_unit_collection', aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None), owner_user_id=getattr(user, 'id', None), result='success', after={'visible_count': len(units), 'status': status or None, 'limit': limit}, @@ -207,11 +207,11 @@ def list_receipt_rpa_units(): } for unit in units]}}) -@schedule_admin_bp.route('/receipt-rpa-units//retry', methods=['POST']) +@schedule_admin_bp.route('/inbound-rpa-units//retry', methods=['POST']) @require_admin def retry_receipt_rpa_unit(unit_id: int): """管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。""" - failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id) + failed = db.session.get(FreightRpaInboundUnitRun, unit_id) if failed is None: raise NotFoundError('Receipt RPA unit not found') if failed.status not in {'failed', 'cancelled'}: @@ -222,15 +222,15 @@ def retry_receipt_rpa_unit(unit_id: int): from app.core.errors import ValidationError raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED') user = get_current_user() - retry = ShippingReceiptRpaUnitRun( - schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id, + retry = FreightRpaInboundUnitRun( + schedule_run_id=failed.schedule_run_id, source_id=failed.source_id, retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type, warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa', config_snapshot_json=dict(failed.config_snapshot_json or {}), ) db.session.add(retry) db.session.flush() - source = retry.inventory_source + source = retry.source profile = source.rpa_profile if source is not None else None if source is None or profile is None or not profile.enabled: db.session.rollback() @@ -260,7 +260,7 @@ def retry_receipt_rpa_unit(unit_id: int): summary['awaiting_receipt_rpa'] = True run.response_summary_json = summary append_shipping_audit_event( - event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit', + event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit', aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None), owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason, before={'status': failed.status, 'error_code': failed.error_code}, diff --git a/backend/app/api/tools/shipping_notice.py b/backend/app/api/tools/shipping_notice.py index b9fe1c2d..bf9811cb 100644 --- a/backend/app/api/tools/shipping_notice.py +++ b/backend/app/api/tools/shipping_notice.py @@ -199,7 +199,7 @@ def tool_ensure_inventory(): task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), trigger='legacy_tool_ensure_inventory', operator_id=payload.get('operator_id'), - resume_gate_code='inventory_preparation', + resume_gate_code='onhand_preparation', )) @shipping_notice_bp.route('/tools/auto_progress', methods=['POST']) @@ -222,7 +222,7 @@ def tool_match_inventory(): task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), trigger='legacy_tool_match_inventory', operator_id=payload.get('operator_id'), - resume_gate_code='inventory_matching', + resume_gate_code='onhand_matching', )) @shipping_notice_bp.route('/tools/confirm_customer', methods=['POST']) diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py index aaaeb6c0..e0dc462a 100644 --- a/backend/app/api/workspace/__init__.py +++ b/backend/app/api/workspace/__init__.py @@ -12,7 +12,7 @@ from app.api.workspace.shipping_notice import workspace_shipping_notice_bp from app.api.workspace.voucher_check import workspace_voucher_check_bp import app.api.workspace.shipping_process_gate # noqa: F401 -import app.api.workspace.shipping_inventory_candidates # noqa: F401 +import app.api.workspace.shipping_onhand_candidates # noqa: F401 __all__ = [ 'workspace_announcements_bp', diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index c1be6612..528c6741 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -87,11 +87,11 @@ def _ok(payload: Any, *, status: int = 200): return ok(payload, request_id=getattr(g, 'request_id', None), status=status) -@workspace_shipping_notice_bp.route('/receipt-report-files//download', methods=['GET']) +@workspace_shipping_notice_bp.route('/inbound-report-files//download', methods=['GET']) def workspace_download_receipt_report_file(file_id: int): """下载当前接收人或管理员有权读取的原样收料报表。""" user = _require_user() - from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download + from app.services.shipping_notice.inbound_report_access import resolve_receipt_report_download stream, filename, content_type = resolve_receipt_report_download(file_id, user) response = send_file( @@ -102,7 +102,7 @@ def workspace_download_receipt_report_file(file_id: int): return response -@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET']) +@workspace_shipping_notice_bp.route('/inbound-report-files', methods=['GET']) def workspace_list_receipt_report_files(): """列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。""" user = _require_user() @@ -110,7 +110,7 @@ def workspace_list_receipt_report_files(): limit = int(request.args.get('limit') or 100) except (TypeError, ValueError) as exc: raise ValidationError('limit must be an integer') from exc - from app.services.shipping_notice.receipt_report_access import list_receipt_report_files + from app.services.shipping_notice.inbound_report_access import list_receipt_report_files return _ok({'items': list_receipt_report_files(user, limit=limit)}) @@ -1308,11 +1308,11 @@ def workspace_shipping_task_inventory_file(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') - from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download + from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download resolved = resolve_task_inventory_download(task) if resolved is None: - raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND') + raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND') path, download_name = resolved from app.services.shipping_notice.fulfillment_audit import record_access_audit record_access_audit( @@ -1338,28 +1338,28 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no: raise NotFoundError('Not found') from pathlib import Path - from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch + from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch requested_file_no = str(inventory_file_no or '').strip() inventory_file = ( - ShippingInventoryFile.query + FreightRpaOnhandReportFile.query .join( - ShippingNoticeLineInventoryMatch, - ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id, + ShippingNoticeLineOnhandMatch, + ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id, ) .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no, - ShippingInventoryFile.inventory_file_no == requested_file_no, + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no, + FreightRpaOnhandReportFile.onhand_file_no == requested_file_no, ) .first() ) storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip() path = Path(storage_path).resolve() if storage_path else None if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file(): - raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND') - from app.services.shipping_notice.inventory_file_store import build_inventory_download_name + raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND') + from app.services.shipping_notice.onhand_file_store import build_inventory_download_name download_name = build_inventory_download_name( inventory_file, source_file_name=inventory_file.source_file_name, path=path, ) diff --git a/backend/app/api/workspace/shipping_inventory_candidates.py b/backend/app/api/workspace/shipping_onhand_candidates.py similarity index 93% rename from backend/app/api/workspace/shipping_inventory_candidates.py rename to backend/app/api/workspace/shipping_onhand_candidates.py index 05053fdf..b92ce18d 100644 --- a/backend/app/api/workspace/shipping_inventory_candidates.py +++ b/backend/app/api/workspace/shipping_onhand_candidates.py @@ -1,8 +1,8 @@ """ -backend/app/api/workspace/shipping_inventory_candidates.py +backend/app/api/workspace/shipping_onhand_candidates.py 用途:正式 Task 库存候选只读详情 API。 -依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。 +依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、onhand_candidate_projection。 逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason, 不把可恢复业务阻断误报成 404。 """ @@ -13,7 +13,7 @@ from flask import request from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp from app.core.errors import ValidationError -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_detail, ) from app.services.shipping_notice.query_service import get_task_for_user diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index f9539311..46725e5e 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -370,8 +370,8 @@ class Config: 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' + SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = ( + os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true' ) FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int( os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900' @@ -443,8 +443,8 @@ class Config: SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int( os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24' ) - SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = ( - os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true' + SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = ( + os.getenv('SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED', 'true').lower() == 'true' ) SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS') FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP') diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 49105fc8..49a9622d 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -16,7 +16,7 @@ from app.jobs.handlers import ( # noqa: F401 procurement_contract_review, schedule_run, shipping_document_layout, - shipping_inventory_callback_process, + freight_rpa_onhand_callback_process, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, diff --git a/backend/app/jobs/handlers/shipping_inventory_callback_process.py b/backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py similarity index 55% rename from backend/app/jobs/handlers/shipping_inventory_callback_process.py rename to backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py index 0fd3fe3a..68ca3baf 100644 --- a/backend/app/jobs/handlers/shipping_inventory_callback_process.py +++ b/backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py @@ -1,9 +1,13 @@ """ -backend/app/jobs/handlers/shipping_inventory_callback_process.py +backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py 用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。 -依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。 +依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。 逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。 + 业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后 + onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚, + 重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回 + payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。 """ from __future__ import annotations @@ -16,7 +20,7 @@ from app.jobs.types import JobType from app.models import Job -@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS) +@register_handler(JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS) def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None: """处理一个已收件的库存 RPA 回调。 @@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N owned_attempt = int(job.attempts or 0) try: - from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch result = process_rpa_report_inventory_batch(dict(job.payload_json or {})) result_data = result.get('data') if isinstance(result, dict) else None @@ -44,7 +48,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}: failed_items = result_data.get('failed') if isinstance(result_data, dict) else [] first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None - from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback + from app.services.shipping_notice.onhand_rpa_workflow import settle_failed_inventory_callback settle_failed_inventory_callback( dict(job.payload_json or {}), @@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N message='库存 RPA 回调已异步处理', owned_attempt=owned_attempt, ) - except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence + except Exception as exc: # noqa: BLE001 - 队列收口保留可重试证据 db.session.rollback() + # 【Task 7 修复轮 3】批量 commit 后投递失败的重抛携带「未成功文件清单」—— + # 写回 Job payload(retry_dispatch_files),重试经批量入口的「只重投失败 + # 文件」通道补齐(整批重放会被 callback_id 已消费的 replay 检查跳过、 + # 已收口的排程 run 校验拦下);清单随重试结果逐轮收敛,直至全部成功或 + # attempts 耗尽。普通意外异常(无清单)仍整批自然重放。 + from app.services.shipping_notice.onhand_rpa_workflow import ( + OnhandReportDispatchAfterCommitError, + ) + + if isinstance(exc, OnhandReportDispatchAfterCommitError) and exc.failed_files: + job.payload_json = { + **(dict(job.payload_json or {})), + 'retry_dispatch_files': list(exc.failed_files), + } + db.session.commit() fail_job( job.id, error=str(exc), result={'status': 'processing_failed', 'error': str(exc)[:1000]}, - retryable=False, + # 【Task 7 修复轮 2】意外异常(含批量 commit 后 onhand 事实处理函数失败 + # ——process_rpa_report_inventory_batch 已尽力完成其余投递、排程收口与 + # drop 文件清理入队后原样重抛)必须可重试:文件行已提交不回滚,重放按 + # 幂等契约补齐收口;业务失败(transport/result_status=failed)仍走上方 + # retryable=False 分支。 + retryable=True, owned_attempt=owned_attempt, ) diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 91830e23..b22cbef2 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -3,7 +3,9 @@ backend/app/jobs/types.py 用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。 逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨); - shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。 + shipping_process_gate 由 shipping worker 与发货通知任务同队列领取; + 在手回调成员 FREIGHT_RPA_ONHAND_CALLBACK_PROCESS 的持久化值为 + freight_rpa_onhand_callback_process。 """ from __future__ import annotations @@ -20,8 +22,9 @@ class JobType(StrEnum): SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SHIPPING_PROCESS_GATE = 'shipping_process_gate' - # RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 - SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process' + # 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 + # 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。 + FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process' # 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。 SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark' # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) @@ -76,7 +79,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'shipping': frozenset({ 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', 'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', - 'shipping_inventory_callback_process', + 'freight_rpa_onhand_callback_process', 'shipping_stp_auto_create', 'shipping_line_auto_fulfill', 'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress', }), diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 464398b4..f84461bd 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -2,8 +2,9 @@ backend/app/models/__init__.py 用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。 -依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。 +依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。 逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。 + 在手/入站模型导出 FreightRpa*。 """ from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest @@ -31,15 +32,15 @@ from app.models.contract_payment import ( ContractPaymentVendorRequest, ) from app.models.shipping import ( - ShippingInventoryFile, ShippingNotice, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingTaskEvent, ShippingTaskPurgeAudit, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ) +from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile from app.models.shipping_order_submission import ShippingOrderSubmission from app.models.shipping_order_task import ShippingOrderTask from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence @@ -52,8 +53,8 @@ from app.models.shipping_context_provider import ShippingContextProvider, Shippi from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact from app.models.shipping_fulfillment import ( ShippingExportArtifactLine, - ShippingInventoryVerification, - ShippingInventoryVerificationLine, + ShippingOnhandVerification, + ShippingOnhandVerificationLine, ShippingReservation, ShippingUploadAttempt, ) @@ -95,7 +96,7 @@ from app.models.shipping_order_review import ( from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency -from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch +from app.models.shipping_notice_line_onhand_match import ShippingNoticeLineOnhandMatch from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion from app.models.shipping_order_extraction_run import ( ShippingOrderExtractionDiagnosticAudit, @@ -137,27 +138,28 @@ from app.models.shipping_document_layout import ShippingDocumentLayoutVersion from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot -from app.models.shipping_inventory_config import ( - ShippingInventoryField, - ShippingInventoryExternalMapping, - ShippingInventoryConfigurationTestRun, - ShippingInventoryValidationBatch, - ShippingInventorySourceParsingBindingAudit, - ShippingInventoryParsingProfile, - ShippingInventoryRoutingRule, - ShippingInventoryRoutingRuleCondition, - ShippingInventoryRoutingRuleVersion, - ShippingInventorySource, - ShippingInventoryStructureAnalysis, - ShippingRpaProfile, +from app.models.freight_rpa_config import ( + FreightRpaOnhandField, + FreightRpaOnhandExternalMapping, + FreightRpaOnhandConfigurationTestRun, + FreightRpaOnhandValidationBatch, + FreightRpaSourceParsingBindingAudit, + FreightRpaParsingProfile, + FreightRpaOnhandRoutingRule, + FreightRpaOnhandRoutingRuleCondition, + FreightRpaOnhandRoutingRuleVersion, + FreightRpaSource, + FreightRpaOnhandReportConfig, + FreightRpaOnhandStructureAnalysis, + FreightRpaProfile, ) -from app.models.shipping_receipt_report import ( - ShippingReceiptNotificationDelivery, - ShippingReceiptReportConfig, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, +from app.models.freight_rpa_inbound_report import ( + FreightRpaInboundNotificationDelivery, + FreightRpaInboundReportConfig, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) -from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession +from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession from app.models.shipping_customer import ( ShippingBusinessSequence, ShippingCustomer, @@ -180,18 +182,18 @@ from app.models.shipping_identity_rule import ( ShippingIdentityRuleAuditEvent, ShippingIdentityRuleSet, ) -from app.models.shipping_inventory_candidates import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, +from app.models.shipping_onhand_candidates import ( + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, ) -from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt +from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan -from app.models.shipping_inventory_preparation import ( - ShippingInventoryPreparationAttempt, - ShippingInventoryPreparationSourceAttempt, +from app.models.shipping_onhand_preparation import ( + ShippingOnhandPreparationAttempt, + ShippingOnhandPreparationSourceAttempt, ) -from app.models.shipping_inventory_mapping import ShippingInventoryMapping +from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping from app.models.training import ( LeanTrainingCompletion, LeanTrainingReminder, @@ -319,7 +321,7 @@ __all__ = [ 'ShippingOrderReviewLineDecision', 'ShippingOrderReviewWaveLine', 'ShippingOrderReviewWaveIdempotency', - 'ShippingNoticeLineInventoryMatch', + 'ShippingNoticeLineOnhandMatch', 'ShippingOrderReviewSuggestion', 'ShippingOrderProcessingRun', 'ShippingOrderProcessingRunIntake', @@ -368,30 +370,31 @@ __all__ = [ 'ShippingIdentityRuleAuditEvent', 'ShippingTaskEvent', 'ShippingTaskPurgeAudit', - 'ShippingInventoryFile', - 'ShippingTaskInventoryLink', - 'ShippingRpaProfile', - 'ShippingInventorySource', - 'ShippingReceiptReportConfig', - 'ShippingReceiptRpaUnitRun', - 'ShippingReceiptReportFile', - 'ShippingReceiptNotificationDelivery', - 'ShippingInventoryField', - 'ShippingInventoryStructureAnalysis', - 'ShippingInventoryRoutingRule', - 'ShippingInventoryRoutingRuleCondition', - 'ShippingInventoryRoutingRuleVersion', - 'ShippingInventoryExternalMapping', - 'ShippingInventoryConfigurationTestRun', - 'ShippingInventoryValidationBatch', - 'ShippingInventorySourceParsingBindingAudit', - 'ShippingInventoryParsingProfile', - 'ShippingTemporaryInventorySession', + 'FreightRpaOnhandReportFile', + 'ShippingTaskOnhandLink', + 'FreightRpaProfile', + 'FreightRpaSource', + 'FreightRpaOnhandReportConfig', + 'FreightRpaInboundReportConfig', + 'FreightRpaInboundUnitRun', + 'FreightRpaInboundReportFile', + 'FreightRpaInboundNotificationDelivery', + 'FreightRpaOnhandField', + 'FreightRpaOnhandStructureAnalysis', + 'FreightRpaOnhandRoutingRule', + 'FreightRpaOnhandRoutingRuleCondition', + 'FreightRpaOnhandRoutingRuleVersion', + 'FreightRpaOnhandExternalMapping', + 'FreightRpaOnhandConfigurationTestRun', + 'FreightRpaOnhandValidationBatch', + 'FreightRpaSourceParsingBindingAudit', + 'FreightRpaParsingProfile', + 'ShippingTemporaryOnhandSession', 'ShippingExcelTemplate', 'ShippingExportArtifact', 'ShippingReservation', - 'ShippingInventoryVerification', - 'ShippingInventoryVerificationLine', + 'ShippingOnhandVerification', + 'ShippingOnhandVerificationLine', 'ShippingExportArtifactLine', 'ShippingUploadAttempt', 'ShippingProcessExecution', @@ -426,10 +429,10 @@ __all__ = [ 'MaintenanceDevice', 'MaintenanceRecord', 'MaintenanceAuditLog', - 'ShippingInventoryCandidateSet', - 'ShippingInventoryCandidateSource', - 'ShippingInventoryCandidateLine', - 'ShippingTaskInventoryRpaAttempt', + 'ShippingOnhandCandidateSet', + 'ShippingOnhandCandidateSource', + 'ShippingOnhandCandidateLine', + 'FreightRpaOnhandTaskAttempt', 'VoucherCheckProfile', 'VoucherCheckRun', 'VoucherCheckSubject', diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/freight_rpa_config.py similarity index 70% rename from backend/app/models/shipping_inventory_config.py rename to backend/app/models/freight_rpa_config.py index 04d44c5e..6450f7ab 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/freight_rpa_config.py @@ -1,9 +1,10 @@ """ -models/shipping_inventory_config.py +backend/app/models/freight_rpa_config.py -用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。 +用途:定义货代库存源、RPA Profile、在手报表配置、通用路由规则及外部系统仓库映射主数据。 依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。 -逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置, +逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置; + 在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列), 外部系统映射仅供后端内部复用,不承载调拨决策。 """ @@ -18,18 +19,18 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base -class ShippingInventoryField(Base): +class FreightRpaOnhandField(Base): """用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。""" - __tablename__ = 'shipping_inventory_fields' + __tablename__ = 'freight_rpa_onhand_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'), + UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'), + UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'), + CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'), + CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'), CheckConstraint( "usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')", - name='ck_shipping_inventory_fields_usage_type', + name='ck_freight_rpa_onhand_fields_usage_type', ), ) @@ -48,13 +49,13 @@ class ShippingInventoryField(Base): updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) -class ShippingRpaProfile(Base): +class FreightRpaProfile(Base): """货代库存登录连接配置;凭据字段始终保存密文。""" - __tablename__ = 'shipping_rpa_profiles' + __tablename__ = 'freight_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'), + UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'), + CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -81,24 +82,24 @@ class ShippingRpaProfile(Base): 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') + sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='rpa_profile') -class ShippingInventorySource(Base): +class FreightRpaSource(Base): """库存业务来源;固定仓或库存行动态解析 Warehouse。""" - __tablename__ = 'shipping_inventory_sources' + __tablename__ = 'freight_rpa_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'), + UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'), + CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_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', + name='ck_freight_rpa_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', + "enabled = false OR excel_template_id IS NOT NULL", + name='ck_freight_rpa_sources_enabled_template', ), ) @@ -106,14 +107,12 @@ class ShippingInventorySource(Base): 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) + rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, 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) + # 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定); + # CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。 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) @@ -122,31 +121,72 @@ class ShippingInventorySource(Base): 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') + rpa_profile: Mapped[FreightRpaProfile] = 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' + onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship( + back_populates='source', uselist=False, cascade='all, delete-orphan', ) - receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship( - back_populates='inventory_source', uselist=False, cascade='all, delete-orphan', + external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship( + back_populates='source', cascade='all, delete-orphan' + ) + inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship( + back_populates='source', uselist=False, cascade='all, delete-orphan', ) -class ShippingInventorySourceParsingBindingAudit(Base): - """库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。""" +class FreightRpaOnhandReportConfig(Base): + """库存站点的一对一在手报表配置;报表路径与查询条件归 RPA 域。 - __tablename__ = 'shipping_inventory_source_parsing_binding_audits' + 解析方案绑定随本表保存(purpose='onhand')。站点启用要求「本配置存在且 + parsing_profile_id 非空」,PostgreSQL CHECK 不能跨表,该校验由保存站点的服务执行。 + """ + + __tablename__ = 'freight_rpa_onhand_report_configs' __table_args__ = ( - Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'), + UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source'), ) id: Mapped[int] = mapped_column(primary_key=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False) - previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, + # 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。 + source_id: Mapped[int] = mapped_column( + ForeignKey('freight_rpa_sources.id', ondelete='CASCADE'), nullable=False, index=True, ) - parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False) + # 在手报表文件解析规则(purpose='onhand');空则站点不得启用(服务层校验)。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True, + ) + # 业务报表定义属于配置行;Driver 的 selector、等待与下载实现不进入数据库配置。 + report_path_json: Mapped[dict[str, Any]] = mapped_column( + JSON, default=dict, server_default=text("'{}'"), nullable=False, + ) + # 与入站同构:查询条件原样下发 Worker;空条件表示页面默认。 + query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( + JSON, default=list, server_default=text("'[]'"), 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) + + source: Mapped['FreightRpaSource'] = relationship(back_populates='onhand_report_config') + parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship(back_populates='sources') + + +class FreightRpaSourceParsingBindingAudit(Base): + """库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。""" + + __tablename__ = 'freight_rpa_onhand_source_parsing_binding_audits' + __table_args__ = ( + Index('ix_inventory_source_parsing_binding_audit_source_created', 'source_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False) + previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, + ) + parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False) operation: Mapped[str] = mapped_column(String(32), nullable=False) reason: Mapped[str] = mapped_column(String(500), nullable=False) actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) @@ -157,29 +197,27 @@ class ShippingInventorySourceParsingBindingAudit(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) -class ShippingInventoryParsingProfile(Base): +class FreightRpaParsingProfile(Base): """可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。 - 注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表", - 用途以 purpose 字段为准,勿按表名推断只服务库存。 - purpose='onhand':在手库存文件(原 inventory),端点用 ShippingInventoryField - 库存字段目录(既有语义); - purpose='inbound':入站收料文件(原 movement),端点用定死领域字段 + 表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。 + purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录; + purpose='inbound':入站文件,端点用定死领域字段 (MOVEMENT_FIELDS,doc_no/line_no/.../movement_date), - 供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。 - 绑定入口:库存站点 ShippingInventorySource.parsing_profile_id / - 收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='inbound'); - purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。 + 不依赖库存字段目录。校验逻辑按 purpose 分支。 + 绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id / + 入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound'); + purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。 """ - __tablename__ = 'shipping_inventory_parsing_profiles' + __tablename__ = 'freight_rpa_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'), CheckConstraint( "purpose IN ('onhand', 'inbound', 'outbound')", - name='ck_shipping_inventory_parsing_profiles_purpose', + name='ck_freight_rpa_parsing_profiles_purpose', ), ) @@ -198,7 +236,7 @@ class ShippingInventoryParsingProfile(Base): fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) # Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook. sample_analysis_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True, ) # Preserve every confirmed evidence switch so a draft remains explainable after samples change. sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column( @@ -209,16 +247,17 @@ class ShippingInventoryParsingProfile(Base): 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') - sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship( + # s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。 + sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile') + sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship( foreign_keys=[sample_analysis_id], ) -class ShippingInventoryStructureAnalysis(Base): +class FreightRpaOnhandStructureAnalysis(Base): """库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。""" - __tablename__ = 'shipping_inventory_structure_analyses' + __tablename__ = 'freight_rpa_onhand_structure_analyses' __table_args__ = ( Index('ix_inv_structure_analysis_file_hash', 'file_checksum'), Index('ix_inv_structure_analysis_created', 'created_at'), @@ -246,24 +285,28 @@ class ShippingInventoryStructureAnalysis(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) -class ShippingInventoryConfigurationTestRun(Base): +class FreightRpaOnhandConfigurationTestRun(Base): """库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。""" - __tablename__ = 'shipping_inventory_configuration_test_runs' - __table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),) + __tablename__ = 'freight_rpa_onhand_configuration_test_runs' + __table_args__ = ( + UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'), + # PostgreSQL 标识符上限 63。index=True 会生成 65 字节的自动名,故用显式短名。 + Index('ix_fr_onhand_cfg_test_runs_validation_batch_id', 'validation_batch_id'), + ) id: Mapped[int] = mapped_column(primary_key=True) run_no: Mapped[str] = mapped_column(String(64), nullable=False) validation_batch_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True, ) rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) source_config_version: Mapped[int] = mapped_column(Integer, nullable=False) rpa_profile_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) + analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_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) @@ -271,10 +314,10 @@ class ShippingInventoryConfigurationTestRun(Base): completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) -class ShippingInventoryValidationBatch(Base): +class FreightRpaOnhandValidationBatch(Base): """库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。""" - __tablename__ = 'shipping_inventory_validation_batches' + __tablename__ = 'freight_rpa_onhand_validation_batches' __table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),) id: Mapped[int] = mapped_column(primary_key=True) @@ -287,21 +330,21 @@ class ShippingInventoryValidationBatch(Base): stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) retry_of_batch_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, + ForeignKey('freight_rpa_onhand_validation_batches.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): +class FreightRpaOnhandRoutingRule(Base): """可版本化的库存源路由决策表;仅产出受控 Source 候选。""" - __tablename__ = 'shipping_inventory_routing_rules' + __tablename__ = 'freight_rpa_onhand_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'), + UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'), + CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'), + CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'), + CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -321,17 +364,17 @@ class ShippingInventoryRoutingRule(Base): 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' + conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship( + back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence' ) -class ShippingInventoryRoutingRuleCondition(Base): +class FreightRpaOnhandRoutingRuleCondition(Base): """库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。""" - __tablename__ = 'shipping_inventory_routing_rule_conditions' + __tablename__ = 'freight_rpa_onhand_routing_rule_conditions' __table_args__ = ( - UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'), + UniqueConstraint('rule_id', 'sequence', name='uq_freight_rpa_onhand_routing_rule_conditions_sequence'), CheckConstraint( "source_kind = 'order_field' AND order_field_id IS NOT NULL", name='ck_inventory_routing_condition_source', @@ -339,7 +382,7 @@ class ShippingInventoryRoutingRuleCondition(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) + rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_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) @@ -347,24 +390,24 @@ class ShippingInventoryRoutingRuleCondition(Base): 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') + rule: Mapped[FreightRpaOnhandRoutingRule] = relationship(back_populates='conditions') -class ShippingInventoryRoutingRuleVersion(Base): +class FreightRpaOnhandRoutingRuleVersion(Base): """已发布路由规则的不可变定义快照,供任务审计回放使用。""" - __tablename__ = 'shipping_inventory_routing_rule_versions' - __table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),) + __tablename__ = 'freight_rpa_onhand_routing_rule_versions' + __table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_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) + rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_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): +class FreightRpaOnhandExternalMapping(Base): """库存源到外部系统仓库的映射。 freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件 @@ -374,18 +417,18 @@ class ShippingInventoryExternalMapping(Base): (in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。 """ - __tablename__ = 'shipping_inventory_external_mappings' + __tablename__ = 'freight_rpa_onhand_external_mappings' __table_args__ = ( Index( 'uq_shipping_inv_ext_map_src_default_enabled', - 'inventory_source_id', + '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_inv_ext_map_src_wh_enabled', - 'inventory_source_id', + 'source_id', 'freight_warehouse_id', unique=True, postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'), @@ -394,7 +437,7 @@ class ShippingInventoryExternalMapping(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_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) @@ -410,4 +453,4 @@ class ShippingInventoryExternalMapping(Base): 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') + source: Mapped[FreightRpaSource] = relationship(back_populates='external_mappings') diff --git a/backend/app/models/shipping_receipt_report.py b/backend/app/models/freight_rpa_inbound_report.py similarity index 66% rename from backend/app/models/shipping_receipt_report.py rename to backend/app/models/freight_rpa_inbound_report.py index b5b61bdf..47471aff 100644 --- a/backend/app/models/shipping_receipt_report.py +++ b/backend/app/models/freight_rpa_inbound_report.py @@ -1,9 +1,9 @@ """ -收料报表 RPA 的配置、运行、归档与通知投递持久化模型。 +backend/app/models/freight_rpa_inbound_report.py -用途:为独立收料排程保存站点级配置、每站点/仓库执行单元、原样归档文件及企微投递事实。 -依赖:库存站点、排程运行、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 -逻辑:模型只复用库存站点的连接资料,通过独立外键与唯一约束隔离库存快照、匹配和旧 RPA Worker 链路。 +用途:入站报表 RPA 的配置、运行、归档与通知投递持久化模型。 +依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 +逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。 """ from __future__ import annotations @@ -17,22 +17,22 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base -class ShippingReceiptReportConfig(Base): +class FreightRpaInboundReportConfig(Base): """库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。""" - __tablename__ = 'shipping_receipt_report_configs' + __tablename__ = 'freight_rpa_inbound_report_configs' __table_args__ = ( - UniqueConstraint('inventory_source_id', name='uq_shipping_receipt_report_configs_source'), + UniqueConstraint('source_id', name='uq_freight_rpa_inbound_report_configs_source'), ) id: Mapped[int] = mapped_column(primary_key=True) - inventory_source_id: Mapped[int] = mapped_column( - ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True, + source_id: Mapped[int] = mapped_column( + ForeignKey('freight_rpa_sources.id'), nullable=False, index=True, ) # 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。 # 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。 parsing_profile_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True, + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True, ) report_path_json: Mapped[dict[str, Any]] = mapped_column( JSON, default=dict, server_default=text("'{}'"), nullable=False, @@ -47,32 +47,32 @@ class ShippingReceiptReportConfig(Base): 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='receipt_report_config') - parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship() + source: Mapped['FreightRpaSource'] = relationship(back_populates='inbound_report_config') + parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship() -class ShippingReceiptRpaUnitRun(Base): +class FreightRpaInboundUnitRun(Base): """一次收料执行的站点或站点-Warehouse 不可重复执行单元。 schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。 """ - __tablename__ = 'shipping_receipt_rpa_unit_runs' + __tablename__ = 'freight_rpa_inbound_rpa_unit_runs' __table_args__ = ( - UniqueConstraint('callback_id', name='uq_shipping_receipt_rpa_unit_runs_callback'), + UniqueConstraint('callback_id', name='uq_freight_rpa_inbound_rpa_unit_runs_callback'), CheckConstraint( "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", - name='ck_shipping_receipt_rpa_unit_runs_status', + name='ck_freight_rpa_inbound_rpa_unit_runs_status', ), Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'), - Index('ix_shipping_receipt_unit_run_source_created', 'inventory_source_id', 'created_at'), + Index('ix_shipping_receipt_unit_run_source_created', 'source_id', 'created_at'), ) id: Mapped[int] = mapped_column(primary_key=True) schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) retry_of_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True, + ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True, ) source_code: Mapped[str] = mapped_column(String(64), nullable=False) connector_type: Mapped[str] = mapped_column(String(32), nullable=False) @@ -89,26 +89,26 @@ class ShippingReceiptRpaUnitRun(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id]) - inventory_source: Mapped['ShippingInventorySource'] = relationship() - retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id]) - files: Mapped[list['ShippingReceiptReportFile']] = relationship( + source: Mapped['FreightRpaSource'] = relationship() + retry_of: Mapped[Optional['FreightRpaInboundUnitRun']] = relationship(remote_side=[id]) + files: Mapped[list['FreightRpaInboundReportFile']] = relationship( back_populates='unit_run', cascade='all, delete-orphan', ) -class ShippingReceiptReportFile(Base): +class FreightRpaInboundReportFile(Base): """收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。""" - __tablename__ = 'shipping_receipt_report_files' + __tablename__ = 'freight_rpa_inbound_report_files' __table_args__ = ( - UniqueConstraint('unit_run_id', 'sha256', name='uq_shipping_receipt_report_files_unit_sha256'), - CheckConstraint("file_size >= 0", name='ck_shipping_receipt_report_files_size'), - Index('ix_shipping_receipt_report_files_unit', 'unit_run_id'), - Index('ix_shipping_receipt_report_files_expires', 'archive_expires_at', 'archive_deleted_at'), + UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_inbound_report_files_unit_sha256'), + CheckConstraint("file_size >= 0", name='ck_freight_rpa_inbound_report_files_size'), + Index('ix_freight_rpa_inbound_report_files_unit', 'unit_run_id'), + Index('ix_freight_rpa_inbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'), ) id: Mapped[int] = mapped_column(primary_key=True) - unit_run_id: Mapped[int] = mapped_column(ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=False, index=True) + unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=False, index=True) storage_provider: Mapped[str] = mapped_column(String(32), nullable=False) storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) storage_key: Mapped[str] = mapped_column(String(1024), nullable=False) @@ -125,35 +125,37 @@ class ShippingReceiptReportFile(Base): archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - unit_run: Mapped[ShippingReceiptRpaUnitRun] = relationship(back_populates='files') - deliveries: Mapped[list['ShippingReceiptNotificationDelivery']] = relationship( + unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files') + deliveries: Mapped[list['FreightRpaInboundNotificationDelivery']] = relationship( back_populates='report_file', cascade='all, delete-orphan', ) -class ShippingReceiptNotificationDelivery(Base): +class FreightRpaInboundNotificationDelivery(Base): """收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。""" - __tablename__ = 'shipping_receipt_notification_deliveries' + __tablename__ = 'freight_rpa_inbound_notification_deliveries' __table_args__ = ( - UniqueConstraint('idempotency_key', name='uq_shipping_receipt_notification_deliveries_idempotency'), - CheckConstraint("message_type IN ('file', 'summary')", name='ck_shipping_receipt_notification_deliveries_type'), + UniqueConstraint('idempotency_key', name='uq_freight_rpa_inbound_notification_deliveries_idempotency'), + CheckConstraint("message_type IN ('file', 'summary')", name='ck_freight_rpa_inbound_notification_deliveries_type'), CheckConstraint( "status IN ('pending', 'sending', 'success', 'failed')", - name='ck_shipping_receipt_notification_deliveries_status', + name='ck_freight_rpa_inbound_notification_deliveries_status', ), Index('ix_shipping_receipt_delivery_file_recipient', 'report_file_id', 'recipient_user_id'), Index('ix_shipping_receipt_delivery_unit_created', 'unit_run_id', 'created_at'), + # PostgreSQL 标识符上限 63。表名替换后的自动名是 64 字节,故用显式短名。 + Index('ix_fr_inbound_notif_deliveries_recipient_user_id', 'recipient_user_id'), ) id: Mapped[int] = mapped_column(primary_key=True) unit_run_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True, + ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True, ) report_file_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_report_files.id'), nullable=True, index=True, + ForeignKey('freight_rpa_inbound_report_files.id'), nullable=True, index=True, ) - recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True) + recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False) message_type: Mapped[str] = mapped_column(String(16), nullable=False) idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False) status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending') @@ -164,5 +166,5 @@ class ShippingReceiptNotificationDelivery(Base): 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) - unit_run: Mapped[Optional[ShippingReceiptRpaUnitRun]] = relationship(foreign_keys=[unit_run_id]) - report_file: Mapped[Optional[ShippingReceiptReportFile]] = relationship(back_populates='deliveries') + unit_run: Mapped[Optional[FreightRpaInboundUnitRun]] = relationship(foreign_keys=[unit_run_id]) + report_file: Mapped[Optional[FreightRpaInboundReportFile]] = relationship(back_populates='deliveries') diff --git a/backend/app/models/shipping_inventory_mapping.py b/backend/app/models/freight_rpa_onhand_mapping.py similarity index 69% rename from backend/app/models/shipping_inventory_mapping.py rename to backend/app/models/freight_rpa_onhand_mapping.py index dcc8f196..8945f5dd 100644 --- a/backend/app/models/shipping_inventory_mapping.py +++ b/backend/app/models/freight_rpa_onhand_mapping.py @@ -1,8 +1,8 @@ """ -models/shipping_inventory_mapping.py +backend/app/models/freight_rpa_onhand_mapping.py 用途:保存不可变库存字段映射版本。 -依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。 +依赖:FreightRpaOnhandReportFile、FreightRpaParsingProfile、Base。 逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。 """ @@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class ShippingInventoryMapping(Base): +class FreightRpaOnhandMapping(Base): """库存文件的不可变字段映射版本。""" - __tablename__ = 'shipping_inventory_mappings' + __tablename__ = 'freight_rpa_onhand_mappings' __table_args__ = ( - UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), + UniqueConstraint('onhand_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'), - Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'), + Index('ix_shipping_inventory_mapping_file_status', 'onhand_file_id', 'status'), ) id: Mapped[int] = mapped_column(Integer, primary_key=True) - inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False) + onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='CASCADE'), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active') - profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True) + profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id', ondelete='SET NULL'), nullable=True) mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id'), nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/freight_rpa_onhand_report_file.py b/backend/app/models/freight_rpa_onhand_report_file.py new file mode 100644 index 00000000..dceb2a78 --- /dev/null +++ b/backend/app/models/freight_rpa_onhand_report_file.py @@ -0,0 +1,123 @@ +""" +backend/app/models/freight_rpa_onhand_report_file.py + +用途:货代 RPA 抓回的在手报表文件。 +依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。 +逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy import ( + Boolean, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class FreightRpaOnhandReportFile(Base): + """货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。 + + 在手文件表归货代 RPA(s18 由 shipping_onhand_files 改名而来);列不改, + 仍含解析行、字段映射与快照状态,本阶段只改表名与指向它的外键。 + """ + + __tablename__ = 'freight_rpa_onhand_report_files' + __table_args__ = ( + Index('ix_freight_rpa_onhand_report_files_user_created', 'user_id', 'created_at'), + Index( + 'ix_freight_rpa_onhand_report_files_source_snapshot', + 'source_code', + 'warehouse_id', + 'snapshot_status', + 'exported_at', + ), + Index( + 'ix_freight_rpa_onhand_report_files_source_warehouse', + 'source_code', + 'warehouse_id', + ), + Index( + 'uq_freight_rpa_onhand_report_files_rpa_identity_ready', + 'rpa_run_no', + 'source_code', + 'warehouse_id', + 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 NOT NULL" + ), + sqlite_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" + ), + ), + # 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。 + Index( + 'uq_freight_rpa_onhand_report_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" + ), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + onhand_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) + user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) + source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + storage_path: Mapped[str] = mapped_column(String(500), nullable=False) + schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) + onhand_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + line_count: Mapped[int] = mapped_column(Integer, default=0) + 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) + 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) + source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) + exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) + rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) + source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) + invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), 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) + + links: Mapped[List['ShippingTaskOnhandLink']] = relationship( + 'ShippingTaskOnhandLink', + back_populates='inventory_file', + cascade='all, delete-orphan', + ) diff --git a/backend/app/models/shipping_task_inventory_rpa_attempts.py b/backend/app/models/freight_rpa_onhand_task_attempts.py similarity index 96% rename from backend/app/models/shipping_task_inventory_rpa_attempts.py rename to backend/app/models/freight_rpa_onhand_task_attempts.py index 4abbbd30..5633bbdb 100644 --- a/backend/app/models/shipping_task_inventory_rpa_attempts.py +++ b/backend/app/models/freight_rpa_onhand_task_attempts.py @@ -1,5 +1,5 @@ """ -models/shipping_task_inventory_rpa_attempts.py +backend/app/models/freight_rpa_onhand_task_attempts.py 用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。 依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。 @@ -47,10 +47,10 @@ PER_SOURCE_RPA_ATTEMPT_STATUSES = ( ) -class ShippingTaskInventoryRpaAttempt(Base): +class FreightRpaOnhandTaskAttempt(Base): """逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。""" - __tablename__ = 'shipping_task_inventory_rpa_attempts' + __tablename__ = 'freight_rpa_onhand_task_rpa_attempts' __table_args__ = ( # 三元组唯一:同一运行号同一源只允许一条记录 UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'), @@ -87,7 +87,7 @@ class ShippingTaskInventoryRpaAttempt(Base): trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) - inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + onhand_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) diff --git a/backend/app/models/in_transit_transfer.py b/backend/app/models/in_transit_transfer.py index ee497f15..74429c1a 100644 --- a/backend/app/models/in_transit_transfer.py +++ b/backend/app/models/in_transit_transfer.py @@ -5,7 +5,7 @@ 配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档 TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。 依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁); - source_file_id 外键指向 shipping_receipt_report_files(ShippingReceiptReport 原样归档,入站证据)。 + source_file_id 外键指向 freight_rpa_inbound_report_files(FreightRpaInboundReportFile 原样归档,入站证据)。 逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单; Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在 DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14); @@ -606,7 +606,7 @@ class TransferMovementLedger(Base): record_kind: Mapped[str] = mapped_column(String(16), nullable=False) # 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。 source_file_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_report_files.id', ondelete='SET NULL'), nullable=True, + ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True, ) file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -622,9 +622,9 @@ class TransferMovementLedger(Base): ) executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - # 溯源关系:档案行 → ShippingReceiptReport 原样归档文件(单向,不回挂; ShippingReceiptReportFile + # 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile # 不感知调拨域,避免跨域 back_populates 环)。 - source_file: Mapped[Optional['ShippingReceiptReportFile']] = relationship() + source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship() @event.listens_for(TransferAuditEvent, 'before_update') diff --git a/backend/app/models/job.py b/backend/app/models/job.py index df7ef9cd..fd6803c4 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -2,7 +2,7 @@ backend/app/models/job.py 用途:通用后台任务模型,承载跨业务域的异步任务执行状态。 -依赖:models.base.Base。 +依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。 逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。 """ @@ -149,7 +149,7 @@ class Job(Base): ForeignKey('shipping_process_gates.id'), nullable=True, index=True, ) candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True, + ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, index=True, ) fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 5fbad44b..b19233ba 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -1,7 +1,7 @@ """ backend/app/models/shipping.py -用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。 +用途:货代发货通知正式 Notice(shipping_notices)、事件、在手报表文件(freight_rpa_onhand_report_files,s18 起归 RPA,列仍含解析行与快照状态)、任务关联(shipping_task_onhand_links)、接入记录与文档/候选模型。 依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。 逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列; Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches); @@ -164,108 +164,15 @@ class ShippingTaskPurgeAudit(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) -class ShippingInventoryFile(Base): - """货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。""" - - __tablename__ = 'shipping_inventory_files' - __table_args__ = ( - Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'), - Index( - 'ix_shipping_inventory_files_source_snapshot', - 'source_code', - 'warehouse_id', - 'snapshot_status', - 'exported_at', - ), - Index( - 'ix_shipping_inventory_files_source_warehouse', - 'source_code', - 'warehouse_id', - ), - Index( - 'uq_shipping_inventory_files_rpa_identity_ready', - 'rpa_run_no', - 'source_code', - 'warehouse_id', - 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 NOT NULL" - ), - sqlite_where=text( - "snapshot_status = 'ready' AND rpa_run_no 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" - ), - ), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) - user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) - source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) - storage_path: Mapped[str] = mapped_column(String(500), nullable=False) - schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) - inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - line_count: Mapped[int] = mapped_column(Integer, default=0) - 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) - 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) - source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) - exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) - expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) - rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) - source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) - invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) - invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) - input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - operation_id: Mapped[Optional[str]] = mapped_column(String(128), 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) - - links: Mapped[List['ShippingTaskInventoryLink']] = relationship( - 'ShippingTaskInventoryLink', - back_populates='inventory_file', - cascade='all, delete-orphan', - ) - - -class ShippingTaskInventoryLink(Base): +class ShippingTaskOnhandLink(Base): """发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。""" - __tablename__ = 'shipping_task_inventory_links' + __tablename__ = 'shipping_task_onhand_links' __table_args__ = ( - Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'), - Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'), + Index('ix_shipping_task_onhand_links_task_active', 'task_id', 'is_active'), + Index('ix_shipping_task_onhand_links_file_active', 'onhand_file_id', 'is_active'), Index( - 'ix_shipping_task_inventory_links_task_source', + 'ix_shipping_task_onhand_links_task_source', 'task_id', 'matched_source_code', ), @@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base): id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True) - inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True) + onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), index=True) link_role: Mapped[str] = mapped_column(String(32), default='member') access_mode: Mapped[str] = mapped_column(String(32), default='readonly') is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True) @@ -283,8 +190,8 @@ class ShippingTaskInventoryLink(Base): 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) - preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True) - source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True) + preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', use_alter=True), nullable=True, index=True) + source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_source_attempts.id', use_alter=True), nullable=True, index=True) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) @@ -294,10 +201,10 @@ class ShippingTaskInventoryLink(Base): linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id]) - inventory_file: Mapped['ShippingInventoryFile'] = relationship( - 'ShippingInventoryFile', + inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship( + 'FreightRpaOnhandReportFile', back_populates='links', - foreign_keys=[inventory_file_id], + foreign_keys=[onhand_file_id], ) diff --git a/backend/app/models/shipping_excel_template.py b/backend/app/models/shipping_excel_template.py index 91a069cf..f0b841c5 100644 --- a/backend/app/models/shipping_excel_template.py +++ b/backend/app/models/shipping_excel_template.py @@ -2,7 +2,7 @@ models/shipping_excel_template.py 用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。 -依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。 +依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。 逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和; co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。 """ @@ -44,7 +44,7 @@ class ShippingExcelTemplate(Base): 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') + sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='excel_template') class ShippingExportArtifact(Base): @@ -62,8 +62,8 @@ class ShippingExportArtifact(Base): 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) + inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False) + inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_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) diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index d4323b31..68800cf6 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -2,7 +2,7 @@ backend/app/models/shipping_fulfillment.py 用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。 -依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。 +依赖:冻结订单 Snapshot、freight_rpa_onhand_report_files、导出 Artifact 与 SQLAlchemy Base;核验表 shipping_notice_onhand_verifications / shipping_notice_onhand_verification_lines;Notice 主表 shipping_notices。 逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。 """ @@ -46,53 +46,53 @@ class ShippingReservation(Base): updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) -class ShippingInventoryVerification(Base): +class ShippingOnhandVerification(Base): """一次任务库存核验的不可变轮次,绑定当时有效库存快照。""" - __tablename__ = 'shipping_notice_inventory_verifications' + __tablename__ = 'shipping_notice_onhand_verifications' __table_args__ = ( CheckConstraint( "status IN ('completed', 'expired', 'superseded')", - name='ck_shipping_notice_inventory_verifications_status', + name='ck_shipping_notice_onhand_verifications_status', ), - Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'), + Index('ix_shipping_notice_onhand_verifications_task_created', 'task_id', 'created_at'), ) id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) - inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) + onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) + preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id'), nullable=True) status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed') result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship( - back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id', + lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship( + back_populates='verification', cascade='all, delete-orphan', order_by='ShippingOnhandVerificationLine.id', ) -class ShippingInventoryVerificationLine(Base): +class ShippingOnhandVerificationLine(Base): """一个预约单在一轮库存中的需求、可用数量和确定性结果。""" - __tablename__ = 'shipping_notice_inventory_verification_lines' + __tablename__ = 'shipping_notice_onhand_verification_lines' __table_args__ = ( UniqueConstraint( 'verification_id', 'reservation_id', - name='uq_shipping_notice_inventory_verification_lines_reservation', + name='uq_shipping_notice_onhand_verification_lines_reservation', ), CheckConstraint( "status IN ('available', 'shortage', 'invalid')", - name='ck_shipping_notice_inventory_verification_lines_status', + name='ck_shipping_notice_onhand_verification_lines_status', ), ) id: Mapped[int] = mapped_column(primary_key=True) verification_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False, + ForeignKey('shipping_notice_onhand_verifications.id', ondelete='CASCADE'), nullable=False, ) reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False) required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False) @@ -100,7 +100,7 @@ class ShippingInventoryVerificationLine(Base): status: Mapped[str] = mapped_column(String(16), nullable=False) detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines') + verification: Mapped['ShippingOnhandVerification'] = relationship(back_populates='lines') class ShippingExportArtifactLine(Base): @@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base): ) reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False) verification_line_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False, + ForeignKey('shipping_notice_onhand_verification_lines.id'), nullable=False, ) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping_notice_line.py b/backend/app/models/shipping_notice_line.py index b2d4f9d3..997f3ca0 100644 --- a/backend/app/models/shipping_notice_line.py +++ b/backend/app/models/shipping_notice_line.py @@ -2,7 +2,7 @@ backend/app/models/shipping_notice_line.py 用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。 -依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。 +依赖:shipping_notices、shipping_order_snapshot_lines、freight_rpa_onhand_report_files、SQLAlchemy Base。 逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。 """ @@ -47,7 +47,7 @@ class ShippingNoticeLine(Base): # 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。 inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) inventory_file_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, index=True, ) inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_onhand_match.py similarity index 84% rename from backend/app/models/shipping_notice_line_inventory_match.py rename to backend/app/models/shipping_notice_line_onhand_match.py index 32625f87..e4fdc953 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_onhand_match.py @@ -1,9 +1,9 @@ """ -models/shipping_notice_line_inventory_match.py +models/shipping_notice_line_onhand_match.py 用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。 -依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。 -逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史; +依赖:shipping_notices、freight_rpa_onhand_report_files、shipping_order_review_cases(可选关联)。 +逻辑:由 onhand_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史; is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。 """ @@ -30,15 +30,15 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class ShippingNoticeLineInventoryMatch(Base): +class ShippingNoticeLineOnhandMatch(Base): """一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。""" - __tablename__ = 'shipping_notice_line_inventory_matches' + __tablename__ = 'shipping_notice_line_onhand_matches' __table_args__ = ( UniqueConstraint( 'task_id', 'snapshot_line_id', - 'inventory_snapshot_id', + 'onhand_snapshot_id', name='uq_shipping_notice_line_inv_match_task_line_snap', ), # 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。 @@ -51,7 +51,7 @@ class ShippingNoticeLineInventoryMatch(Base): ), Index('ix_shipping_notice_line_inv_match_task', 'task_id'), Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'), - Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'), + Index('ix_shipping_notice_line_inv_match_snapshot', 'onhand_snapshot_id'), CheckConstraint( "match_result IN (" "'matched', 'not_found', 'result_missing', 'preparing', " @@ -60,7 +60,7 @@ class ShippingNoticeLineInventoryMatch(Base): name='ck_shipping_notice_line_inv_match_result', ), CheckConstraint( - "inventory_status IN (" + "onhand_status IN (" "'ready', 'preparing', 'mapping_failed', 'source_conflict', " "'unavailable', 'invalid_key', 'invalid'" ")", @@ -85,22 +85,22 @@ class ShippingNoticeLineInventoryMatch(Base): line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True, index=True, ) candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) candidate_line_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'), + ForeignKey('shipping_onhand_candidate_lines.id', ondelete='SET NULL'), nullable=True, index=True, ) - inventory_snapshot_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), + onhand_snapshot_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, ) match_result: Mapped[str] = mapped_column(String(32), nullable=False) - inventory_status: Mapped[str] = mapped_column(String(32), nullable=False) + onhand_status: Mapped[str] = mapped_column(String(32), nullable=False) required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) @@ -111,7 +111,7 @@ class ShippingNoticeLineInventoryMatch(Base): part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true') matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow) detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) @@ -146,7 +146,7 @@ class ShippingNoticeLineInventoryMatch(Base): invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) - superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True) + superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_onhand_matches.id'), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True) - verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True) + mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id', ondelete='SET NULL'), nullable=True, index=True) + verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id', ondelete='SET NULL'), nullable=True, index=True) diff --git a/backend/app/models/shipping_inventory_candidates.py b/backend/app/models/shipping_onhand_candidates.py similarity index 86% rename from backend/app/models/shipping_inventory_candidates.py rename to backend/app/models/shipping_onhand_candidates.py index b9e8059f..eefa8cbd 100644 --- a/backend/app/models/shipping_inventory_candidates.py +++ b/backend/app/models/shipping_onhand_candidates.py @@ -1,12 +1,12 @@ """ -models/shipping_inventory_candidates.py +models/shipping_onhand_candidates.py 用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。 - InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), + ShippingOnhandCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), 同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存 同一时刻的完整不可变副本,用于审计与回滚。 依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、 - ShippingInventoryRoutingRule(可选外键,路由规则版本)。 + FreightRpaOnhandRoutingRule(可选外键,路由规则版本)。 逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结; input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等); source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。 @@ -39,7 +39,7 @@ def _utc_now() -> datetime: return datetime.utcnow() -class ShippingInventoryCandidateSet(Base): +class ShippingOnhandCandidateSet(Base): """ 库存候选集合(冻结真相根)。 @@ -48,7 +48,7 @@ class ShippingInventoryCandidateSet(Base): 二者至少一个非空(CheckConstraint 强制)。 """ - __tablename__ = 'shipping_inventory_candidate_sets' + __tablename__ = 'shipping_onhand_candidate_sets' __table_args__ = ( CheckConstraint( 'task_id IS NOT NULL OR review_case_id IS NOT NULL', @@ -98,7 +98,7 @@ class ShippingInventoryCandidateSet(Base): ) superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) superseded_by_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True, + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True, ) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) @@ -111,19 +111,19 @@ class ShippingInventoryCandidateSet(Base): ) remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship( + sources: Mapped[list['ShippingOnhandCandidateSource']] = relationship( back_populates='candidate_set', cascade='all, delete-orphan', - order_by='ShippingInventoryCandidateSource.candidate_order', + order_by='ShippingOnhandCandidateSource.candidate_order', ) - lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship( + lines: Mapped[list['ShippingOnhandCandidateLine']] = relationship( back_populates='candidate_set', cascade='all, delete-orphan', - order_by='ShippingInventoryCandidateLine.line_no', + order_by='ShippingOnhandCandidateLine.line_no', ) -class ShippingInventoryCandidateSource(Base): +class ShippingOnhandCandidateSource(Base): """ 任务级候选库存源(Set 的子级)。 @@ -132,7 +132,7 @@ class ShippingInventoryCandidateSource(Base): candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。 """ - __tablename__ = 'shipping_inventory_candidate_sources' + __tablename__ = 'shipping_onhand_candidate_sources' __table_args__ = ( UniqueConstraint( 'candidate_set_id', 'source_code', @@ -151,13 +151,13 @@ class ShippingInventoryCandidateSource(Base): id: Mapped[int] = mapped_column(primary_key=True) candidate_set_id: Mapped[int] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False, ) source_code: Mapped[str] = mapped_column(String(64), nullable=False) candidate_order: Mapped[int] = mapped_column(Integer, nullable=False) candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule') routing_rule_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True, + ForeignKey('freight_rpa_onhand_routing_rules.id', ondelete='SET NULL'), nullable=True, ) routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -170,12 +170,12 @@ class ShippingInventoryCandidateSource(Base): DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, ) - candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( + candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship( back_populates='sources', ) -class ShippingInventoryCandidateLine(Base): +class ShippingOnhandCandidateLine(Base): """ 行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。 @@ -185,7 +185,7 @@ class ShippingInventoryCandidateLine(Base): part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。 """ - __tablename__ = 'shipping_inventory_candidate_lines' + __tablename__ = 'shipping_onhand_candidate_lines' __table_args__ = ( UniqueConstraint( 'candidate_set_id', 'line_no', @@ -199,7 +199,7 @@ class ShippingInventoryCandidateLine(Base): id: Mapped[int] = mapped_column(primary_key=True) candidate_set_id: Mapped[int] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False, ) line_no: Mapped[int] = mapped_column(Integer, nullable=False) source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -215,6 +215,6 @@ class ShippingInventoryCandidateLine(Base): DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, ) - candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( + candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship( back_populates='lines', ) diff --git a/backend/app/models/shipping_inventory_preparation.py b/backend/app/models/shipping_onhand_preparation.py similarity index 77% rename from backend/app/models/shipping_inventory_preparation.py rename to backend/app/models/shipping_onhand_preparation.py index 786f0574..8ee6d471 100644 --- a/backend/app/models/shipping_inventory_preparation.py +++ b/backend/app/models/shipping_onhand_preparation.py @@ -1,8 +1,8 @@ """ -models/shipping_inventory_preparation.py +models/shipping_onhand_preparation.py 用途:表达一次任务级库存准备轮次及逐库存源状态。 -依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。 +依赖:ShippingOrderTask、RecoveryPlan、FreightRpaOnhandTaskAttempt、FreightRpaOnhandReportFile、ShippingTaskOnhandLink、Base。 逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。 """ @@ -17,10 +17,10 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base -class ShippingInventoryPreparationAttempt(Base): +class ShippingOnhandPreparationAttempt(Base): """一次任务级库存准备恢复轮次。""" - __tablename__ = 'shipping_inventory_preparation_attempts' + __tablename__ = 'shipping_onhand_preparation_attempts' __table_args__ = ( UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'), CheckConstraint( @@ -38,7 +38,7 @@ class ShippingInventoryPreparationAttempt(Base): attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True) + candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True) input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) @@ -46,13 +46,13 @@ class ShippingInventoryPreparationAttempt(Base): started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan') + source_attempts = relationship('ShippingOnhandPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan') -class ShippingInventoryPreparationSourceAttempt(Base): +class ShippingOnhandPreparationSourceAttempt(Base): """准备轮次中某个库存源的业务状态。""" - __tablename__ = 'shipping_inventory_preparation_source_attempts' + __tablename__ = 'shipping_onhand_preparation_source_attempts' __table_args__ = ( UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'), CheckConstraint( @@ -63,17 +63,17 @@ class ShippingInventoryPreparationSourceAttempt(Base): ) id: Mapped[int] = mapped_column(Integer, primary_key=True) - preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False) + preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='CASCADE'), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False) warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) - rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True) - inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True) - task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True) + rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_task_rpa_attempts.id', ondelete='SET NULL'), nullable=True) + onhand_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True) + task_onhand_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_onhand_links.id', ondelete='SET NULL'), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), 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) - preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts') + preparation_attempt = relationship('ShippingOnhandPreparationAttempt', back_populates='source_attempts') diff --git a/backend/app/models/shipping_order_review_line_decision.py b/backend/app/models/shipping_order_review_line_decision.py index fb83a1e2..a770bbe0 100644 --- a/backend/app/models/shipping_order_review_line_decision.py +++ b/backend/app/models/shipping_order_review_line_decision.py @@ -32,8 +32,8 @@ class ShippingOrderReviewLineDecision(Base): ), CheckConstraint( "decision_code IN (" - "'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', " - "'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'" + "'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', " + "'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'" ")", name='ck_shipping_review_line_decisions_code', ), diff --git a/backend/app/models/shipping_order_task.py b/backend/app/models/shipping_order_task.py index 68338d0c..dfaa9d62 100644 --- a/backend/app/models/shipping_order_task.py +++ b/backend/app/models/shipping_order_task.py @@ -2,7 +2,7 @@ backend/app/models/shipping_order_task.py 用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。 -依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。 +依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_onhand_candidate_sets。 逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。 页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。 """ @@ -104,7 +104,7 @@ class ShippingOrderTask(Base): ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True, ) active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True, + ForeignKey('shipping_onhand_candidate_sets.id', use_alter=True), nullable=True, index=True, ) step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) active_process_execution_id: Mapped[Optional[int]] = mapped_column( diff --git a/backend/app/models/shipping_process_gate.py b/backend/app/models/shipping_process_gate.py index 33ef80fc..1dbf9f20 100644 --- a/backend/app/models/shipping_process_gate.py +++ b/backend/app/models/shipping_process_gate.py @@ -2,7 +2,7 @@ models/shipping_process_gate.py 用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。 -依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。 +依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job、shipping_onhand_candidate_sets;状态枚举与 process_gate_contract 对齐。 逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。 由领域服务独占写入;Job 仅调度。 co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。 @@ -78,7 +78,7 @@ class ShippingProcessExecution(Base): ) # 绑定候选版本,防止旧 callback/job 写入新候选链。 candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, + ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, ) execution_revision: Mapped[int] = mapped_column( Integer, nullable=False, default=1, server_default='1', diff --git a/backend/app/models/shipping_temporary_inventory.py b/backend/app/models/shipping_temporary_onhand.py similarity index 90% rename from backend/app/models/shipping_temporary_inventory.py rename to backend/app/models/shipping_temporary_onhand.py index 3ad02321..cf0ccdd4 100644 --- a/backend/app/models/shipping_temporary_inventory.py +++ b/backend/app/models/shipping_temporary_onhand.py @@ -1,8 +1,8 @@ """ -models/shipping_temporary_inventory.py +models/shipping_temporary_onhand.py 用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。 -依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。 +依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、freight_rpa_onhand_structure_analyses。 逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检; co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id; 本表不代表库存站点配置,也不代表生产库存快照。 @@ -19,12 +19,12 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class ShippingTemporaryInventorySession(Base): +class ShippingTemporaryOnhandSession(Base): """对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。""" - __tablename__ = 'shipping_temporary_inventory_sessions' + __tablename__ = 'shipping_temporary_onhand_sessions' __table_args__ = ( - UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'), + UniqueConstraint('session_no', name='uq_shipping_temporary_onhand_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'), @@ -37,7 +37,7 @@ class ShippingTemporaryInventorySession(Base): 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, + ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True, ) task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True) declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate') diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_onhand_admin_service.py similarity index 69% rename from backend/app/services/admin/shipping_inventory_service.py rename to backend/app/services/admin/shipping_onhand_admin_service.py index 7e2a1b9d..29a8839d 100644 --- a/backend/app/services/admin/shipping_inventory_service.py +++ b/backend/app/services/admin/shipping_onhand_admin_service.py @@ -1,9 +1,14 @@ """ -services/admin/shipping_inventory_service.py +services/admin/shipping_onhand_admin_service.py -用途:管理库存源、RPA Profile、路由规则和外部系统映射主数据。 -依赖:db、库存配置模型、凭据加密、Source/Profile 校验、统一 AppError。 +用途:管理库存源、RPA Profile、在手报表配置、路由规则和外部系统映射主数据。 +依赖:db、库存配置模型(含 s18 起的 FreightRpaOnhandReportConfig 配置行)、凭据加密、 + Source/Profile 校验、统一 AppError。 逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。 + s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 一对一配置行 + (save_source 载荷内嵌 onhand_report_config 时经 _apply_onhand_report_config 写行), + 站点行只保留连接、模板绑定、仓库模式与启停;启用门禁由 + assert_onhand_source_can_enable 在服务层执行(PostgreSQL CHECK 不能跨表)。 """ from __future__ import annotations @@ -14,22 +19,22 @@ 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, ShippingNotice, + FreightRpaOnhandExternalMapping, FreightRpaOnhandReportFile, FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition, + FreightRpaOnhandRoutingRuleVersion, FreightRpaSource, FreightRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice, ShippingOrderField, - ShippingInventoryParsingProfile, - ShippingNoticeLine, ShippingNoticeLineInventoryMatch, + FreightRpaParsingProfile, + ShippingNoticeLine, ShippingNoticeLineOnhandMatch, ShippingExcelTemplate, - ShippingInventorySourceParsingBindingAudit, - ShippingReceiptReportConfig, + FreightRpaSourceParsingBindingAudit, + FreightRpaInboundReportConfig, FreightRpaOnhandReportConfig, ) from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.freight_rpa.common.credential_crypto import encrypt_credential -from app.services.shipping_notice.inventory_source_repository import validate_source_profile +from app.services.shipping_notice.onhand_source_repository import validate_source_profile from app.services.shipping_notice.upload_config_validation import validate_upload_config 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 +from app.services.shipping_notice.onhand_routing_engine import ALLOWED_ACTIONS +from app.services.shipping_notice import onhand_parsing_profile from app.services.shipping_notice.order_schema import service as order_schema_service @@ -62,7 +67,7 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]: """ value = data.get(field, {}) if not isinstance(value, dict): - raise ValidationError(f'{field} must be an object', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') return dict(value) @@ -84,19 +89,19 @@ def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> d """校验 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') + raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_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)}, + code='SHIPPING.ONHAND_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', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', ) return {key: normalized[key] for key in allowed if normalized.get(key)} @@ -105,7 +110,7 @@ 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') + raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') result: list[dict[str, Any]] = [] seen_names: set[str] = set() allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'} @@ -113,7 +118,7 @@ def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: 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}, + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index}, ) name = str(item.get('name') or '').strip() mode = str(item.get('mode') or 'single').strip().lower() @@ -121,16 +126,16 @@ def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: 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') + raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_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') + raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_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') + raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_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') + raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_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') + raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') parameter: dict[str, Any] = { 'name': name, 'mode': mode, 'values': normalized_values, 'required': required, 'select_all': select_all, @@ -138,14 +143,14 @@ def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: 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') + raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') parameter['joiner'] = joiner seen_names.add(name.lower()) result.append(parameter) return result -def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]: +def _profile_payload(profile: FreightRpaProfile) -> 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, @@ -168,15 +173,15 @@ def _iso(value: datetime | None) -> str | None: def list_profiles() -> list[dict[str, Any]]: """列出 Profile 元数据,不返回可恢复的凭据。""" - return [_profile_payload(item) for item in ShippingRpaProfile.query.order_by(ShippingRpaProfile.profile_code).all()] + return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()] def delete_profile(profile_id: int) -> None: """删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。""" - profile = db.session.get(ShippingRpaProfile, profile_id) + profile = db.session.get(FreightRpaProfile, 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(): + if FreightRpaSource.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() @@ -184,10 +189,10 @@ def delete_profile(profile_id: int) -> None: 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 + profile = db.session.get(FreightRpaProfile, 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 or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={}) # 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version, # upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。 prev_non_upload = ( @@ -237,26 +242,42 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int return _profile_payload(profile) -def _source_payload(source: ShippingInventorySource) -> dict[str, Any]: - """序列化库存站点及其是否满足正式启用前置条件。""" +def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]: + """序列化站点一对一在手报表配置行,不透传解析方案定义。""" + return { + 'id': config.id, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'parsing_profile_id': config.parsing_profile_id, + } + + +def _source_payload(source: FreightRpaSource) -> dict[str, Any]: + """序列化库存站点及其是否满足正式启用前置条件。 + + s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺, + 改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。 + """ 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 [], + 'onhand_report_config': ( + _onhand_report_config_payload(source.onhand_report_config) + if source.onhand_report_config is not None else None + ), '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 _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]: +def _receipt_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]: """序列化独立收料配置,禁止把库存路径或凭据透传至管理端。""" profile = config.parsing_profile return { - 'id': config.id, 'inventory_source_id': config.inventory_source_id, + 'id': config.id, 'source_id': config.source_id, 'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [], # 入站解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。 @@ -282,7 +303,7 @@ def _validate_inbound_profile_binding(profile_id: Any) -> int | None: """ if profile_id is None or str(profile_id).strip() == '': return None - profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id)) + profile = db.session.get(FreightRpaParsingProfile, int(profile_id)) if profile is None or profile.status != 'published' or profile.purpose != 'inbound': raise ValidationError( 'Inbound parsing profile must be published with purpose inbound', @@ -292,7 +313,7 @@ def _validate_inbound_profile_binding(profile_id: Any) -> int | None: def _validate_receipt_report_config( - source: ShippingInventorySource, data: dict[str, Any], + source: FreightRpaSource, data: dict[str, Any], ) -> tuple[dict[str, str], list[dict[str, Any]]]: """规范收料配置,与库存同构:路径+查询条件;日期禁填。 @@ -328,24 +349,24 @@ def _validate_receipt_report_config( def get_receipt_report_config(source_id: int) -> dict[str, Any] | None: """读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none() + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none() return _receipt_report_config_payload(config) if config else None def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """保存站点内独立收料配置并追加配置前后快照审计,不写入库存 Source 字段。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') path, parameters = _validate_receipt_report_config(source, data) - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none() + config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none() before = _receipt_report_config_payload(config) if config else None is_new = config is None if config is None: - config = ShippingReceiptReportConfig(inventory_source_id=source.id) + config = FreightRpaInboundReportConfig(source_id=source.id) config.created_by = actor_id db.session.add(config) else: @@ -357,37 +378,173 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id db.session.flush() after = _receipt_report_config_payload(config) append_shipping_audit_event( - event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config', + event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config', aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update', result='success', before=before, after=after, - metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type, + metadata={'source_id': source.id, 'connector_type': source.connector_type, 'parsing_profile_id': config.parsing_profile_id}, ) db.session.commit() return after -def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]: - """冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。""" +def _validate_onhand_profile_binding(profile_id: Any) -> int | None: + """校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。 + + Args: + profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。 + + Returns: + int | None: 规整后的方案 id 或 None。 + + Raises: + ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand + (fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。 + """ + raw = str(profile_id).strip() if profile_id is not None else '' + if raw in {'', '0'}: + return None + if not raw.isdigit(): + raise ValidationError( + 'Onhand parsing profile must be published with purpose onhand', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + profile = db.session.get(FreightRpaParsingProfile, int(raw)) + if profile is None or profile.status != 'published' or profile.purpose != 'onhand': + raise ValidationError( + 'Onhand parsing profile must be published with purpose onhand', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + return profile.id + + +def _apply_onhand_report_config( + source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None, +) -> FreightRpaOnhandReportConfig: + """把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。 + + 核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话; + 校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。 + 报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域, + 管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。 + + Args: + source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。 + data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。 + actor_id: 当前管理员主键,仅写审计字段。 + + Returns: + FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。 + """ + # [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。 + report_path = _json_object(data, 'report_path_json') + # DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整); + # 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。 + if source.connector_type != 'dbs' and report_path: + raise ValidationError( + 'Only DBS inventory sources can define report_path_json', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', + ) + parameters = _validate_query_parameters(data) + parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id')) + # [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。 + config = source.onhand_report_config + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.report_path_json = report_path + config.query_parameters_json = parameters + config.parsing_profile_id = parsing_profile_id + config.updated_by = actor_id + return config + + +def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。 + + 核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉 + 启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。 + + Args: + source_id: 库存站点主键,必须已存在。 + data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。 + actor_id: 当前管理员主键,仅写审计字段。 + + Returns: + dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。 + + Raises: + NotFoundError: 站点不存在。 + ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。 + """ + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + config = _apply_onhand_report_config(source, data, actor_id=actor_id) + # 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。 + assert_onhand_source_can_enable(source) + db.session.commit() + return _onhand_report_config_payload(config) + + +def assert_onhand_source_can_enable(source: FreightRpaSource) -> None: + """启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。 + + 【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、 + 保存在手配置(save_onhand_report_config 拆绑定前)时调用; + PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。 + + Args: + source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。 + + Returns: + None: 门禁通过(站点未启用时恒通过)。 + + Raises: + ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板, + 统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。 + """ + if not source.enabled: + return + config = source.onhand_report_config + if config is None or not config.parsing_profile_id or not source.excel_template_id: + raise ValidationError( + 'Enabled inventory source requires onhand report config, parsing profile and excel template', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + + +def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]: + """冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。 + + s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。 + """ + config = source.onhand_report_config return { 'source_id': source.id, 'source_code': source.source_code, 'enabled': bool(source.enabled), - 'parsing_profile_id': source.parsing_profile_id, - 'parsing_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None, + 'parsing_profile_id': config.parsing_profile_id if config is not None else None, + 'parsing_profile_checksum': ( + config.parsing_profile.checksum + if config is not None and config.parsing_profile is not None else None + ), 'excel_template_id': source.excel_template_id, 'config_version': source.config_version, } -def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None: +def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None: """校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。""" if profile.status != 'published': - raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {} if not mapping: - raise ValidationError('Published parsing profile is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') template = source.excel_template if template is None: return @@ -405,7 +562,7 @@ def _validate_source_parsing_binding(source: ShippingInventorySource, profile: S if missing_fields: raise ValidationError( 'Parsing profile does not provide all inventory fields required by the excel template', - code='SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields}, + code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields}, ) @@ -446,26 +603,36 @@ def bind_source_parsing_profile( normalized_profile_id = int(profile_id) except (TypeError, ValueError) as exc: raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc - profile = db.session.get(ShippingInventoryParsingProfile, normalized_profile_id) + profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') - sources = [db.session.get(ShippingInventorySource, source_id) for source_id in normalized_ids] + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') + sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids] if any(source is None for source in sources): - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') typed_sources = [source for source in sources if source is not None] # [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。 for source in typed_sources: _validate_source_parsing_binding(source, profile) for source in typed_sources: before = _binding_snapshot(source) - previous_profile_id = source.parsing_profile_id - source.parsing_profile = profile + # s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。 + config = source.onhand_report_config + previous_profile_id = config.parsing_profile_id if config is not None else None + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.parsing_profile_id = profile.id + config.updated_by = actor_id source.updated_by = actor_id + # 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。 source.config_version += 1 db.session.flush() - db.session.add(ShippingInventorySourceParsingBindingAudit( - inventory_source_id=source.id, previous_parsing_profile_id=previous_profile_id, - parsing_profile_id=profile.id, operation=operation, reason=normalized_reason, actor_id=actor_id, + db.session.add(FreightRpaSourceParsingBindingAudit( + source_id=source.id, previous_parsing_profile_id=previous_profile_id, + parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id, source_config_version_before=before['config_version'], source_config_version_after=source.config_version, before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source), )) @@ -475,11 +642,11 @@ def bind_source_parsing_profile( def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]: """读取库存站点解析绑定审计,仅返回配置快照和操作者标识。""" - if db.session.get(ShippingInventorySource, source_id) is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - rows = ShippingInventorySourceParsingBindingAudit.query.filter_by( - inventory_source_id=source_id, - ).order_by(ShippingInventorySourceParsingBindingAudit.id.desc()).all() + if db.session.get(FreightRpaSource, source_id) is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + rows = FreightRpaSourceParsingBindingAudit.query.filter_by( + source_id=source_id, + ).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all() return [{ 'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id, 'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id, @@ -492,27 +659,27 @@ def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]: def list_sources() -> list[dict[str, Any]]: """列出库存源及其稳定业务配置。""" - return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()] + return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()] def delete_source(source_id: int) -> None: """删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0 + has_snapshot = FreightRpaOnhandReportFile.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 rule in FreightRpaOnhandRoutingRule.query.all() for candidates in [(rule.action_payload_json or {}).get('source_codes', [])] if isinstance(candidates, list) ) has_task = db.session.query(ShippingNoticeLine.id).filter( ShippingNoticeLine.inventory_source_code == source_code, - ).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter( - ShippingNoticeLineInventoryMatch.inventory_source_code == source_code, + ).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter( + ShippingNoticeLineOnhandMatch.source_code == source_code, ).first() is not None has_export_run = any( source_code in {str(code).strip().upper() for code in source_codes} @@ -521,15 +688,15 @@ def delete_source(source_id: int) -> None: 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') + raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED') db.session.delete(source) db.session.commit() -def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]: +def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]: """投影库存快照的管理端只读行,不暴露存储路径或库存明细。""" return { - 'id': snapshot.id, 'inventory_file_no': snapshot.inventory_file_no, + 'id': snapshot.id, 'inventory_file_no': snapshot.onhand_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, @@ -543,8 +710,8 @@ def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]: def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]: """列出最新库存快照,供管理员确认当前可用的库存文件。""" - rows = ShippingInventoryFile.query.order_by( - ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(), + rows = FreightRpaOnhandReportFile.query.order_by( + FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(), ).limit(max(1, min(limit, 200))).all() return [_snapshot_payload(row) for row in rows] @@ -563,22 +730,22 @@ def get_snapshot_download(snapshot_id: int) -> tuple[str, str]: """ from pathlib import Path - snapshot = db.session.get(ShippingInventoryFile, snapshot_id) + snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id) if snapshot is None: - raise NotFoundError('Inventory snapshot not found', code='SHIPPING.INVENTORY_SNAPSHOT_NOT_FOUND') + raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_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"}') + raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND') + filename = str(snapshot.source_file_name or f'{snapshot.onhand_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), + file_rows = FreightRpaOnhandReportFile.query.filter( + FreightRpaOnhandReportFile.rpa_run_no.is_not(None), ).order_by( - ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(), + FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(), ).limit(max(1, min(limit, 200))).all() records = [_snapshot_payload(row) for row in file_rows] known_identities = { @@ -636,10 +803,12 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]: return records[:max(1, min(limit, 200))] -def _template_validation_missing(source: ShippingInventorySource) -> list[str]: +def _template_validation_missing(source: FreightRpaSource) -> list[str]: """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" template = source.excel_template - profile = source.parsing_profile + # s18 起解析方案绑定取自 onhand_report_config 配置行。 + config = source.onhand_report_config + profile = config.parsing_profile if config is not None else None if template is None or profile is None: return [] definition = template.definition_json if isinstance(template.definition_json, dict) else {} @@ -669,13 +838,16 @@ def _activation_check( } -def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]: +def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]: """构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。 测试导出不再参与启用门禁;启停由管理员显式开关完成。 """ profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled) - parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published' + # s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。 + config = source.onhand_report_config + parsing_profile = config.parsing_profile if config is not None else None + parsing_ready = parsing_profile is not None and parsing_profile.status == 'published' template_ready = source.excel_template is not None and source.excel_template.status == 'published' template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False return [ @@ -685,7 +857,7 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, ), _activation_check( 'parsing_profile', passed=parsing_ready, action='configure_parsing_profile', - evidence={'profile_id': source.parsing_profile_id, 'published': parsing_ready}, + evidence={'profile_id': parsing_profile.id if parsing_profile is not None else None, 'published': parsing_ready}, ), _activation_check( 'excel_template', passed=template_ready, action='configure_excel_template', @@ -698,7 +870,7 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, ] -def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]: +def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]: """返回库存站点启用硬门槛的结构化结果。 Args: @@ -719,14 +891,14 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: """启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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', + code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED', details=status, ) source.enabled = True @@ -737,9 +909,9 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: """停用库存站点,保留其解析方案和历史运行审计。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') source.enabled = False source.updated_by = actor_id db.session.commit() @@ -750,15 +922,20 @@ 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 + """保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。 + + s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id / + excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案 + 绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。 + """ + source = db.session.get(FreightRpaSource, 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') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_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) + profile = db.session.get(FreightRpaProfile, 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) @@ -772,32 +949,21 @@ def save_source( '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 = source or FreightRpaSource( 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.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400) source.enabled = enabled source.updated_by = actor_id @@ -806,16 +972,36 @@ def save_source( if is_new: source.created_by = actor_id db.session.add(source) + # [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError + # (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。 + if enabled and excel_template is None: + raise ValidationError( + 'published excel_template_id is required', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + try: + # flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。 + db.session.flush() + except Exception as exc: + db.session.rollback() + raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc + # [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。 + config_data = data.get('onhand_report_config') + if isinstance(config_data, dict): + _apply_onhand_report_config(source, config_data, actor_id=actor_id) + # [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。 + if enabled: + assert_onhand_source_can_enable(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 + raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc return _source_payload(source) -def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]: +def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> 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, @@ -832,47 +1018,47 @@ def _validate_rule_condition_expected(operator: str, value: Any) -> Any: 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') + raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_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') + raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_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 + raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc if length < 0: - raise ValidationError('Length must not be negative', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_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') + raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_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()] + return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()] def delete_draft_rule(rule_id: int) -> None: """删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。""" - rule = db.session.get(ShippingInventoryRoutingRule, rule_id) + rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id) if rule is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') if rule.status != 'draft': - raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.INVENTORY_RULE_DELETE_BLOCKED') + raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_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) + rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id) if rule is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') if rule.status != 'published': - raise ConflictError('Only published routing rules can be retired', code='SHIPPING.INVENTORY_RULE_RETIRE_INVALID') + raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID') rule.status = 'retired' rule.updated_by = actor_id db.session.commit() @@ -882,12 +1068,12 @@ def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: 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) + current = db.session.get(FreightRpaOnhandRoutingRule, rule_id) if current is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_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( + raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE') + rule = current if rule_id else FreightRpaOnhandRoutingRule( rule_code='', rule_name='', scope='', action_type='', action_payload_json={} ) rule.rule_code = str(_text(data, 'rule_code', required=True)).upper() @@ -903,37 +1089,37 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None 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') + raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_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') + raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED') # 草稿更新在同一版本内替换条件;发布后不可原地修改。 if rule_id: - db.session.query(ShippingInventoryRoutingRuleCondition).filter_by(rule_id=rule.id).delete( + db.session.query(FreightRpaOnhandRoutingRuleCondition).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') + raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_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 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') + raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') published_fields = { str(config.get('field_id')) for config in order_schema_service.get_published_contract()['fields'] if config.get('scope') == field.scope } if field.id not in published_fields: - raise ValidationError('Routing order field is not published', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') else: - raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') + raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') operator = str(item['operator']) - rule.conditions.append(ShippingInventoryRoutingRuleCondition( + rule.conditions.append(FreightRpaOnhandRoutingRuleCondition( condition_group=int(item.get('condition_group') or 1), source_kind=source_kind, order_field_id=order_field_id, operator=operator, expected_value_json=_validate_rule_condition_expected( @@ -946,7 +1132,7 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None 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 + raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc return _rule_payload(rule) @@ -956,11 +1142,11 @@ def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: 路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际 库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。 """ - rule = db.session.get(ShippingInventoryRoutingRule, rule_id) + rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id) if rule is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') if rule.status != 'draft': - raise ConflictError('Only draft routing rules can be published', code='SHIPPING.INVENTORY_RULE_PUBLISH_INVALID') + raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_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 = { @@ -970,27 +1156,27 @@ def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: } existing_codes = { str(code).strip().upper() - for (code,) in db.session.query(ShippingInventorySource.source_code).all() + for (code,) in db.session.query(FreightRpaSource.source_code).all() } missing_codes = sorted(source_codes - existing_codes) if missing_codes: raise ValidationError( 'Routing rule references unavailable inventory sources', - code='SHIPPING.INVENTORY_RULE_SOURCE_INVALID', + code='SHIPPING.ONHAND_RULE_SOURCE_INVALID', details={'source_codes': missing_codes}, ) rule.status = 'published' rule.updated_by = actor_id - db.session.add(ShippingInventoryRoutingRuleVersion( + db.session.add(FreightRpaOnhandRoutingRuleVersion( 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]: +def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]: return { - 'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id, + 'id': mapping.id, 'source_id': mapping.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, @@ -1001,31 +1187,31 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An def list_external_mappings() -> list[dict[str, Any]]: """列出库存源到外部系统仓库的映射,不执行调拨判断。""" - return [_external_payload(item) for item in ShippingInventoryExternalMapping.query.order_by(ShippingInventoryExternalMapping.id).all()] + return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()] def delete_external_mapping(mapping_id: int) -> None: """删除错误的外部仓库映射;历史文件和任务不回写此实时配置。""" - record = db.session.get(ShippingInventoryExternalMapping, mapping_id) + record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) if record is None: - raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND') + raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_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 + record = db.session.get(FreightRpaOnhandExternalMapping, 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') + raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND') try: - source_id = int(data.get('inventory_source_id')) + source_id = int(data.get('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 + raise ValidationError('source_id is required') from exc + if db.session.get(FreightRpaSource, source_id) is None: + raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='') + record.source_id = source_id # 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行, # 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。 record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None @@ -1045,5 +1231,5 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping 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 + raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc return _external_payload(record) diff --git a/backend/app/services/freight_rpa/common/callback_sinks.py b/backend/app/services/freight_rpa/common/callback_sinks.py index 49ab0585..5c1e02b6 100644 --- a/backend/app/services/freight_rpa/common/callback_sinks.py +++ b/backend/app/services/freight_rpa/common/callback_sinks.py @@ -1,9 +1,14 @@ """ services/freight_rpa/common/callback_sinks.py -用途:RPA 回调业务 sink 注册表——freight_rpa 侧的回调分发缝。 +用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起 + 与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch. + dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact, + kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind + (inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等) + 仍走本模块的 register_sink / dispatch_sink,不改 envelope)。 依赖:app.core.errors.AppError。 -逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,onhand 等待拆端点按 kind 分发到 +逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到 组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404, 绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由 组合根调用 register_sink 注入真实业务持久化处理器。 diff --git a/backend/app/services/freight_rpa/common/report_audit.py b/backend/app/services/freight_rpa/common/report_audit.py new file mode 100644 index 00000000..3d18351b --- /dev/null +++ b/backend/app/services/freight_rpa/common/report_audit.py @@ -0,0 +1,384 @@ +"""freight_rpa/common/report_audit.py + +用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入 + ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。 +依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors. + ValidationError、SQLAlchemy 会话(app.db)。 +逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa + 包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/ + freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与 + append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent + 模型,事件名(shipping_inbound_rpa_callback_received / + shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。 + 与 audit_service 的有意差异(均为本域受控场景): + (1)before/after 快照不做白名单投影——本域快照键均为受控诊断键 + (status/error_code/sha256/file_size 等),原样入 snapshot 列; + (2)不做 XFA 加密完整快照(本域无敏感完整载荷); + (3)保留期恒为 None(货代统一审计账本永久保留); + (4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash + 取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。 + 本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ValidationError +from app.models import ShippingAuditEvent + +# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。 +_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'}) +_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'}) + +# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自 +# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。 +_FORBIDDEN_AUDIT_KEYS = frozenset({ + 'api_key', + 'api_base_url', + 'authorization', + 'body', + 'content', + 'document_text', + 'email_body', + 'minio', + 'object_key', + 'object_url', + 'password', + 'prompt', + 'provider_config', + 'quote', + 'raw_content', + 'raw_output', + 'secret', + 'token', + 'url', + 'user_agent', +}) + + +def _is_forbidden_audit_key(key: str) -> bool: + """键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。""" + return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS + + +def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]: + """ + 递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。 + + Returns: + 命中键路径列表(调用方排序后入 ValidationError.details)。 + """ + found: list[str] = [] + if isinstance(payload, dict): + for key, child in payload.items(): + key_text = str(key) + child_path = f'{path}.{key_text}' if path else key_text + if _is_forbidden_audit_key(key_text): + found.append(child_path) + found.extend(_collect_forbidden_keys(child, path=child_path)) + elif isinstance(payload, list): + for index, child in enumerate(payload): + found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]')) + return found + + +def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]: + """验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。""" + safe = dict(metadata or {}) + forbidden = _collect_forbidden_keys(safe) + if forbidden: + raise ValidationError( + 'RPA report audit metadata contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN', + details={'forbidden_keys': sorted(set(forbidden))}, + ) + return safe + + +def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None: + """校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。""" + if refs is None: + return None + if not isinstance(refs, list): + raise ValidationError( + f'RPA report audit {field_name} must be a list', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + ) + forbidden = _collect_forbidden_keys(refs) + if forbidden: + raise ValidationError( + f'RPA report audit {field_name} contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + details={'forbidden_keys': sorted(set(forbidden))}, + ) + return refs + + +def _stable_hash(value: Any) -> str: + """对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。""" + encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(encoded.encode('ascii')).hexdigest() + + +def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None: + """ + 计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。 + + 核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。 + """ + left = before if isinstance(before, dict) else {} + right = after if isinstance(after, dict) else {} + changed: dict[str, Any] = {} + added: dict[str, Any] = {} + removed: dict[str, Any] = {} + for key in sorted(set(left) | set(right)): + if key in left and key in right: + if left[key] != right[key]: + changed[key] = {'from': left[key], 'to': right[key]} + elif key in right: + added[key] = right[key] + else: + removed[key] = left[key] + if not changed and not added and not removed: + return None + return {'changed': changed, 'added': added, 'removed': removed} + + +def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None: + """ + 读取同聚合最新一条事件的 event_hash 作为哈希链前驱。 + + 核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。 + 调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。 + """ + previous = ( + ShippingAuditEvent.query + .filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128]) + .order_by(ShippingAuditEvent.id.desc()) + .first() + ) + if previous is None: + return None + return str(previous.event_hash) if previous.event_hash else None + + +def _event_hash_payload( + *, + event_type: str, + aggregate_type: str, + aggregate_id: str, + action: str | None, + result: str | None, + reason_code: str | None, + run_no: str | None, + task_no: str | None, + operation_id: str | None, + request_id: str | None, + actor_type: str, + actor_id: str | None, + before_snapshot: dict[str, Any] | None, + after_snapshot: dict[str, Any] | None, + diff_json: dict[str, Any] | None, + previous_event_hash: str | None, + sensitivity_level: str | None, +) -> dict[str, Any]: + """组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。""" + return { + 'event_type': event_type, + 'aggregate_type': aggregate_type, + 'aggregate_id': aggregate_id, + 'action': action, + 'result': result, + 'reason_code': reason_code, + 'workflow_id': None, + 'workflow_item_id': None, + 'workflow_item_version_id': None, + 'version_no': None, + 'run_no': run_no, + 'document_id': None, + 'review_case_no': None, + 'task_no': task_no, + 'operation_id': operation_id, + 'request_id': request_id, + 'actor_type': actor_type, + 'actor_id': actor_id, + 'before_snapshot': before_snapshot, + 'after_snapshot': after_snapshot, + 'diff': diff_json, + 'previous_event_hash': previous_event_hash, + 'sensitivity_level': sensitivity_level, + } + + +def append_rpa_report_event( + *, + event_type: str, + aggregate_type: str, + aggregate_id: str, + run_no: str | None = None, + task_no: str | None = None, + intake_no: str | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, + actor_role: str | None = None, + actor_display: str | None = None, + request_id: str | None = None, + operation_id: str | None = None, + correlation_id: str | None = None, + source: str | None = None, + result: str | None = None, + error_code: str | None = None, + conversation_id: str | None = None, + unit_id: str | int | None = None, + document_id: str | int | None = None, + review_case_no: str | None = None, + owner_user_id: str | int | None = None, + attempt_no: int | None = None, + action: str | None = None, + reason_code: str | None = None, + reason: str | None = None, + before: Any = None, + after: Any = None, + evidence_refs: list[dict[str, Any]] | None = None, + artifact_refs: list[dict[str, Any]] | None = None, + context_refs: dict[str, Any] | None = None, + metadata: dict[str, Any] | None = None, + sensitivity_level: str | None = None, +) -> ShippingAuditEvent: + """ + 追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。 + + 用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的 + RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名, + 事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。 + 核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏; + [STEP 2] 计算 before/after 稳定哈希与顶层 diff; + [STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash; + [STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。 + Args: + event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received); + 禁止传入用户自由文本。 + aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。 + run_no/task_no: 排程 run / task 软引用(截断 64)。 + actor_type/actor_id/actor_role/actor_display: 操作主体四元组 + (actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。 + result: success / failure / rejected / ignored(白名单外抛 ValidationError)。 + before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。 + evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。 + metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。 + unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。 + action/reason_code/reason/error_code/conversation_id/correlation_id/source/ + request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。 + Returns: + 尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。 + Raises: + ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。 + """ + # [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。 + if actor_type not in _ALLOWED_ACTOR_TYPES: + raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID') + if result is not None and result not in _ALLOWED_RESULTS: + raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID') + safe_metadata = _sanitize_metadata(metadata) + if before is not None and _collect_forbidden_keys(before): + raise ValidationError( + 'RPA report audit snapshot contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))}, + ) + if after is not None and _collect_forbidden_keys(after): + raise ValidationError( + 'RPA report audit snapshot contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))}, + ) + + # [STEP 2] 快照哈希与顶层差异。 + before_snapshot = before if isinstance(before, dict) else None + after_snapshot = after if isinstance(after, dict) else None + diff_json = _snapshot_diff(before, after) + + # [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。 + db.session.flush() + previous_event_hash = _resolve_previous_event_hash( + aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128], + ) + resolved_run_no = str(run_no)[:64] if run_no else None + resolved_task_no = str(task_no)[:64] if task_no else None + resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None + resolved_operation_id = str(operation_id)[:64] if operation_id else None + resolved_request_id = str(request_id)[:64] if request_id else None + resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None + event_hash = _stable_hash(_event_hash_payload( + event_type=str(event_type)[:64], + aggregate_type=str(aggregate_type)[:64], + aggregate_id=str(aggregate_id)[:128], + action=str(action)[:64] if action else None, + result=result, + reason_code=str(reason_code)[:128] if reason_code else None, + run_no=resolved_run_no, + task_no=resolved_task_no, + operation_id=resolved_operation_id, + request_id=resolved_request_id, + actor_type=actor_type, + actor_id=resolved_actor_id, + before_snapshot=before_snapshot, + after_snapshot=after_snapshot, + diff_json=diff_json, + previous_event_hash=previous_event_hash, + sensitivity_level=resolved_sensitivity, + )) + + # [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。 + event = ShippingAuditEvent( + event_type=str(event_type)[:64], + aggregate_type=str(aggregate_type)[:64], + aggregate_id=str(aggregate_id)[:128], + run_no=resolved_run_no, + task_no=resolved_task_no, + intake_no=str(intake_no)[:64] if intake_no else None, + actor_type=actor_type, + actor_id=resolved_actor_id, + actor_role=str(actor_role)[:64] if actor_role else None, + actor_display=str(actor_display)[:128] if actor_display else None, + request_id=resolved_request_id, + operation_id=resolved_operation_id, + correlation_id=str(correlation_id)[:64] if correlation_id else None, + source=str(source)[:32] if source else None, + result=result, + error_code=str(error_code)[:64] if error_code else None, + conversation_id=str(conversation_id)[:100] if conversation_id else None, + unit_id=str(unit_id)[:64] if unit_id is not None else None, + document_id=str(document_id)[:64] if document_id is not None else None, + review_case_no=str(review_case_no)[:64] if review_case_no else None, + owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None, + attempt_no=int(attempt_no) if attempt_no is not None else None, + action=str(action)[:64] if action else None, + reason_code=str(reason_code)[:128] if reason_code else None, + reason=str(reason)[:2000] if reason else None, + before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None, + after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None, + before_snapshot_json=before_snapshot, + after_snapshot_json=after_snapshot, + diff_json=diff_json, + previous_event_hash=previous_event_hash, + event_hash=event_hash, + sensitivity_level=resolved_sensitivity, + evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'), + artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'), + context_refs_json=dict(context_refs or {}) if context_refs else None, + metadata_json=safe_metadata, + retention_expires_at=None, + ) + db.session.add(event) + db.session.flush() + return event + + +# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。 +RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS diff --git a/backend/app/services/freight_rpa/common/worker_heartbeat.py b/backend/app/services/freight_rpa/common/worker_heartbeat.py index 1e82ff16..bbcaa839 100644 --- a/backend/app/services/freight_rpa/common/worker_heartbeat.py +++ b/backend/app/services/freight_rpa/common/worker_heartbeat.py @@ -35,10 +35,10 @@ RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服 RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接" RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试" # [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换—— -# inventory_export→onhand_export、receipt_export→inbound_export(freight_upload 不变); +# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload; # worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。 ONHAND_EXPORT_CAPABILITY = "onhand_export" -FREIGHT_UPLOAD_CAPABILITY = "freight_upload" +FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload" INBOUND_EXPORT_CAPABILITY = "inbound_export" # inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。 INBOUND_WORKER_ID_SUFFIX = "-inbound" @@ -59,7 +59,7 @@ _REASON_USER_HINTS: dict[str, str] = { "environment_mismatch": "Worker 环境与后端环境不一致", "missing_onhand_export_capability": "Worker 未声明 onhand_export 能力", "missing_inbound_export_capability": "Worker 未声明 inbound_export 能力", - "missing_freight_upload_capability": "Worker 未声明 freight_upload 能力", + "missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力", "credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY", "upload_queue_dir_not_configured": "未配置货代上传队列目录", "upload_queue_dir_not_accessible": "货代上传队列目录不可访问", @@ -454,7 +454,7 @@ def _worker_is_eligible( backend_env: 后端归一环境(dev/test/prod)。 ttl_seconds: 心跳 TTL。 now: 当前 epoch 秒。 - required_capability: 必选能力(onhand_export / inbound_export / freight_upload)。 + required_capability: 必选能力(onhand_export / inbound_export / freight_rpa_upload)。 Returns: (是否合格, 不合格原因列表)。 @@ -482,7 +482,7 @@ def _worker_is_eligible( def _missing_capability_reason(required_capability: str) -> str: - """按必选能力生成缺失原因码(onhand_export / inbound_export / freight_upload)。""" + """按必选能力生成缺失原因码(onhand_export / inbound_export / freight_rpa_upload)。""" return f"missing_{required_capability}_capability" @@ -610,7 +610,7 @@ def _check_rpa_worker_ready_for_capability( message, detail_message = "ready", "ready" else: failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons))) - if required_capability == FREIGHT_UPLOAD_CAPABILITY: + if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY: detail = _summarize_reasons(failure.reasons) message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE detail_message = f"{message}({detail})" if detail else message @@ -731,7 +731,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness: 检查货代上传 RPA 是否可安全自动触发。 核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与 - freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。 + freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。 Returns: RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。 @@ -740,7 +740,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness: return _check_rpa_worker_ready_for_capability( trigger_dir=upload_trigger_dir(), - required_capability=FREIGHT_UPLOAD_CAPABILITY, + required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY, extra_reasons=_freight_upload_config_reasons(), ) @@ -777,7 +777,7 @@ def assert_freight_upload_rpa_ready() -> None: "checked_at": result.checked_at, "shared_scope_id": shared_scope_id(), "trigger_dir": str(upload_trigger_dir() or ""), - "capability": FREIGHT_UPLOAD_CAPABILITY, + "capability": FREIGHT_RPA_UPLOAD_CAPABILITY, }, ) @@ -906,7 +906,7 @@ def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]: "upload_trigger_dir": str(upload_trigger_dir() or ""), "reasons": readiness.reasons, "workers": workers, - "freight_upload": { + "freight_rpa_upload": { "ready": freight_readiness.ready, "message": freight_readiness.message, "detail_message": freight_readiness.detail_message, diff --git a/backend/app/services/freight_rpa/inbound/report_archive.py b/backend/app/services/freight_rpa/inbound/report_archive.py index c01ffbc5..423ea62e 100644 --- a/backend/app/services/freight_rpa/inbound/report_archive.py +++ b/backend/app/services/freight_rpa/inbound/report_archive.py @@ -4,19 +4,24 @@ services/freight_rpa/inbound/report_archive.py 用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、 三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员 强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage / - schedule.freight_inbound_rpa_retention / shipping_notice.receipt_report_notification - 平移而来(函数名 receipt 词根→inbound;模型 ShippingReceiptReport* 引用不变——批次 S 才改表)。 -依赖:models(ShippingReceiptReportFile / ShippingReceiptRpaUnitRun / ShippingReceiptNotificationDelivery / + schedule.freight_rpa_inbound_retention / shipping_notice.receipt_report_notification + 平移而来(函数名 receipt 词根→inbound;模型 ShippingInboundReport* 引用不变——批次 S 才改表)。 +依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun / FreightRpaInboundNotificationDelivery / User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、 freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、 - shipping_notice.audit_service(适应度测试白名单内,本模块唯一 shipping_notice 业务依赖, - 见 tests/services/freight_rpa/test_import_boundary.py)。 + freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代 + shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块, + 边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、 + freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。 逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink (shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档, - empty/success/failed 三个终态分支各自 commit;终态落库后的业务桥(推进在途调拨来源任务、 - 调拨证据同步)与排程终态归集(finalize)经 on_terminal 钩子回调 shipping_notice 侧实现, - 本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa, - 与拆分前「归档 commit 后立刻推桥」的调用顺序逐点一致。 + empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」—— + commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact; + 处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404 + FREIGHT_RPA.SINK_NOT_REGISTERED;同一 unit_run_id + sha256 已有文件时不插第二行、 + 仍投递 ok=True 的事实供处理函数重试。业务收尾(推进在途调拨来源任务、调拨证据 + 同步、排程终态归集)改由 Task 7 的处理函数(handle_inbound_report 等)承担, + 本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa。 """ from __future__ import annotations @@ -24,26 +29,24 @@ from __future__ import annotations import hashlib from datetime import datetime, timedelta from pathlib import Path -from typing import Any, Callable +from typing import Any from flask import current_app from app import db from app.core.errors import NotFoundError, ValidationError from app.models import ( - ShippingReceiptNotificationDelivery, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + FreightRpaInboundNotificationDelivery, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, User, ) from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.common.report_audit import append_rpa_report_event from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir +from app.services.freight_rpa.reports.dispatch import dispatch_report_fact +from app.services.freight_rpa.reports.facts import ReportFact from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media -from app.services.shipping_notice.audit_service import append_shipping_audit_event - -# 终态落库后的业务收尾钩子:由 shipping_notice 域注入(推进在途调拨来源任务 + 调拨证据同步 -# + 排程终态归集),契约 = 原 storage.ingest_receipt_callback 中「commit 之后的桥/finalize 尾巴」。 -InboundTerminalHook = Callable[..., None] def _read_inbound_callback_file(file_path: str) -> bytes: @@ -73,21 +76,29 @@ def _read_inbound_callback_file(file_path: str) -> bytes: return path.read_bytes() -def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerminalHook) -> dict[str, Any]: +def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]: """幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。 Args: payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。 - on_terminal: 必填业务收尾钩子(shipping_notice 域注入,见模块 docstring);在每个终态 - 分支 commit 之后、以与拆分前完全一致的实参被调用—— - empty/failed: on_terminal(unit, ok=False, error_code=..., error_message=...); - success: on_terminal(unit, ok=True, file_no=..., file_sha256=...)。 - 业务约束:钩子内部异常只记日志,绝不回滚归档终态(契约由实现方保持)。 + Returns: + dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。 + Raises: + ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。 + NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。 + AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。 + 业务顺序(Task 6 契约):每个终态分支先 db.session.commit() 再构造 + ReportFact(report_kind='inbound', source_code=unit.source_code, ...) 调 + dispatch_report_fact;事实恒带 unit_run_id=unit.id(Task 7 修复轮 2—— + 含 failure/empty 与幂等重放,处理函数据此精确定位本单元的排程 run); + 处理函数异常原样外抛(不吞、不回滚已提交终态); + 同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实 + (供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。 """ if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA: raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID') callback_id = str(payload.get('callback_id') or '').strip() - unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() if unit is None: raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND') status = str(payload.get('status') or '').strip().lower() @@ -98,8 +109,8 @@ def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerm unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64] unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000] unit.finished_at = datetime.utcnow() - append_shipping_audit_event( - event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit', + append_rpa_report_event( + event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, @@ -111,46 +122,67 @@ def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerm }, metadata={'callback_status': status, 'skip_reason': unit.error_code}, ) + # [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id + # 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。 db.session.commit() - on_terminal( - unit, ok=False, error_code=unit.error_code or 'no_receipt_data', + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False, + error_code=unit.error_code or 'no_receipt_data', error_message=unit.error_message or 'no_receipt_data', - ) + unit_run_id=unit.id, + )) return {'unit_run_id': unit.id, 'status': 'empty'} if status != 'success': unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow() - append_shipping_audit_event( - event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit', + append_rpa_report_event( + event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure', before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message}, metadata={'callback_status': status}, ) + # [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id + # 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。 db.session.commit() - on_terminal(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message) + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False, + error_code=unit.error_code, error_message=unit.error_message, + unit_run_id=unit.id, + )) return {'unit_run_id': unit.id, 'status': 'failed'} data = _read_inbound_callback_file(str(payload.get('file_path') or '')) sha256 = hashlib.sha256(data).hexdigest() claimed = str(payload.get('sha256') or '').lower() if claimed and claimed != sha256: raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH') - existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() + existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() if existing: + # [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试; + # unit_run_id 自单元行回填(Task 7 修复轮 2)。 + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=existing.id, sha256=sha256, ok=True, + unit_run_id=unit.id, + )) return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True} filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx' file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') - record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3)) + record = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3)) db.session.add(record) unit.status = 'success'; unit.finished_at = datetime.utcnow() db.session.flush() - append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3}) + append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3}) + # [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id + # 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。 db.session.commit() - on_terminal(unit, ok=True, file_no=str(record.id), file_sha256=sha256) + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=record.id, sha256=sha256, ok=True, + unit_run_id=unit.id, + )) return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False} -def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: +def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: """仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。 Args: @@ -161,11 +193,11 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int """ limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000)) now = datetime.utcnow() - rows = ShippingReceiptReportFile.query.filter( - ShippingReceiptReportFile.archive_expires_at.is_not(None), - ShippingReceiptReportFile.archive_expires_at <= now, - ShippingReceiptReportFile.archive_deleted_at.is_(None), - ).order_by(ShippingReceiptReportFile.id).limit(limit).all() + rows = FreightRpaInboundReportFile.query.filter( + FreightRpaInboundReportFile.archive_expires_at.is_not(None), + FreightRpaInboundReportFile.archive_expires_at <= now, + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + ).order_by(FreightRpaInboundReportFile.id).limit(limit).all() success = failed = 0 errors: list[str] = [] for report_file in rows: @@ -173,8 +205,8 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int file_asset_storage.delete_object(report_file.storage_key) report_file.archive_deleted_at = now report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()} - append_shipping_audit_event( - event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file', + append_rpa_report_event( + event_type='shipping_inbound_report_archive_deleted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', unit_id=report_file.unit_run_id, result='success', before={'status': 'archived'}, after={'status': 'archive_deleted'}, @@ -183,8 +215,8 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int success += 1 except Exception as exc: errors.append(f'{report_file.id}: {exc}') - append_shipping_audit_event( - event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file', + append_rpa_report_event( + event_type='shipping_inbound_report_archive_delete_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', unit_id=report_file.unit_run_id, result='failure', before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]}, @@ -195,7 +227,7 @@ def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}] -def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]: +def _recipient_ids(report_file: FreightRpaInboundReportFile) -> list[int]: """从所属排程冻结的接收人列表取目标用户;停用通知时返回空。""" run = report_file.unit_run.schedule_run task = run.task if run else None @@ -208,23 +240,23 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict: """向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。 Args: - file_id: 已归档收料文件主键(ShippingReceiptReportFile.id)。 + file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。 force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。 Returns: dict: success_count / failed_count(file_not_found 时附 reason)。 """ - report_file = db.session.get(ShippingReceiptReportFile, file_id) + report_file = db.session.get(FreightRpaInboundReportFile, file_id) if report_file is None: return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'} success_count = failed_count = 0 for user_id in _recipient_ids(report_file): key = f'receipt:file:{report_file.id}:user:{user_id}' - delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none() + delivery = FreightRpaInboundNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none() if delivery and delivery.status == 'success' and not force: success_count += 1 continue if delivery is None: - delivery = ShippingReceiptNotificationDelivery( + delivery = FreightRpaInboundNotificationDelivery( unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id, message_type='file', idempotency_key=key, status='pending', ) @@ -234,8 +266,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict: if user is None or not user.wecom_userid: delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding' failed_count += 1 - append_shipping_audit_event( - event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', + append_rpa_report_event( + event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='failure', before={'delivery_status': 'pending'}, @@ -252,8 +284,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict: delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0} success_count += 1 - append_shipping_audit_event( - event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id), + append_rpa_report_event( + event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success', before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], @@ -262,8 +294,8 @@ def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict: except Exception as exc: delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000] failed_count += 1 - append_shipping_audit_event( - event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', + append_rpa_report_event( + event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='failure', before={'delivery_status': 'pending'}, diff --git a/backend/app/services/freight_rpa/inbound/trigger_io.py b/backend/app/services/freight_rpa/inbound/trigger_io.py index aeee8ad1..ba94649d 100644 --- a/backend/app/services/freight_rpa/inbound/trigger_io.py +++ b/backend/app/services/freight_rpa/inbound/trigger_io.py @@ -5,7 +5,7 @@ services/freight_rpa/inbound/trigger_io.py 原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。 依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块 (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 -逻辑:由 schedule.freight_inbound_rpa_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、 +逻辑:由 schedule.freight_rpa_inbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、 in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、 freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、 freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用, diff --git a/backend/app/services/freight_rpa/onhand/attempts.py b/backend/app/services/freight_rpa/onhand/attempts.py index e242211d..b933b958 100644 --- a/backend/app/services/freight_rpa/onhand/attempts.py +++ b/backend/app/services/freight_rpa/onhand/attempts.py @@ -3,8 +3,8 @@ services/freight_rpa/onhand/attempts.py 用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。 依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。 -逻辑:由 shipping_notice 的 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件, - 决定是否还能继续触发 RPA 重试;事件类型字符串(inventory_rpa_* 等)是落库数据值, +逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件, + 决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值, 随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。 """ @@ -20,8 +20,8 @@ DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3 _ONHAND_SUCCESS_EVENTS = { "inventory_uploaded", "inventory_parsed", - "inventory_rpa_drop_ingested", - "inventory_rpa_ready", + "onhand_rpa_drop_ingested", + "onhand_rpa_ready", "inventory_template_mapping_used", } @@ -49,10 +49,10 @@ def onhand_rpa_attempts(task: ShippingNotice | None) -> int: since: datetime | None = last_reset.created_at if last_reset else None triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter( - ShippingTaskEvent.event_type == "inventory_rpa_triggered" + ShippingTaskEvent.event_type == "onhand_rpa_triggered" ) failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter( - ShippingTaskEvent.event_type == "inventory_rpa_failed" + ShippingTaskEvent.event_type == "onhand_rpa_failed" ) if since: triggered = triggered.filter(ShippingTaskEvent.created_at >= since) diff --git a/backend/app/services/freight_rpa/onhand/callback_cleanup.py b/backend/app/services/freight_rpa/onhand/callback_cleanup.py index a8631f4d..496151ad 100644 --- a/backend/app/services/freight_rpa/onhand/callback_cleanup.py +++ b/backend/app/services/freight_rpa/onhand/callback_cleanup.py @@ -2,7 +2,7 @@ services/freight_rpa/onhand/callback_cleanup.py 用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记 - (Task 9 自 shipping_notice.inventory_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。 + (Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。 依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。 逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队; scheduler/worker 启动时定期消费队列。 diff --git a/backend/app/services/freight_rpa/onhand/report_store.py b/backend/app/services/freight_rpa/onhand/report_store.py new file mode 100644 index 00000000..ebc269f4 --- /dev/null +++ b/backend/app/services/freight_rpa/onhand/report_store.py @@ -0,0 +1,84 @@ +"""freight_rpa/onhand/report_store.py + +用途:freight_rpa_onhand_report_files 的写入唯一入口(阶段 B Task 5)——发货域 + (shipping_notice)与调度等其他消费方不得自行构造 FreightRpaOnhandReportFile 行, + 插入/按主键更新统一经本模块收敛,保证报表事实写入只发生在货代 RPA 域。 +依赖:app.db、app.models.FreightRpaOnhandReportFile、app.core.errors.NotFoundError。 +逻辑:insert_onhand_report 接收与 FreightRpaOnhandReportFile 列同名的关键字参数 + (storage_path、file_sha256、onhand_lines_json、field_mapping_json、 + snapshot_status、warehouse_id、source_code、rpa_run_no 等),flush 后 + 返回 file_id;update_onhand_report 按主键更新给定列。两者都【只 flush 不 + commit】——事务提交时机归属调用方;两者都【不创建任务关联】—— + shipping_task_onhand_links 等 link 表归发货域,由调用方自行维护。 + 【禁止】import app.services.shipping_notice / in_transit_transfer(import + 方向只能反过来,边界由 tests/services/shipping_notice/ + test_report_model_boundary.py 锁定)。 +""" + +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import NotFoundError +from app.models import FreightRpaOnhandReportFile + + +def insert_onhand_report(**columns: Any) -> int: + """插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。 + + 【AI 触发时机】:任何需要新增在手/库存快照文件记录的场景 + (RPA 回调入快照、人工上传保存、空快照记录)须调用本函数,禁止在 + shipping_notice 域内直接构造 FreightRpaOnhandReportFile 行。 + + 核心逻辑:[STEP 1] 以与模型列同名的关键字参数构造行; + [STEP 2] db.session.add + flush(拿到自增主键且同事务内可见); + [STEP 3] 返回 int 主键,供调用方按需经 db.session.get 取回 ORM 对象。 + + Args: + **columns: FreightRpaOnhandReportFile 的任意合法列关键字(禁止传入不存在的 + 列名,非法列名会在构造时抛 TypeError)。无默认值语义变化—— + 列默认值仍由模型定义(default=)承担。 + + Returns: + 新插入行的 file_id(int)。 + + Raises: + TypeError: 传入了模型不存在的列关键字。 + sqlalchemy.exc.IntegrityError: 唯一约束(如 onhand_file_no / RPA 幂等索引) + 冲突,由调用方决定 savepoint 回滚或复用既有行。 + """ + row = FreightRpaOnhandReportFile(**columns) + db.session.add(row) + db.session.flush() + return int(row.id) + + +def update_onhand_report(file_id: int, **columns: Any) -> None: + """按 file_id 更新该行的给定列并 flush。不 commit。 + + 【AI 触发时机】:快照过期(snapshot_status→expired)、批次同身份改写 + share_mode、identity_status 回填等针对既有在手报表行的列更新场景。 + + 核心逻辑:[STEP 1] 按主键取行(命中身份缓存即为同一 ORM 对象,调用方 + 持有的引用会同步可见更新),缺失抛 NotFoundError(fail-closed,禁止静默 + 吞掉错配);[STEP 2] 逐列 setattr;[STEP 3] flush。【不 commit】—— + 事务归属调用方;【不动任务关联】——link 表更新归发货域。 + + Args: + file_id: freight_rpa_onhand_report_files 主键(int;禁止传入非整数 ID)。 + **columns: 要更新的列名与取值(禁止传入模型不存在的列名)。 + + Raises: + NotFoundError: file_id 对应的行不存在。 + TypeError: 传入了模型不存在的列关键字。 + """ + row = db.session.get(FreightRpaOnhandReportFile, file_id) + if row is None: + raise NotFoundError( + f"Onhand report file not found: {file_id}", + details={'file_id': file_id}, + ) + for key, value in columns.items(): + setattr(row, key, value) + db.session.flush() \ No newline at end of file diff --git a/backend/app/services/freight_rpa/onhand/trigger_io.py b/backend/app/services/freight_rpa/onhand/trigger_io.py index 4954b425..77f64db2 100644 --- a/backend/app/services/freight_rpa/onhand/trigger_io.py +++ b/backend/app/services/freight_rpa/onhand/trigger_io.py @@ -5,7 +5,7 @@ services/freight_rpa/onhand/trigger_io.py 单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。 依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块 (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 -逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、inventory_rpa_workflow(回调 schema 校验)、 +逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、onhand_rpa_workflow(回调 schema 校验)、 per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用, 与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相 (Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。 diff --git a/backend/app/services/freight_rpa/onhand/workflow_protocol.py b/backend/app/services/freight_rpa/onhand/workflow_protocol.py index 2eeeef38..f26ca451 100644 --- a/backend/app/services/freight_rpa/onhand/workflow_protocol.py +++ b/backend/app/services/freight_rpa/onhand/workflow_protocol.py @@ -3,11 +3,11 @@ services/freight_rpa/onhand/workflow_protocol.py 用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、 排程进度记账与超时窗口判定的纯协议层。 -依赖:app.models(ShippingTaskEvent / ShippingTaskInventoryRpaAttempt / ScheduleRun)、 +依赖:app.models(ShippingTaskEvent / FreightRpaOnhandTaskAttempt / ScheduleRun)、 app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何 shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py AST 全包扫描锁死,含函数内延迟 import)。 -逻辑:Task 9 拆分自 shipping_notice.inventory_rpa_workflow——回调进入 +逻辑:Task 9 拆分自 shipping_notice.onhand_rpa_workflow——回调进入 /api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内 调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/ 门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。 @@ -21,7 +21,7 @@ from pathlib import Path from typing import Any from app.extensions import db -from app.models import ScheduleRun, ShippingTaskEvent, ShippingTaskInventoryRpaAttempt +from app.models import ScheduleRun, ShippingTaskEvent, FreightRpaOnhandTaskAttempt def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None: @@ -61,7 +61,7 @@ def is_legacy_trigger_run_no(run_no: str) -> bool: def expected_rpa_callback_run_no(task: Any) -> str: """读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。""" - last_trigger = latest_task_event(task, "inventory_rpa_triggered") + last_trigger = latest_task_event(task, "onhand_rpa_triggered") if not last_trigger: return "" detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {} @@ -101,9 +101,9 @@ def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str def get_consumed_inventory_rpa_run_no(task: Any) -> str: """读取已消费(处理完成)的 RPA 轮次 run_no。""" attempt = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter_by(task_no=str(task.task_no or ''), status='consumed') - .order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.consumed_at.desc(), FreightRpaOnhandTaskAttempt.id.desc()) .first() ) return str(getattr(attempt, 'source_run_no', '') or '').strip() @@ -119,7 +119,7 @@ def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None: if not effective: return attempt = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter_by(task_no=str(task.task_no or ''), source_run_no=effective) .one_or_none() ) @@ -199,7 +199,7 @@ def record_onhand_batch_progress( 'updated_at': datetime.utcnow().isoformat(), } run.response_summary_json = summary - # commit 时机与拆分前 inventory_rpa_workflow.report_inventory_batch_progress 完全一致: + # commit 时机与拆分前 onhand_rpa_workflow.report_inventory_batch_progress 完全一致: # 校验通过、计数写完后立即提交,再由业务层构造响应。 db.session.commit() return { @@ -221,7 +221,7 @@ def compute_rpa_wait_window( 【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。 Args: - triggered_at: 最近一次 inventory_rpa_triggered 事件的 created_at。 + triggered_at: 最近一次 onhand_rpa_triggered 事件的 created_at。 timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。 now: 可注入当前时间(测试用);缺省 utcnow。 diff --git a/backend/app/services/freight_rpa/reports/__init__.py b/backend/app/services/freight_rpa/reports/__init__.py new file mode 100644 index 00000000..11e0c747 --- /dev/null +++ b/backend/app/services/freight_rpa/reports/__init__.py @@ -0,0 +1,45 @@ +"""freight_rpa/reports/__init__.py + +用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨 + (in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。 +依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。 +逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice) + 一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。 + 本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer + (import 边界由 tests/services/freight_rpa/test_report_queries.py 与 + test_import_boundary.py 锁定)。 +""" + +from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind +from app.services.freight_rpa.reports.queries import ( + InboundConfigView, + InboundFileView, + OnhandConfigView, + SiteView, + clear_inbound_parse_failure, + get_inbound_config, + get_onhand_config, + get_site, + latest_usable_inbound_file, + mark_inbound_parse_failure, + read_inbound_file_bytes, + usable_inbound_file_condition, +) + +__all__ = [ + 'REPORT_KINDS', + 'InboundConfigView', + 'InboundFileView', + 'OnhandConfigView', + 'ReportFact', + 'SiteView', + 'clear_inbound_parse_failure', + 'get_inbound_config', + 'get_onhand_config', + 'get_site', + 'latest_usable_inbound_file', + 'mark_inbound_parse_failure', + 'read_inbound_file_bytes', + 'require_report_kind', + 'usable_inbound_file_condition', +] \ No newline at end of file diff --git a/backend/app/services/freight_rpa/reports/dispatch.py b/backend/app/services/freight_rpa/reports/dispatch.py new file mode 100644 index 00000000..a1530856 --- /dev/null +++ b/backend/app/services/freight_rpa/reports/dispatch.py @@ -0,0 +1,78 @@ +"""freight_rpa/reports/dispatch.py + +用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit + 终态、再投递事实」的第二段分发(批次 B Task 6)。 +依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、 + require_report_kind)。 +逻辑:组合根(Task 7 的 shipping_notice.rpa_sinks.register_inbound_sinks / + register_onhand_sinks 等)在应用启动时调用 register_report_handler 注入各 + kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive. + ingest_inbound_callback)在每个终态 db.session.commit() 之后调用 + dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA. + SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码), + 绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。 + 本模块不 commit、不 rollback。 +""" + +from __future__ import annotations + +from typing import Callable + +from app.core.errors import AppError +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind + +# 报表事实处理函数契约:接收单个 ReportFact,返回 None; +# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。 +Handler = Callable[[ReportFact], None] + +# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。 +_REPORT_HANDLERS: dict[str, Handler] = {} + + +def register_report_handler(report_kind: str, handler: Handler) -> None: + """ + 注册一个报表事实处理函数(由组合根在应用启动时调用)。 + + 【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks / + register_onhand_sinks)时调用;测试直接调用注入临时处理函数。 + 核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound / + outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。 + Args: + report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。 + handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用, + 不校验其内部行为。 + Raises: + ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。 + """ + kind = require_report_kind(report_kind) + _REPORT_HANDLERS[kind] = handler + + +def dispatch_report_fact(fact: ReportFact) -> None: + """ + 把已随终态 commit 的报表事实投递给对应 kind 的处理函数。 + + 【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态 + db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 / + 单元不存在 / 落库失败均不得投递)。 + 核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数, + 其异常原样向外抛(不包日志、不吞);未注册抛 + AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。 + 本函数不 commit、不 rollback。 + Args: + fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/ + sha256/ok/error_code/error_message)。 + Raises: + ValidationError: fact.report_kind 不在白名单。 + AppError: kind 未注册处理函数(404;归档终态已提交不回滚, + Worker 重试整笔回调即可补投递)。 + """ + kind = require_report_kind(fact.report_kind) + handler = _REPORT_HANDLERS.get(kind) + if handler is None: + raise AppError( + code='FREIGHT_RPA.SINK_NOT_REGISTERED', + message=f'No report handler registered for kind: {kind}', + http_status=404, + ) + handler(fact) diff --git a/backend/app/services/freight_rpa/reports/facts.py b/backend/app/services/freight_rpa/reports/facts.py new file mode 100644 index 00000000..6933889a --- /dev/null +++ b/backend/app/services/freight_rpa/reports/facts.py @@ -0,0 +1,71 @@ +"""freight_rpa/reports/facts.py + +用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。 +依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。 +逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作; + report kind 只认 onhand / inbound / outbound,非法值抛 + ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'), + 与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。 + 本模块不 import shipping_notice / in_transit_transfer。 + 【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递 + 必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from app.core.errors import ValidationError + +# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用 +# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。 +REPORT_KINDS = ('onhand', 'inbound', 'outbound') + +# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码, +# 避免为同一类入参错误分裂出多个近义 code。 +_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID' + + +@dataclass(frozen=True) +class ReportFact: + """一份回报表的事实行(跨域只读传输对象)。 + + 用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照; + ok=False 时 error_code/error_message 描述失败原因。 + 约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指); + unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递 + 必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新), + 允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。 + """ + + report_kind: str + source_code: str + file_id: int | None + sha256: str | None + ok: bool + error_code: str | None = None + error_message: str | None = None + unit_run_id: int | None = None + + +def require_report_kind(value: str) -> str: + """校验并原样返回合法的 report kind。 + + 用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。 + 核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛 + ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。 + + Args: + value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。 + Returns: + 原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。 + Raises: + ValidationError: value 不在白名单内(HTTP 400,不可重试)。 + """ + if value not in REPORT_KINDS: + raise ValidationError( + f"Unsupported report kind: {value!r}", + code=_INVALID_KIND_ERROR_CODE, + details={'report_kind': value, 'allowed': list(REPORT_KINDS)}, + ) + return value \ No newline at end of file diff --git a/backend/app/services/freight_rpa/reports/queries.py b/backend/app/services/freight_rpa/reports/queries.py new file mode 100644 index 00000000..4808b3cc --- /dev/null +++ b/backend/app/services/freight_rpa/reports/queries.py @@ -0,0 +1,599 @@ +"""freight_rpa/reports/queries.py + +用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+ + 解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露 + freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、 + 入站归档文件),使消费方不再直接 import freight_rpa 模型表。 +依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig / + FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接 + (RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、 + app.core.errors(NotFoundError)、 + file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。 +逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer + ——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。 + usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤 + 表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移, + 两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 = + 未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 + + 未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 = + 未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window + 的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer + (import 禁令)而保持口径逐位一致。 + 【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补 + config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析 + 方案(get_inbound_parsing_profile)、失效文件存在性(has_expired_inbound_ + file)、重建通道归档清单(list_reparseable_inbound_files)、入站可用站点 + 编码清单(list_inbound_configured_source_codes)——供 in_transit_transfer + 收敛为「只按 source_code / file_id 读取」的只读函数消费面。 + mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timedelta +from zoneinfo import ZoneInfo + +from sqlalchemy import ColumnElement, and_, not_, or_ + +from app import db +from app.core.errors import NotFoundError +from app.models import ( + FreightRpaInboundReportConfig, + FreightRpaInboundReportFile, + FreightRpaOnhandReportConfig, + FreightRpaSource, +) +from app.services.file_assets.storage import file_asset_storage + +# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000), +# 防止上游超长错误信息把写入顶爆。 +_PARSE_ERROR_CODE_MAX = 64 +_PARSE_ERROR_MESSAGE_MAX = 2000 + +# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内 +# 复制而非 import,见文件头 import 禁令)。 +_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") +_UTC_TZ = ZoneInfo("UTC") + + +def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]: + """返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。 + + 自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B + Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会 + 漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学 + 并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。 + + Args: + now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致), + 缺省取当前 Asia/Shanghai 时刻。 + Returns: + (窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。 + """ + if now is None: + now = datetime.now(_SHANGHAI_TZ) + if now.tzinfo is None: + now = now.replace(tzinfo=_UTC_TZ) + sh_now = now.astimezone(_SHANGHAI_TZ) + start_utc = ( + datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ) + .astimezone(_UTC_TZ) + .replace(tzinfo=None) + ) + return start_utc, start_utc + timedelta(hours=24) + + +def _fresh_and_retention_valid(now: datetime) -> ColumnElement: + """新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。""" + window_start, window_end = _business_date_utc_window(now) + return and_( + FreightRpaInboundReportFile.created_at >= window_start, + FreightRpaInboundReportFile.created_at < window_end, + or_( + FreightRpaInboundReportFile.archive_expires_at.is_(None), + FreightRpaInboundReportFile.archive_expires_at > now, + ), + ) + + +def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement: + """返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。 + + 判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致): + 未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 + (created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+ + 未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。 + 本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一 + 事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。 + + Args: + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + 可直接并入 .filter() 的单个 SQLAlchemy 条件。 + """ + now = now or datetime.utcnow() + return and_( + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + _fresh_and_retention_valid(now), + ) + + +def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement: + """返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。 + + 判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立 + (保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid) + 推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate + 迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓, + 不报 ready,也不等待保留期清理任务落位。 + + Args: + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + 可直接并入 .filter() 的单个 SQLAlchemy 条件。 + """ + now = now or datetime.utcnow() + return and_( + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + not_(_fresh_and_retention_valid(now)), + ) + + +@dataclass(frozen=True) +class SiteView: + """库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。 + + 阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别 + 方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、 + rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。 + """ + + source_code: str + display_name: str + connector_type: str + excel_template_id: int | None + enabled: bool + source_id: int = 0 + rpa_profile_id: int = 0 + warehouse_resolution_mode: str = "" + + +@dataclass(frozen=True) +class RpaLoginProfileView: + """RPA 登录连接只读视图(freight_rpa_profiles 行)。 + + 凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker + trigger,禁止出现在任何日志/接口响应中。 + """ + + profile_id: int + profile_code: str + login_url: str + login_config: dict + username_ciphertext: str | None + password_ciphertext: str | None + enabled: bool + + +@dataclass(frozen=True) +class OnhandConfigView: + """在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。""" + + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + + +@dataclass(frozen=True) +class InboundConfigView: + """入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。 + + 阶段 B Task 4 增补 config_id / config_version(调拨入站触发落可审计单元行 + 快照需要配置行主键与版本,不再引用配置模型)。 + """ + + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + config_id: int = 0 + config_version: int = 1 + + +@dataclass(frozen=True) +class InboundProfileView: + """入站解析方案只读视图(freight_rpa_parsing_profiles 行)。 + + 定义(definition_json:field_mapping / sheet_name / header_row_index 等) + 原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景 + 自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。 + """ + + profile_id: int + profile_code: str + version: int + status: str + purpose: str + definition_json: dict + + +@dataclass(frozen=True) +class InboundFileView: + """入站归档文件的只读视图;source_code 取自其所属执行单元行。 + + parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B + Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。 + """ + + file_id: int + source_code: str + sha256: str + storage_key: str + original_filename: str + created_at: datetime + parse_failed_at: datetime | None = None + + +def get_site(source_code: str) -> SiteView | None: + """按 source_code 返回库存站点只读视图。 + + 用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用, + 替代直接查询 FreightRpaSource。 + 核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。 + + Args: + source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。 + Returns: + SiteView;站点不存在返回 None(调用方自行 fail-closed)。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + if site is None: + return None + return SiteView( + source_code=site.source_code, + display_name=site.display_name, + connector_type=site.connector_type, + excel_template_id=site.excel_template_id, + enabled=bool(site.enabled), + # [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。 + source_id=site.id, + rpa_profile_id=site.rpa_profile_id, + warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""), + ) + + +def get_onhand_config(source_code: str) -> OnhandConfigView | None: + """按 source_code 返回在手报表配置只读视图。 + + 用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在 + freight_rpa_onhand_report_configs,站点行不再承载这三列)。 + 核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行 + 缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。 + + Args: + source_code: 站点实例编码。 + Returns: + OnhandConfigView;站点无配置返回 None。 + """ + config = ( + FreightRpaOnhandReportConfig.query + .join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id) + .filter(FreightRpaSource.source_code == source_code) + .first() + ) + if config is None: + return None + return OnhandConfigView( + report_path_json=dict(config.report_path_json or {}), + query_parameters_json=list(config.query_parameters_json or []), + parsing_profile_id=config.parsing_profile_id, + ) + + +def get_inbound_config(source_code: str) -> InboundConfigView | None: + """按 source_code 返回入站报表配置只读视图(与在手配置同构)。 + + 用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点 + enabled 与本配置行是否存在决定。 + 核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行, + 命中即映射视图;缺失返回 None。 + + Args: + source_code: 站点实例编码。 + Returns: + InboundConfigView;站点或配置不存在返回 None。 + """ + config = ( + FreightRpaInboundReportConfig.query + .join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id) + .filter(FreightRpaSource.source_code == source_code) + .first() + ) + if config is None: + return None + return InboundConfigView( + report_path_json=dict(config.report_path_json or {}), + query_parameters_json=list(config.query_parameters_json or []), + parsing_profile_id=config.parsing_profile_id, + # [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。 + config_id=config.id, + config_version=int(config.config_version or 1), + ) + + +def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None: + """按 source_code 返回站点绑定的 RPA 登录连接只读视图。 + + 用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码) + 时调用,替代直接查询站点与其登录连接模型。 + 核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律 + 返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文 + 原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。 + + Args: + source_code: 站点实例编码(大小写敏感)。 + Returns: + RpaLoginProfileView;站点或连接不存在返回 None。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + profile = site.rpa_profile if site is not None else None + if profile is None: + return None + return RpaLoginProfileView( + profile_id=profile.id, + profile_code=profile.profile_code, + login_url=profile.login_url, + login_config=dict(profile.login_config_json or {}), + username_ciphertext=profile.username_ciphertext, + password_ciphertext=profile.password_ciphertext, + enabled=bool(profile.enabled), + ) + + +def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None: + """按 source_code 返回入站配置绑定的解析方案只读视图。 + + 用途:调拨运行期取数(movement_file_repository)、清空重建 + (backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析 + 规则定义时调用,替代直接持有配置模型关系。 + 核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None; + 不校验 status/purpose(调用方按场景自行 fail-closed,见 + InboundProfileView docstring)。 + + Args: + source_code: 站点实例编码。 + Returns: + InboundProfileView;无配置、未绑定或方案行缺失返回 None。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + config = site.inbound_report_config if site is not None else None + profile = config.parsing_profile if config is not None else None + if profile is None: + return None + return InboundProfileView( + profile_id=profile.id, + profile_code=profile.profile_code, + version=int(profile.version or 1), + status=profile.status, + purpose=profile.purpose, + definition_json=dict(profile.definition_json or {}), + ) + + +def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView: + """把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。""" + return InboundFileView( + file_id=report.id, + source_code=report.unit_run.source_code, + sha256=report.sha256, + storage_key=report.storage_key, + original_filename=report.original_filename, + created_at=report.created_at, + parse_failed_at=report.parse_failed_at, + ) + + +def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool: + """返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。 + + 用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断 + 该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示 + 重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。 + + 核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition, + 存在任一命中即 True(纯存在性判断,不取列数据不排序)。 + + Args: + source_code: 来源实例编码(写在执行单元行上)。 + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + bool:存在失效但未清理的归档文件 → True;否则 False。 + """ + expired = ( + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter( + FreightRpaInboundReportFile.unit_run.has(source_code=source_code), + expired_inbound_file_condition(now=now), + ) + .first() + ) + return expired is not None + + +def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]: + """维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。 + + 用途:调拨待匹配桶「清空并重新解析」(movement_file_repository → + backlog_reparse_service,spec §6)按来源取重建清单时调用。 + 运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是 + 运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。 + + 核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行 + source_code 过滤),但【刻意无当日门禁】——重建对象正是历史 + 归档;保留期口径一致(archive_expires_at 为空视为长期有效)、 + 未删除(archive_deleted_at 为空)。按 created_at/id 升序返回 + (重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询, + 不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。 + + Args: + source_code: 来源实例编码(经执行单元行 source_code 关联)。 + now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + InboundFileView 列表(created_at 升序;无可重建归档为空表)。 + """ + now = now or datetime.utcnow() + reports = ( + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter( + FreightRpaInboundReportFile.unit_run.has(source_code=source_code), + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + or_( + FreightRpaInboundReportFile.archive_expires_at.is_(None), + FreightRpaInboundReportFile.archive_expires_at > now, + ), + ) + .order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc()) + .all() + ) + return [_inbound_file_view(report) for report in reports] + + +def list_inbound_configured_source_codes() -> list[str]: + """列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省范围 + (inbound_trigger_service.list_inbound_capable_source_codes 委托本函数) + ——入站文件只能来自已配置入站报表的启用站点。 + 核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。 + + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + rows = db.session.query(FreightRpaSource.source_code).join( + FreightRpaInboundReportConfig, + FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all() + return [str(code) for (code,) in rows] + + +def latest_usable_inbound_file( + source_code: str, + *, + now: datetime | None = None, +) -> InboundFileView | None: + """返回某来源当前「可用」的入站归档文件只读视图,最新优先。 + + 用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有 + _latest_usable_report_file 相同——经执行单元行的 source_code 过滤, + 可用门禁(未删除 + 当天业务日抓取 + 未过期,见 + usable_inbound_file_condition),按 created_at/id 倒序取第一条。 + 只读不写、不 flush 不 commit。 + + Args: + source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。 + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + 仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。 + Returns: + InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。 + """ + report = ( + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter( + FreightRpaInboundReportFile.unit_run.has(source_code=source_code), + usable_inbound_file_condition(now=now), + ) + .order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()) + .first() + ) + if report is None: + return None + return _inbound_file_view(report) + + +def read_inbound_file_bytes(file_id: int) -> bytes: + """按 file_id 读取入站归档文件的对象字节。 + + 用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自 + 持有模型 + file_asset_storage 的双跳查询。 + 核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError + (fail-closed);[STEP 2] 以文件的 storage_key 调 + file_asset_storage.get_bytes 读取并返回字节(不含元数据)。 + + Args: + file_id: 归档文件主键(int;禁止传入非整数 ID)。 + Returns: + 文件完整字节内容。 + Raises: + NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。 + """ + report = db.session.get(FreightRpaInboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Inbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + return file_asset_storage.get_bytes(report.storage_key) + + +def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None: + """标记一份入站归档文件解析失败(写入解析失败三分层列)。 + + 用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上, + 使来源状态投影为 parse_failed、阻止下游当作 ready 使用。 + 核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新 + parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/ + parse_error_message(截断 2000)三列;[STEP 3] db.session.flush() + 使同事务内投影立即可见。【不 commit】——调用方处于自己的事务, + 提交/回滚归属调用方,service 层禁止越权提交。 + + Args: + file_id: 归档文件主键(须已入库)。 + error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。 + error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。 + Returns: + None。失败标记随调用方事务落库。 + Raises: + NotFoundError: file_id 对应的归档文件不存在。 + """ + report = db.session.get(FreightRpaInboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Inbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + report.parse_failed_at = datetime.utcnow() + report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX] + report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX] + db.session.flush() + + +def clear_inbound_parse_failure(file_id: int) -> None: + """清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。 + + 用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被 + 清理/过期后调用(无业务意义)。 + 核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作 + 同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at / + parse_error_code / parse_error_message 置 None(三者全空即未失败的 + 约定态);[STEP 3] flush。【不 commit】——事务归属调用方。 + + Args: + file_id: 归档文件主键(须已入库)。 + Returns: + None。清除随调用方事务落库。 + Raises: + NotFoundError: file_id 对应的归档文件不存在。 + """ + report = db.session.get(FreightRpaInboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Inbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + report.parse_failed_at = None + report.parse_error_code = None + report.parse_error_message = None + db.session.flush() \ No newline at end of file diff --git a/backend/app/services/freight_rpa/upload/trigger_io.py b/backend/app/services/freight_rpa/upload/trigger_io.py index 1c0fe2ad..7a15f07c 100644 --- a/backend/app/services/freight_rpa/upload/trigger_io.py +++ b/backend/app/services/freight_rpa/upload/trigger_io.py @@ -7,10 +7,10 @@ services/freight_rpa/upload/trigger_io.py (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、 freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用, - 与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相 - ([PROMPT_UPDATE] 2026-10-16 批次 R 新裁定:upload 契约随发布窗口一次切换—— - action 由 shipment_upload 改为 outbound_upload、schema 由 shipping_notice_upload_rpa.v1 - 改为 freight_rpa.upload.v1,Worker 侧 Task 12 同窗口对齐,旧串全仓清零)。 + 与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相。 + upload 是与 onhand/inbound/outbound 同级的独立域;action 对齐心跳能力 + freight_rpa_upload(FREIGHT_RPA_UPLOAD_CAPABILITY),禁止 outbound_* / shipment_* 作为 upload action; + schema 为 freight_rpa.upload.v1(批次 R 曾误用 outbound 词根,已纠回 freight_rpa_upload)。 """ from __future__ import annotations @@ -28,7 +28,7 @@ from flask import current_app # Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见 # scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。 SCHEMA = "freight_rpa.upload.v1" -ACTION_OUTBOUND_UPLOAD = "outbound_upload" +ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload" def _path(key: str) -> Path | None: @@ -124,7 +124,7 @@ def write_upload_trigger( resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}' body = { - "action": ACTION_OUTBOUND_UPLOAD, + "action": ACTION_FREIGHT_RPA_UPLOAD, "schema_version": SCHEMA, "task_no": task_no, "attempt_id": attempt_id, diff --git a/backend/app/services/in_transit_transfer/backlog_reparse_service.py b/backend/app/services/in_transit_transfer/backlog_reparse_service.py index 3345f71c..575799df 100644 --- a/backend/app/services/in_transit_transfer/backlog_reparse_service.py +++ b/backend/app/services/in_transit_transfer/backlog_reparse_service.py @@ -8,7 +8,8 @@ (解析+组装单一口径)与 _detect_natural_key_collapses/_natural_key_collapse_event (档自然键坍缩守卫与运行期同口径复用)、ledger_sync(sync_ledger_rows / RECORD_KIND_INBOUND / FileMeta)、matching_service._effective_occupancy_filter - (占用排除口径,只读引用)、file_asset_storage、audit。 + (占用排除口径,只读引用)、freight_rpa.reports.queries(站点与入站解析方案 + 只读入口——阶段 B Task 4 收敛)、file_asset_storage、audit。 逻辑:桶数据 100% 可由 MinIO 归档重建(原件长期保留 + 档行 sheet/row_no 溯源), 清空不是破坏性操作而是「从证据重建」。安全不变量:先全量预解析入内存, 任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED), @@ -42,8 +43,12 @@ from sqlalchemy import func from app import db from app.core.errors import AppError -from app.models import ShippingInventorySource, TransferInvoiceItem, TransferMovementLedger +from app.models import TransferInvoiceItem, TransferMovementLedger from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.reports.queries import ( + get_inbound_parsing_profile, + get_site, +) from app.services.in_transit_transfer.audit import build_transfer_audit_event from app.services.in_transit_transfer.evidence_sync import ( _detect_natural_key_collapses, @@ -100,24 +105,23 @@ class ReparseOutcome: def _load_published_inbound_profile(source_code: str): """加载来源当前绑定的「已发布 inbound」解析规则(与运行期取数同口径)。 - 核心逻辑:来源(enabled)→ 收料配置 → parsing_profile,须 published 且 + 核心逻辑:来源(enabled)→ 入站配置 → parsing_profile,须 published 且 purpose='inbound'——与 latest_ready_file 的规则门禁一致,防止重建用了 运行期不会使用的规则口径。只读查询。 + 【阶段 B Task 4】读取改经 freight_rpa.reports.queries 只读入口 + (get_site / get_inbound_parsing_profile),不再引用站点/报表模型;返回 + InboundProfileView(code/version/definition 消费面不变)。 Args: source_code: 来源实例编码。 Returns: - ShippingInventoryParsingProfile;无启用来源/无收料配置/规则缺失或 + InboundProfileView;无启用来源/无入站配置/规则缺失或 非 published inbound 时返回 None(=无重建通道)。 """ - source = ShippingInventorySource.query.filter_by( - source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: return None - config = source.receipt_report_config - if config is None or config.parsing_profile_id is None: - return None - profile = config.parsing_profile + profile = get_inbound_parsing_profile(source_code) if profile is None or profile.status != "published" or profile.purpose != "inbound": return None return profile diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py index 25896506..7f6c7b1f 100644 --- a/backend/app/services/in_transit_transfer/deps.py +++ b/backend/app/services/in_transit_transfer/deps.py @@ -3,7 +3,7 @@ 用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。 依赖:movement_file_repository / capability_client / matching_service / models / Flask config。 逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository - (复用 ShippingReceiptReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由 + (复用 ShippingInboundReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由 匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed); 策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_ @@ -18,7 +18,12 @@ from typing import Any from flask import current_app -from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.models import FreightRpaOnhandExternalMapping +from app.services.freight_rpa.reports.queries import ( + get_inbound_config, + get_inbound_parsing_profile, + get_site, +) from app.services.in_transit_transfer.capability_client import CapabilityClient from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository from app.services.in_transit_transfer.matching_service import ( @@ -47,6 +52,11 @@ class DefaultRouteResolver: def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping: """按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。 + 【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经 + freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型; + 外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings + 不改归属,见计划 Global Constraints),按站点主键直查。 + Args: source_code: 来源实例编码(须启用)。 invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。 @@ -56,14 +66,14 @@ class DefaultRouteResolver: Raises: RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。 """ - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: raise RouteNotResolvedError(source_code=source_code) - mappings = ShippingInventoryExternalMapping.query.filter_by( - inventory_source_id=source.id, enabled=True, + mappings = FreightRpaOnhandExternalMapping.query.filter_by( + source_id=site.source_id, enabled=True, ).all() selected = None - if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match': + if site.warehouse_resolution_mode == 'inventory_match': # [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。 # 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。 key = str(warehouse_code or '').strip().upper() @@ -158,24 +168,24 @@ def get_transfer_dependencies() -> TransferDeps: class _DefaultRpaTrigger: """默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。 - 真实链路 = 落单元行 + 原子写 trigger 文件;来源/ShippingReceiptReportConfig 缺失或 trigger + 真实链路 = 落单元行 + 原子写 trigger 文件;站点/入站配置缺失或 trigger 目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。 - 另在本类前置守卫: ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时 + 另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时 直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。 + 【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口 + (get_site / get_inbound_config / get_inbound_parsing_profile)。 """ def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa - # [守卫] ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳: + # [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳: # 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。 - from app.models import ShippingInventorySource, ShippingReceiptReportConfig - - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is not None: - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first() + site = get_site(source_code) + if site is not None and site.enabled: + config = get_inbound_config(source_code) if config is not None: - profile = config.parsing_profile + profile = get_inbound_parsing_profile(source_code) if profile is None or profile.status != 'published' or profile.purpose != 'inbound': return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'} diff --git a/backend/app/services/in_transit_transfer/evidence_sync.py b/backend/app/services/in_transit_transfer/evidence_sync.py index 29c3cd22..f94bbdd7 100644 --- a/backend/app/services/in_transit_transfer/evidence_sync.py +++ b/backend/app/services/in_transit_transfer/evidence_sync.py @@ -1,9 +1,13 @@ """services/in_transit_transfer/evidence_sync.py -用途:入站证据同步——把来源最新可用入站文件(ShippingReceiptReport RPA 产物)解析并镜像落档(库存异动档 +用途:入站证据同步——把来源最新可用入站文件(freight_rpa 入站 RPA 产物)解析并镜像落档(库存异动档 transfer_movement_ledger,主链路),一次解析、写档不写明细。 -依赖:file_parser / ledger_sync / source_file_status / matching_service - (_latest_usable_report_file 复用)/ contracts / models / audit。 +依赖:file_parser / ledger_sync / freight_rpa.reports.queries(最新可用归档视图 + latest_usable_inbound_file 与解析失败标记 mark/clear——只读只写入口唯一权威)/ + source_file_status(状态投影)/ contracts / audit。 + 【阶段 B Task 4】文件取数不再经 matching_service._latest_usable_report_file + (该函数已删除),改按 source_code 直调 freight_rpa.reports.queries;解析失败 + 标记改按 file_id 调 mark_inbound_parse_failure / clear_inbound_parse_failure。 逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items ——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行: ①按自然键查档不存在 → 插入(record_kind/溯源五列随行); @@ -45,6 +49,11 @@ from decimal import Decimal from typing import Any, Mapping from app import db +from app.services.freight_rpa.reports.queries import ( + clear_inbound_parse_failure, + latest_usable_inbound_file, + mark_inbound_parse_failure, +) from app.services.in_transit_transfer.audit import build_transfer_audit_event from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID from app.services.in_transit_transfer.file_parser import ( @@ -57,11 +66,6 @@ from app.services.in_transit_transfer.ledger_sync import ( FileMeta, sync_ledger_rows, ) -from app.services.in_transit_transfer.matching_service import _latest_usable_report_file -from app.services.in_transit_transfer.source_file_status import ( - clear_inbound_parse_failure, - record_inbound_parse_failure, -) # 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码), # 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在 @@ -318,13 +322,14 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim # [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行 # commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库 # 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。 - report = _latest_usable_report_file(source_code) + # 【阶段 B Task 4】文件身份改取 freight_rpa.reports.queries 只读视图(主键 file_id)。 + file_view = latest_usable_inbound_file(source_code) outcome = sync_ledger_rows( source_code=source_code, record_kind=RECORD_KIND_INBOUND, parsed_rows=assembled, file_meta=FileMeta( - source_file_id=report.id if report is not None else None, + source_file_id=file_view.file_id if file_view is not None else None, file_version=ready.file_version, file_sha256=ready.checksum, ), @@ -365,9 +370,9 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim )) # [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析 # 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit, - # 提交归调用方。无可用 ORM 文件时为 no-op。 - if report is not None and report.parse_failed_at is not None: - clear_inbound_parse_failure(report=report) + # 提交归调用方。无可用归档时为 no-op。 + if file_view is not None and file_view.parse_failed_at is not None: + clear_inbound_parse_failure(file_view.file_id) return result @@ -375,8 +380,8 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d """入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。 【AI 触发时机】:入站 RPA 回调 success 终态落文件后由 - shipping_notice 域 ShippingReceiptReport 归档存储的桥函数调用——桥是记账 - 不是入站链路的正确性依赖,任何异常不得向 ShippingReceiptReport 归档主链路传播(B3:必须自行 commit)。 + shipping_notice 域 ShippingInboundReport 归档存储的桥函数调用——桥是记账 + 不是入站链路的正确性依赖,任何异常不得向 ShippingInboundReport 归档主链路传播(B3:必须自行 commit)。 【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类 解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上; 丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底 @@ -407,7 +412,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d return True except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」) # [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃 - # 绝不允许波及 ShippingReceiptReport 归档终态;丢失的落档由回调重试/人工重取兜底。 + # 绝不允许波及 ShippingInboundReport 归档终态;丢失的落档由回调重试/人工重取兜底。 current_app.logger.warning( "TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc) db.session.rollback() @@ -419,15 +424,15 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d # [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows # 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。 # 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉, - # B3(任何异常不得向 ShippingReceiptReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。 + # B3(任何异常不得向 ShippingInboundReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。 try: code = getattr(exc, "code", None) or "" if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError): detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__ - report = _latest_usable_report_file(source_code) - if report is not None: - record_inbound_parse_failure( - report=report, + file_view = latest_usable_inbound_file(source_code) + if file_view is not None: + mark_inbound_parse_failure( + file_view.file_id, error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID), error_message=str(detail)[:2000], ) diff --git a/backend/app/services/in_transit_transfer/file_preparation.py b/backend/app/services/in_transit_transfer/file_preparation.py index b8e95898..08984607 100644 --- a/backend/app/services/in_transit_transfer/file_preparation.py +++ b/backend/app/services/in_transit_transfer/file_preparation.py @@ -1,7 +1,7 @@ """在途调拨入站文件 Ready 复用与来源级 RPA 触发。 用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件; - 存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingReceiptReport RPA + 存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域术语保留);存在活动 Source Job 时绑定已有任务,保证并发请求只触发一次抓取。 依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。 diff --git a/backend/app/services/in_transit_transfer/inbound_callback_bridge.py b/backend/app/services/in_transit_transfer/inbound_callback_bridge.py index 8cfac5f7..1445d212 100644 --- a/backend/app/services/in_transit_transfer/inbound_callback_bridge.py +++ b/backend/app/services/in_transit_transfer/inbound_callback_bridge.py @@ -1,11 +1,15 @@ """在途调拨入站回调桥。 -用途:货代入站 RPA(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留) +用途:货代入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域,术语保留) 回调落文件后,按来源推进调拨等待中的 TransferSourceJob: success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。 依赖:models(TransferSourceJob)、datetime。 逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作, - 避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。 + 避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数 + handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后 + 经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥 + (inbound_report_storage._advance_transfer_source_job)仍走本函数。 + SourceJob 状态为字符串常量(见 models)。 """ from __future__ import annotations diff --git a/backend/app/services/in_transit_transfer/inbound_file_gate.py b/backend/app/services/in_transit_transfer/inbound_file_gate.py index 2b340a7d..dc77c0dd 100644 --- a/backend/app/services/in_transit_transfer/inbound_file_gate.py +++ b/backend/app/services/in_transit_transfer/inbound_file_gate.py @@ -1,70 +1,20 @@ -"""在途调拨入站归档文件的可用性门禁(单一事实来源)。 +"""在途调拨入站归档文件的可用性门禁(口径唯一,语义归 freight_rpa.reports 维护)。 -用途:把「一份 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA 产物, - shipping_notice 域,术语保留)是否可用于调拨链路」的判定收敛为本模块, - 供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、 - 入站文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。 -依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。 -逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期; - 已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。 - 两函数同核推导,规则文本只存在一处。 +用途:把「一份入站归档文件是否可用于调拨链路」的判定收敛为 + freight_rpa/reports/queries 的权威实现,并向调拨域既有 import 路径 + (api 下载、历史消费方)透传,防止口径漂移。 +依赖:freight_rpa.reports.queries(usable / expired 过滤表达式的唯一权威)。 +逻辑:【阶段 B Task 4】本模块不再自带表达式实现,自身不 import 任何 + freight_rpa 报表模型;可用 = 未删除 + 当天(Asia/Shanghai 业务日)抓取 + + 未过保留期;已失效(expired)= 未删除 且 该核心不成立——两条件同核 + 推导,规则文本与业务日窗口换算见 queries.py(禁止反向 import 出现环)。 """ from __future__ import annotations -from datetime import datetime +from app.services.freight_rpa.reports.queries import ( + expired_inbound_file_condition, + usable_inbound_file_condition, +) -from sqlalchemy import ColumnElement, and_, not_, or_ - -from app.models import ShippingReceiptReportFile -from app.services.in_transit_transfer.date_policy import business_date_utc_window - - -def _fresh_and_retention_valid(now: datetime) -> ColumnElement: - """新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。""" - window_start, window_end = business_date_utc_window(now) - return and_( - ShippingReceiptReportFile.created_at >= window_start, - ShippingReceiptReportFile.created_at < window_end, - or_( - ShippingReceiptReportFile.archive_expires_at.is_(None), - ShippingReceiptReportFile.archive_expires_at > now, - ), - ) - - -def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement: - """返回「当前可用的入站归档文件」SQL 条件。 - - 判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 - + 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载 - 只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。 - - Args: - now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 - Returns: - 可直接并入 .filter() 的单个 SQLAlchemy 条件。 - """ - now = now or datetime.utcnow() - return and_( - ShippingReceiptReportFile.archive_deleted_at.is_(None), - _fresh_and_retention_valid(now), - ) - - -def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement: - """返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。 - - 判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。 - 命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。 - - Args: - now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 - Returns: - 可直接并入 .filter() 的单个 SQLAlchemy 条件。 - """ - now = now or datetime.utcnow() - return and_( - ShippingReceiptReportFile.archive_deleted_at.is_(None), - not_(_fresh_and_retention_valid(now)), - ) +__all__ = ["expired_inbound_file_condition", "usable_inbound_file_condition"] \ No newline at end of file diff --git a/backend/app/services/in_transit_transfer/inbound_report_handler.py b/backend/app/services/in_transit_transfer/inbound_report_handler.py new file mode 100644 index 00000000..025f2f7f --- /dev/null +++ b/backend/app/services/in_transit_transfer/inbound_report_handler.py @@ -0,0 +1,134 @@ +""" +services/in_transit_transfer/inbound_report_handler.py + +用途:inbound 报表事实的调拨侧业务处理函数(阶段 B Task 7)——收料归档 + 终态 commit 后由 dispatch_report_fact 投递的 ReportFact 只在此推进 + 调拨自己的任务:TransferSourceJob 终态推进、调拨证据同步、收料排程收口。 +依赖:app.db、app.models(FreightRpaInboundUnitRun——执行单元读取;报表文件/ + 配置模型禁止在本包引用,边界由 test_inbound_report_read_boundary 锁定)、 + app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact / + require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、 + in_transit_transfer.inbound_callback_bridge / evidence_sync(同包)。 +逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_inbound_sinks) + 注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive. + ingest_inbound_callback 在每个终态 db.session.commit() 之后经 + dispatch_report_fact 调入本函数。处理函数只改调拨自己的行; + 【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚, + Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import ValidationError +from app.models import FreightRpaInboundUnitRun +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind +from app.services.in_transit_transfer.inbound_callback_bridge import ( + advance_source_job_from_inbound_callback, +) + + +def handle_inbound_report(fact: ReportFact) -> None: + """report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready; + ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。 + + (Task 7 契约 docstring 逐字保留如上;以下为补充说明。) + + 核心逻辑: + [STEP 1] kind 门禁(fail-closed);[STEP 2] 经桥推进等待中的来源任务(桥只改 + status='waiting_rpa_callback' 的行,无等待行返回 None——「没有等待行则 return」 + 指调拨侧无任务行可改,第二次投递时该行已离开等待态,桥天然不重复推进); + [STEP 3] 桥只 flush 不 commit,推进结果必须在此提交(B3 持久性);[STEP 4] + success 事实触发调拨证据同步(与拆分前终态收尾同口径:按 ok 触发、不依赖 + 等待任务存在——独立收料批次无调拨任务也须把最新可用文件镜像落档; + 桥内自吞异常并自行 commit,本处不包 try);[STEP 5] 精确定位「本次回调收尾的 + 执行单元」并回写收料排程进度、归集终态(finalize 函数住在 schedule 包—— + freight_rpa 禁止 import 它,只能由本处理函数调用;「仍由该处理函数调用」= 拆分 + 前每笔终态回调后的收口行为保持不变;Task 7 修复轮 2 起定位依据为 fact.unit_run_id + ——归档入口每次投递(含 failure/empty 与幂等重放)自单元行回填,success 与 + failure 同一机制,绝不按来源/错误文本猜「最新单元」)。 + 【不捕获异常】任何一步失败原样外抛供 Worker 重试。 + + Args: + fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/ + file_id/sha256/ok/error_code/error_message)。 + Returns: + None(推进/同步/收口结果全部写库,不返回业务值)。 + Raises: + ValidationError: report_kind 非 inbound(误注册/误分发,fail-closed)。 + """ + # [STEP 1] kind 门禁:本函数只消费 inbound 事实(dispatch 已按 kind 路由, + # 此处防御性复核,防止误注册成其他 kind 的处理函数后静默错写调拨行)。 + kind = require_report_kind(fact.report_kind) + if kind != 'inbound': + raise ValidationError( + f"handle_inbound_report only accepts inbound facts, got: {kind!r}", + code='SHIPPING.RECEIPT_CALLBACK_INVALID', + details={'report_kind': fact.report_kind}, + ) + + # [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready(绑定 + # 文件号/指纹);否则 → failed(带错误码/描述)。桥只改 waiting_rpa_callback 行; + # 无等待行返回 None(调拨侧无行可改,直接结束推进分支)。 + if fact.ok and fact.file_id is not None: + advanced = advance_source_job_from_inbound_callback( + source_code=fact.source_code, + file_no=str(fact.file_id), + file_sha256=fact.sha256, + callback_ok=True, + ) + else: + advanced = advance_source_job_from_inbound_callback( + source_code=fact.source_code, + callback_ok=False, + error_code=fact.error_code, + error_message=fact.error_message, + ) + + # [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交,否则请求结束回滚会 + # 丢掉已推进的任务(B3 持久性——empty/failed 且后续收口提前返回时无人提交)。 + if advanced is not None: + db.session.commit() + + # [STEP 4] 证据同步:success 事实(ok 且 file_id 有值)后把该来源最新可用 + # 入站文件镜像落档。与拆分前终态收尾同口径(按 ok 触发、不依赖等待任务 + # 存在——独立收料批次没有调拨任务,但其文件仍是运行期取数的证据源)。 + # sync_and_commit_for_callback 桥内自吞异常并自行 commit;本处不包 try, + # 若有异常原样外抛(文件已提交,Worker 重试即可补齐落档)。 + if fact.ok and fact.file_id is not None: + from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback + + now = datetime.utcnow() + sync_and_commit_for_callback( + source_code=fact.source_code, + business_date=str(now.date()), + now=now, + ) + + # [STEP 5] 收料排程收口:精确定位「本次回调收尾的执行单元」的排程 run(Task 7 + # 修复轮 2——事实自带 unit_run_id(归档入口每次投递自单元行回填),不再按来源/ + # 错误文本猜单元:同来源、同错误文本的新单元存在时旧回调不得收口错误的 run)。 + schedule_run_id: int | None = None + if fact.unit_run_id is not None: + # 归档入口产线恒回填 unit_run_id;None 仅为兼容手工构造事实的旧调用方—— + # 无单元标识时不猜(跳过收口,不做任何「最新单元」式近似)。 + unit = db.session.get(FreightRpaInboundUnitRun, int(fact.unit_run_id)) + if unit is None: + # 分发紧跟终态 commit:单元行缺失属硬性不一致,fail-closed 而非静默跳过。 + from app.core.errors import NotFoundError + + raise NotFoundError( + f"Inbound RPA unit not found: {fact.unit_run_id}", + details={'unit_run_id': fact.unit_run_id}, + ) + schedule_run_id = unit.schedule_run_id + if schedule_run_id: + from app.services.schedule.freight_rpa_inbound_finalize import ( + finalize_receipt_schedule_run_if_complete, + refresh_receipt_schedule_run_progress, + ) + + refresh_receipt_schedule_run_progress(schedule_run_id) + finalize_receipt_schedule_run_if_complete(schedule_run_id) diff --git a/backend/app/services/in_transit_transfer/inbound_trigger_service.py b/backend/app/services/in_transit_transfer/inbound_trigger_service.py index 47e9367f..4a7b38af 100644 --- a/backend/app/services/in_transit_transfer/inbound_trigger_service.py +++ b/backend/app/services/in_transit_transfer/inbound_trigger_service.py @@ -1,16 +1,20 @@ """在途调拨入站 RPA 触发服务。 -用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = ShippingReceiptReport RPA 产物, - 复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留),不创建排程。 - 按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile, - 先落 RPA 单元运行行(awaiting_rpa,回调按 callback_id 查库可达), - 再装配入站 trigger unit 并调用 write_inbound_export_batch_trigger 原子写 trigger。 -依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、models、db。 +用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = freight_rpa 入站 RPA 产物, + 复用货代入站 trigger 链路),不创建排程。按来源取站点、入站配置与登录连接 + (全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行 + (awaiting_rpa,回调按 callback_id 查库可达),再装配入站 trigger unit 并 + 调用 write_inbound_export_batch_trigger 原子写 trigger。 +依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、 + freight_rpa.reports.queries(get_site / get_inbound_config / get_rpa_login_profile / + list_inbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。 逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围; - 一源一单元,query_parameters 原样下发;来源停用/ShippingReceiptReportConfig 缺失/rpa_profile 缺失时 + 一源一单元,query_parameters 原样下发;来源停用/入站配置缺失/登录连接缺失时 fail-closed;写 trigger 失败把单元行标 failed 并 commit。 trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件: Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。 + 【阶段 B Task 4】trigger unit 载荷键集与 Worker 契约(freight_rpa.inbound.v1) + 逐键不变;读取改走只读函数后不再引用 freight_rpa 报表模型。 """ from __future__ import annotations @@ -24,6 +28,12 @@ from app.services.freight_rpa.inbound.trigger_io import ( SCHEMA, write_inbound_export_batch_trigger, ) +from app.services.freight_rpa.reports.queries import ( + get_inbound_config, + get_rpa_login_profile, + get_site, + list_inbound_configured_source_codes, +) RouteTriggerWriter = Callable[..., str | None] @@ -34,38 +44,39 @@ def _build_trigger_unit( """装配单来源入站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。 核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。 + 【阶段 B Task 4】站点(get_site)/ 入站配置(get_inbound_config)/ 登录连接 + (get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的 + unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。 """ - from app.models import ShippingInventorySource, ShippingReceiptReportConfig - - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: raise RuntimeError(f'source not enabled: {source_code}') - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first() + config = get_inbound_config(source_code) if config is None: raise RuntimeError(f'inbound config missing: {source_code}') - profile = source.rpa_profile + profile = get_rpa_login_profile(source_code) if profile is None or not profile.enabled: raise RuntimeError(f'inbound source profile unavailable: {source_code}') query_parameters = [ dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict) ] snapshot = { - 'config_id': config.id, 'config_version': config.config_version, - 'connector_type': source.connector_type, + 'config_id': config.config_id, 'config_version': config.config_version, + 'connector_type': site.connector_type, 'report_path_json': config.report_path_json or {}, 'query_parameters_json': query_parameters, - 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, + 'warehouse_id': None, 'rpa_profile_id': profile.profile_id, } return { - 'inventory_source_id': source.id, + 'source_id': site.source_id, 'callback_id': f'inbound:{uuid.uuid4().hex}', - 'source_code': source.source_code, - 'connector_type': source.connector_type, + 'source_code': site.source_code, + 'connector_type': site.connector_type, 'warehouse_id': None, - 'rpa_profile_id': profile.id, + 'rpa_profile_id': profile.profile_id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url, - 'login_config': dict(profile.login_config_json or {}), + 'login_config': dict(profile.login_config or {}), 'credential_envelope': { 'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext, @@ -79,21 +90,17 @@ def _build_trigger_unit( def list_inbound_capable_source_codes() -> list[str]: - """列出可产出入站文件的启用来源实例(enabled 库存源 + 已配置 ShippingReceiptReport)。 + """列出可产出入站文件的启用来源实例(已配置入站报表的启用站点)。 - 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件(ShippingReceiptReport - RPA 产物)只能来自已配置 ShippingReceiptReport 的站点,与货代 ShippingReceiptReport RPA 排程的站点口径一致。 + 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件 + 只能来自已配置入站报表的站点,与货代入站 RPA 排程的站点口径一致。 + 【阶段 B Task 4】站点×入站配置 join 查询改委托 + freight_rpa.reports.queries.list_inbound_configured_source_codes;本函数 + 保留为调拨域语义出口(既有调用方 import 路径不变)。 Returns: 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 """ - from app import db - from app.models import ShippingInventorySource, ShippingReceiptReportConfig - - rows = db.session.query(ShippingInventorySource.source_code).join( - ShippingReceiptReportConfig, - ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, - ).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all() - return [str(code) for (code,) in rows] + return list_inbound_configured_source_codes() def trigger_inbound_rpa( @@ -122,11 +129,11 @@ def trigger_inbound_rpa( # [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库, # 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。 from app import db - from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun + from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun - unit = ShippingInboundRpaUnitRun( + unit = FreightRpaInboundUnitRun( # 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。 - inventory_source_id=unit_payload['inventory_source_id'], + source_id=unit_payload['source_id'], source_code=unit_payload['source_code'], connector_type=unit_payload['connector_type'], warehouse_id=unit_payload.get('warehouse_id'), @@ -192,13 +199,13 @@ def trigger_inbound_rpa_batch( 跳过:{source_code, ok: false, error_code, error_message})。 """ from app import db - from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun + from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback from app.services.in_transit_transfer.source_file_status import resolve_source_file_status codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip())) results: list[dict[str, Any]] = [] - units: list[ShippingInboundRpaUnitRun] = [] + units: list[FreightRpaInboundUnitRun] = [] unit_payloads: list[dict[str, Any]] = [] # [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。 @@ -234,8 +241,8 @@ def trigger_inbound_rpa_batch( # [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。 for payload in unit_payloads: - unit = ShippingInboundRpaUnitRun( - inventory_source_id=payload['inventory_source_id'], + unit = FreightRpaInboundUnitRun( + source_id=payload['source_id'], source_code=payload['source_code'], connector_type=payload['connector_type'], warehouse_id=payload.get('warehouse_id'), diff --git a/backend/app/services/in_transit_transfer/ledger_sync.py b/backend/app/services/in_transit_transfer/ledger_sync.py index 41bbea46..1e31fcda 100644 --- a/backend/app/services/in_transit_transfer/ledger_sync.py +++ b/backend/app/services/in_transit_transfer/ledger_sync.py @@ -45,7 +45,7 @@ assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__ # record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。 INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"}) -# 记录种类字面量:inbound=入站(ShippingReceiptReport RPA 产物,shipping_notice 域术语保留); +# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留); # outbound=出站(出货侧结构就位)。 RECORD_KIND_INBOUND = "inbound" RECORD_KIND_OUTBOUND = "outbound" @@ -58,7 +58,7 @@ class FileMeta: """一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。 Args: - source_file_id: 入站原样归档文件 id(shipping_receipt_report_files.id; + source_file_id: 入站原样归档文件 id(freight_rpa_inbound_report_files.id; 测试/极端场景可为 None——档事实留存不依赖文件存在)。 file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。 file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。 @@ -158,7 +158,7 @@ def sync_ledger_rows( Args: source_code: 来源实例编码(自然键成分,整批一致)。 - record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingReceiptReport + record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingInboundReport RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。 parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code (movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与 diff --git a/backend/app/services/in_transit_transfer/matching_service.py b/backend/app/services/in_transit_transfer/matching_service.py index 5af83494..0e82e239 100644 --- a/backend/app/services/in_transit_transfer/matching_service.py +++ b/backend/app/services/in_transit_transfer/matching_service.py @@ -6,7 +6,9 @@ 依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/ scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/ source_file_status / capability_client / date_policy / quantity / contracts / - audit / models。 + audit / models。【阶段 B Task 4】取可用入站归档文件的查询已删除并收口到 + freight_rpa.reports.queries.latest_usable_inbound_file(匹配不再引用 + freight_rpa 报表模型;证据链消费方见 evidence_sync)。 逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由 本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind= 'inbound' + 来源 IN + movement_date 范围 + transfer_executed=false + @@ -40,7 +42,6 @@ from sqlalchemy import and_, or_ from app import db from app.core.errors import AppError, NotFoundError, ValidationError from app.models import ( - ShippingReceiptReportFile, TransferInvoiceItem, TransferMatching, TransferMovementLedger, @@ -70,7 +71,6 @@ from app.services.in_transit_transfer.file_preparation import ( ) from app.services.in_transit_transfer.ledger_sync import RECORD_KIND_INBOUND from app.services.in_transit_transfer.quantity import classify_quantity_match -from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition from app.services.in_transit_transfer.scope_rules import ( ScopeRule, apply_scope_filters, @@ -201,37 +201,6 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun return "success" -def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None: - """返回某来源当前「可用」(当天抓取且未清理未过期)的入站归档文件,最新优先。 - - 【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用 - 文件上(parse_failed 三列)、或落档成功后清除其标记、或档落地回填 - source_file_id 时调用——查询口径与 - source_file_status.resolve_source_file_status 的可用文件判定一致 - (inbound_file_gate.usable_inbound_file_condition),防止两处口径漂移。 - - 核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run - 关联单元运行行的 source_code)+ 可用门禁过滤;[STEP 2] 按 - created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。 - - Args: - source_code: 来源实例编码(入站执行单元行上的 source_code)。 - Returns: - 最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/ - 已清理)返回 None。 - """ - return ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - usable_inbound_file_condition(), - ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) - .first() - ) - - def _validate_movement_date_range( business_date: str, movement_date_from: str | None, movement_date_to: str | None, ) -> tuple[date | None, date | None]: diff --git a/backend/app/services/in_transit_transfer/movement_contract.py b/backend/app/services/in_transit_transfer/movement_contract.py index e0b5aaa1..66f0b687 100644 --- a/backend/app/services/in_transit_transfer/movement_contract.py +++ b/backend/app/services/in_transit_transfer/movement_contract.py @@ -41,7 +41,7 @@ class MovementField: # 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。 -# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingReceiptReport External ASN #); +# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingInboundReport External ASN #); # 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。 # [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。 # [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号 diff --git a/backend/app/services/in_transit_transfer/movement_file_repository.py b/backend/app/services/in_transit_transfer/movement_file_repository.py index 586d639f..9088e8de 100644 --- a/backend/app/services/in_transit_transfer/movement_file_repository.py +++ b/backend/app/services/in_transit_transfer/movement_file_repository.py @@ -1,18 +1,23 @@ """在途调拨真实异动(入站/出站)文件仓库。 -用途:读取货代入站链路已落库的 ShippingReceiptReportFile(入站证据 = ShippingReceiptReport RPA - 产物,shipping_notice 域术语保留;对象存储原始 xlsx), - 用该来源 ShippingReceiptReportConfig 绑定的 inbound 解析规则(purpose='inbound',端点=定死 - 领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyInboundFile。 -依赖: ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、 - movement_contract、inbound_file_gate(可用性门禁)、openpyxl。 -逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、 - 文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域 +用途:读取货代入站链路已落库的入站归档文件(入站证据 = freight_rpa 入站 + RPA 产物,对象存储原始 xlsx),用该来源入站报表配置绑定的 inbound + 解析规则(purpose='inbound',端点=定死领域字段 MOVEMENT_FIELDS)的 + field_mapping 把列映射为领域行,产出 ReadyInboundFile。 +依赖:【阶段 B Task 4】freight_rpa.reports.queries(站点 get_site / 入站配置 + get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用 + 归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes / + 维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、 + file_preparation(ReadyInboundFile 契约)、openpyxl。 +逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新 + 【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失 + 或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域 字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整 校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内 折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。 - 另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):同一 join - 路径但显式去掉当日门禁,仅供 backlog_reparse_service 使用,运行期禁用。 + 另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道): + 委托 queries 维护通道查询(同一 join 路径但显式去掉当日门禁),仅供 + backlog_reparse_service 使用,运行期禁用。 """ from __future__ import annotations @@ -23,11 +28,15 @@ from datetime import datetime from io import BytesIO from typing import Any, Mapping -from sqlalchemy import or_ - -from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.reports.queries import ( + get_inbound_config, + get_inbound_parsing_profile, + get_site, + latest_usable_inbound_file, + list_reparseable_inbound_files, + read_inbound_file_bytes, +) from app.services.in_transit_transfer.file_preparation import ReadyInboundFile -from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition # 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。 _HEADER_WS_RE = re.compile(r"\s+") @@ -38,7 +47,7 @@ class ReparseableArchiveFile: """一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。 Args: - file_id: 归档文件 id(shipping_receipt_report_files.id,档行溯源列同源)。 + file_id: 归档文件 id(入站归档文件表主键,档行溯源列同源)。 storage_key: 对象存储键(重建时按此取归档字节)。 sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。 file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。 @@ -66,14 +75,24 @@ def _normalize_header_label(value: Any) -> str: class ShippingInboundFileRepository: - """真实入站/异动 ready 文件仓库(复用 ShippingReceiptReport 归档 + inbound 解析规则)。""" + """真实入站/异动 ready 文件仓库(复用 freight_rpa 入站归档 + inbound 解析规则)。 - def __init__(self) -> None: - self._storage = file_asset_storage + 【阶段 B Task 4】模型/存储读取全部收敛到 freight_rpa.reports.queries 只读 + 入口,本类不再 import freight_rpa 报表模型或对象存储客户端;对调用方 + (file_preparation / deps / backlog_reparse_service)的类名与方法签名不变。 + """ def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None: """返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。 + 核心逻辑:[STEP 1] 站点须启用(get_site)+ 入站配置须存在 + (get_inbound_config)+ 绑定解析方案须 published inbound + (get_inbound_parsing_profile,与运行期规则门禁同一口径); + [STEP 2] 取最新可用归档视图(latest_usable_inbound_file,当天 + fail-closed 门禁见 queries.usable_inbound_file_condition)并按 + file_id 读归档字节(read_inbound_file_bytes);[STEP 3] 按方案 + field_mapping 提取领域行。 + Args: source_code: 来源实例编码。 business_date: 业务日期(用于展示,不强制匹配文件日期)。 @@ -81,45 +100,34 @@ class ShippingInboundFileRepository: ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。 新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。 """ - from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile - - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: return None - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first() + config = get_inbound_config(source_code) if config is None or config.parsing_profile_id is None: return None - profile = config.parsing_profile + profile = get_inbound_parsing_profile(source_code) if profile is None or profile.status != 'published' or profile.purpose != 'inbound': return None - report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - # 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 inbound_file_gate。 - usable_inbound_file_condition(), - ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) - .first() - ) - if report is None: + view = latest_usable_inbound_file(source_code) + if view is None: return None - data = self._storage.get_bytes(report.storage_key) + definition = profile.definition_json or {} + data = read_inbound_file_bytes(view.file_id) rows = _extract_movement_rows( data, - field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}), - sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None, - header_row_index=(profile.definition_json or {}).get('header_row_index'), + field_mapping=dict(definition.get('field_mapping') or {}), + sheet_name=str(definition.get('sheet_name') or '').strip() or None, + header_row_index=definition.get('header_row_index'), ) return ReadyInboundFile( source_code=source_code, business_date=business_date, - file_no=report.original_filename or str(report.id), - file_version=f"sha256:{report.sha256}"[:64], - checksum=report.sha256, + file_no=view.original_filename or str(view.file_id), + file_version=f"sha256:{view.sha256}"[:64], + checksum=view.sha256, rows=tuple(rows), ) @@ -130,13 +138,11 @@ class ShippingInboundFileRepository: (evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义, 本方法是显式的历史重建通道(spec §6),两者不得混用。 - 核心逻辑:join 路径与 latest_ready_file 的归档文件查询同款 - (ShippingReceiptReportFile → unit_run.has(source_code=...)),但显式去掉 - 「当天业务日抓取」新鲜度门禁——重建对象正是历史归档;保留期口径与 - inbound_file_gate 一致(archive_expires_at 为空视为长期有效),未清理 - (archive_deleted_at 空)且未过保留期(expires > now)才可重建。按归档 - 时间升序返回(重建必须按归档时间序重落,保证幂等重放顺序确定)。 - 只读查询,不触碰对象存储字节(字节由调用方按需经 file_asset_storage 取)。 + 核心逻辑:委托 freight_rpa.reports.queries.list_reparseable_inbound_files + 维护通道查询(同一 join 路径,显式去掉「当天业务日抓取」新鲜度门禁—— + 重建对象正是历史归档;保留期口径一致),并把只读视图映射为本仓库的 + 维护契约 ReparseableArchiveFile。只读查询,不触碰对象存储字节(字节 + 由调用方按需经 file_asset_storage 取)。 Args: source_code: 来源实例编码(经收料执行单元行 source_code 关联)。 @@ -144,34 +150,16 @@ class ShippingInboundFileRepository: Returns: ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。 """ - from app.models import ShippingReceiptReportFile - - reports = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - # 维护通道可用性 = 未清理 + 未过保留期(NULL=长期有效,与 - # inbound_file_gate 保留期口径一致);【刻意无当日门禁】。 - ShippingReceiptReportFile.archive_deleted_at.is_(None), - or_( - ShippingReceiptReportFile.archive_expires_at.is_(None), - ShippingReceiptReportFile.archive_expires_at > now, - ), - ) - .order_by(ShippingReceiptReportFile.created_at.asc(), ShippingReceiptReportFile.id.asc()) - .all() - ) return [ ReparseableArchiveFile( - file_id=report.id, - storage_key=report.storage_key, - sha256=report.sha256, - file_version=f"sha256:{report.sha256}"[:64], - archived_at=report.created_at, - original_filename=report.original_filename, + file_id=view.file_id, + storage_key=view.storage_key, + sha256=view.sha256, + file_version=f"sha256:{view.sha256}"[:64], + archived_at=view.created_at, + original_filename=view.original_filename, ) - for report in reports + for view in list_reparseable_inbound_files(source_code, now=now) ] @@ -196,7 +184,7 @@ def _extract_movement_rows( header_row_index: 1-based 表头行;空则自动探测。 """ from openpyxl import load_workbook - from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index + from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True) try: @@ -251,4 +239,4 @@ def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str if codes and index < len(row): for code in codes: output[code] = row[index] - return output + return output \ No newline at end of file diff --git a/backend/app/services/in_transit_transfer/source_file_status.py b/backend/app/services/in_transit_transfer/source_file_status.py index 57f55d88..28876348 100644 --- a/backend/app/services/in_transit_transfer/source_file_status.py +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -1,30 +1,31 @@ """在途调拨来源入站文件状态投影服务。 -用途:只读货代入站链路(入站证据 = ShippingReceiptReport RPA 产物,shipping_notice 域,术语保留) - 已有事实(ShippingInboundRpaUnitRun 别名 + ShippingReceiptReportFile), +用途:只读货代入站链路已有事实(入站执行单元行 + freight_rpa 入站归档文件), 按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 / 无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。 -依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile ,前者经域内别名引用)、 - inbound_file_gate(可用/失效判定单一事实来源)。 -逻辑:按来源取该来源最新入站执行单元;命中可用门禁(当天业务日抓取且未过期, - 见 inbound_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→ - parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断); - 有进行中单元 → fetching;最新单元为失败终态 → failed; - 文件仍在但已失效 → expired;否则 → none。 - record_inbound_parse_failure / clear_inbound_parse_failure 维护解析失败三列 - (写入与清除均只 flush 不 commit,事务归属调用方)。 +依赖:freight_rpa.reports.queries(最新可用入站归档 / 失效文件存在性 / 解析失败 + 标记的只读写入口——口径唯一权威);入站执行单元行模型(经域内别名引用)。 +逻辑:【阶段 B Task 4】模型查询全部改走 freight_rpa.reports.queries 只读入口—— + 可用文件命中(当天业务日抓取且未过期未清理,口径见 + queries.usable_inbound_file_condition)→ ready,但文件已标记解析失败 + (parse_failed_at 非空)→ parse_failed(不可当 ready,仍带 file_no/ + file_sha256 便于诊断);有进行中单元 → fetching;最新单元为失败终态 → + failed;空数据单元 → no_data;文件仍在但已失效 → expired;否则 → none。 + record/clear_inbound_parse_failure 保留为兼容薄壳(既有调用方按 ORM 文件 + 对象传参),内部按主键委托 queries.mark/clear 同一实现(写入与清除均只 + flush 不 commit,事务归属调用方)。 """ from __future__ import annotations -from datetime import datetime +from typing import Any -from app import db -from app.models import ShippingReceiptReportFile -from app.models.shipping_receipt_report import ShippingReceiptRpaUnitRun as ShippingInboundRpaUnitRun -from app.services.in_transit_transfer.inbound_file_gate import ( - expired_inbound_file_condition, - usable_inbound_file_condition, +from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun +from app.services.freight_rpa.reports.queries import ( + clear_inbound_parse_failure as _clear_parse_failure_by_id, + has_expired_inbound_file, + latest_usable_inbound_file, + mark_inbound_parse_failure as _mark_parse_failure_by_id, ) RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing') @@ -38,7 +39,8 @@ def resolve_source_file_status(*, source_code: str) -> dict: """返回某来源的入站文件状态投影。 失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见 - inbound_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。 + freight_rpa.reports.queries 的可用/失效条件):保留期已到 或 非当前业务日 + (Asia/Shanghai)抓取。 Returns: {"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...}, @@ -46,47 +48,41 @@ def resolve_source_file_status(*, source_code: str) -> dict: parse_failed 表示文件仍可用但解析失败:has_ready_file=False, 仍带 file_no/file_sha256 便于诊断与前端提示。 """ - report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - usable_inbound_file_condition(), - ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) - .first() - ) - if report is not None: + # 【阶段 B Task 4】可用文件读取经 freight_rpa.reports.queries 只读视图 + # (file_no/failure 事实列随视图一次取得,不再引用归档文件模型)。 + file_view = latest_usable_inbound_file(source_code) + if file_view is not None: + file_no = file_view.original_filename or str(file_view.file_id) # 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败, # 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。 - if report.parse_failed_at is not None: + if file_view.parse_failed_at is not None: return { 'file_status': 'parse_failed', 'has_ready_file': False, - 'file_no': report.original_filename or str(report.id), - 'file_sha256': report.sha256, + 'file_no': file_no, + 'file_sha256': file_view.sha256, } return { 'file_status': 'ready', 'has_ready_file': True, - 'file_no': report.original_filename or str(report.id), - 'file_sha256': report.sha256, + 'file_no': file_no, + 'file_sha256': file_view.sha256, } active_unit = ( - ShippingInboundRpaUnitRun.query + FreightRpaInboundUnitRun.query .filter_by(source_code=source_code) - .filter(ShippingInboundRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES)) - .order_by(ShippingInboundRpaUnitRun.id.desc()) + .filter(FreightRpaInboundUnitRun.status.in_(RUNNING_UNIT_STATUSES)) + .order_by(FreightRpaInboundUnitRun.id.desc()) .first() ) if active_unit is not None: return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} latest_unit = ( - ShippingInboundRpaUnitRun.query + FreightRpaInboundUnitRun.query .filter_by(source_code=source_code) - .order_by(ShippingInboundRpaUnitRun.id.desc()) + .order_by(FreightRpaInboundUnitRun.id.desc()) .first() ) if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES: @@ -96,16 +92,8 @@ def resolve_source_file_status(*, source_code: str) -> dict: return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} # 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。 - expired_report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - expired_inbound_file_condition(), - ) - .first() - ) - if expired_report is not None: + # 【阶段 B Task 4】失效存在性经 queries.has_expired_inbound_file(与可用条件同核)。 + if has_expired_inbound_file(source_code): return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} @@ -113,10 +101,9 @@ def resolve_source_file_status(*, source_code: str) -> dict: def record_inbound_parse_failure( *, - report: ShippingReceiptReportFile, + report: Any, error_code: str, error_message: str, - now: datetime | None = None, ) -> None: """标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。 @@ -124,40 +111,34 @@ def record_inbound_parse_failure( 让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后 改调 clear_inbound_parse_failure。 - 核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息; - [STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit, - 事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。 + 【阶段 B Task 4 兼容薄壳】全量语义(失败时刻取当前 UTC、错误码按 64 字符/ + 错误信息按 2000 字符截断、只 flush 不 commit——事务提交时机归属调用方)已 + 收口 freight_rpa.reports.queries.mark_inbound_parse_failure(唯一实现); + 本壳只为既有调用方按归档文件对象传参的签名而保留——取对象主键委托真实现。 Args: - report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。 - error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。 - error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。 - now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。 + report: 入站归档文件对象(仅取主键 .id;须已入库)。 + error_code: 机器可读错误码(真实现内按列宽截断)。 + error_message: 人类可读错误信息(真实现内做防御性截断)。 Returns: - None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。 + None。失败标记随调用方事务落库。 """ - report.parse_failed_at = now or datetime.utcnow() - report.parse_error_code = (error_code or '')[:64] - report.parse_error_message = (error_message or '')[:2000] - db.session.flush() + _mark_parse_failure_by_id(report.id, error_code=error_code, error_message=error_message) -def clear_inbound_parse_failure(*, report: ShippingReceiptReportFile) -> None: +def clear_inbound_parse_failure(*, report: Any) -> None: """清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。 【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态 投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。 - 核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message - 三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内 - 投影立即可见。只 flush 不 commit,事务提交时机归调用方。 + 【阶段 B Task 4 兼容薄壳】语义收口同 record_inbound_parse_failure:取对象 + 主键委托 freight_rpa.reports.queries.clear_inbound_parse_failure(置空三列 + 后 flush,不 commit,事务归属调用方)。 Args: - report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。 + report: 入站归档文件对象(仅取主键 .id;须已入库)。 Returns: - None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。 + None。清除随调用方事务落库。 """ - report.parse_failed_at = None - report.parse_error_code = None - report.parse_error_message = None - db.session.flush() + _clear_parse_failure_by_id(report.id) \ No newline at end of file diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py index 6152779f..3edcd460 100644 --- a/backend/app/services/schedule/__init__.py +++ b/backend/app/services/schedule/__init__.py @@ -343,8 +343,8 @@ def _register_headers_from_config() -> None: for name, cfg in get_all_schedule_sql_configs().items(): if cfg.alias_order and cfg.header_labels: register_schedule_header(name, cfg.alias_order, cfg.header_labels) - from app.services.schedule.freight_onhand_rpa_finalize import register_inventory_rpa_excel_headers - from app.services.schedule.freight_inbound_rpa_finalize import register_receipt_rpa_excel_headers + from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers + from app.services.schedule.freight_rpa_inbound_finalize import register_receipt_rpa_excel_headers register_inventory_rpa_excel_headers() register_receipt_rpa_excel_headers() diff --git a/backend/app/services/schedule/freight_inbound_rpa_archive.py b/backend/app/services/schedule/freight_rpa_inbound_archive.py similarity index 92% rename from backend/app/services/schedule/freight_inbound_rpa_archive.py rename to backend/app/services/schedule/freight_rpa_inbound_archive.py index 7d3a0ae0..b681eaab 100644 --- a/backend/app/services/schedule/freight_inbound_rpa_archive.py +++ b/backend/app/services/schedule/freight_rpa_inbound_archive.py @@ -1,9 +1,9 @@ """ -backend/app/services/schedule/freight_inbound_rpa_archive.py +backend/app/services/schedule/freight_rpa_inbound_archive.py 用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 -依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、 - file_asset_storage、timezone_util、freight_inbound_rpa_finalize.is_freight_receipt_rpa_task。 +依赖:ScheduleRun、FreightRpaInboundReportFile / FreightRpaInboundUnitRun、 + file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_receipt_rpa_task。 逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary; 企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`; warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。 @@ -21,9 +21,9 @@ from typing import Any from flask import current_app from app.core.errors import NotFoundError -from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun +from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun from app.services.file_assets.storage import file_asset_storage -from app.services.schedule.freight_inbound_rpa_finalize import is_freight_receipt_rpa_task +from app.services.schedule.freight_rpa_inbound_finalize import is_freight_receipt_rpa_task from app.services.schedule.timezone_util import resolve_schedule_tzinfo _RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员' @@ -111,7 +111,7 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str: def receipt_rpa_result_excel_name(run: ScheduleRun) -> str: - """收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。""" + """收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。""" return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx' @@ -127,20 +127,20 @@ def _iter_packable_receipt_files(run: ScheduleRun): 核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。 Yields: - ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。 + FreightRpaInboundReportFile: 可从 MinIO 读取的归档记录。 """ if not is_freight_receipt_rpa_task(getattr(run, 'task', None)): return rows = ( - ShippingReceiptReportFile.query.join( - ShippingReceiptRpaUnitRun, - ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id, + FreightRpaInboundReportFile.query.join( + FreightRpaInboundUnitRun, + FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id, ) .filter( - ShippingReceiptRpaUnitRun.schedule_run_id == run.id, - ShippingReceiptReportFile.archive_deleted_at.is_(None), + FreightRpaInboundUnitRun.schedule_run_id == run.id, + FreightRpaInboundReportFile.archive_deleted_at.is_(None), ) - .order_by(ShippingReceiptReportFile.id.asc()) + .order_by(FreightRpaInboundReportFile.id.asc()) .all() ) for report_file in rows: diff --git a/backend/app/services/schedule/freight_inbound_rpa_finalize.py b/backend/app/services/schedule/freight_rpa_inbound_finalize.py similarity index 94% rename from backend/app/services/schedule/freight_inbound_rpa_finalize.py rename to backend/app/services/schedule/freight_rpa_inbound_finalize.py index b7c282c9..69b9c354 100644 --- a/backend/app/services/schedule/freight_inbound_rpa_finalize.py +++ b/backend/app/services/schedule/freight_rpa_inbound_finalize.py @@ -1,9 +1,9 @@ """ -backend/app/services/schedule/freight_inbound_rpa_finalize.py +backend/app/services/schedule/freight_rpa_inbound_finalize.py 用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微; 另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。 -依赖:ShippingReceiptRpaUnitRun、freight_inbound_rpa_archive、scheduler_service 企微通知。 +依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。 逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom; 超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。 """ @@ -18,10 +18,10 @@ from sqlalchemy import func from app import db from app.models import ScheduleRun, ScheduleTask -from app.models import ShippingReceiptRpaUnitRun +from app.models import FreightRpaInboundUnitRun from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header from app.services.schedule.excel_service import export_schedule_result_excel -from app.services.schedule.freight_inbound_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY +from app.services.schedule.freight_rpa_inbound_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA from app.services.shipping_notice.audit_service import append_shipping_audit_event @@ -57,7 +57,7 @@ def register_receipt_rpa_excel_headers() -> None: ) -def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]: +def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]: """ 收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。 @@ -144,7 +144,7 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: if run.status != 'running' or not summary.get('awaiting_receipt_rpa'): return {'updated': False, 'reason': 'not_awaiting_receipt_callback'} - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() + units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() success_count = sum(unit.status == 'success' for unit in units) skipped_count = sum(unit.status == 'empty' for unit in units) failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units) @@ -239,7 +239,7 @@ def mark_receipt_unit_processing(payload: dict) -> dict: callback_id = str(payload.get('callback_id') or '').strip() if not callback_id: return {'updated': False, 'reason': 'callback_id_required'} - unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() if unit is None: return {'updated': False, 'reason': 'unit_not_found'} if unit.status in {'success', 'empty', 'failed', 'cancelled'}: @@ -268,7 +268,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} if not summary.get('awaiting_receipt_rpa'): return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'} - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() + units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() terminal = {'success', 'empty', 'failed', 'cancelled'} if any(unit.status not in terminal for unit in units): return {'finalized': False, 'reason': 'units_pending'} @@ -315,7 +315,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000] else: # 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 - from app.services.schedule.freight_inbound_rpa_archive import receipt_rpa_result_excel_name + from app.services.schedule.freight_rpa_inbound_archive import receipt_rpa_result_excel_name excel_name = receipt_rpa_result_excel_name(run) run.excel_file_data = excel_data @@ -331,7 +331,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: 'raw_receipt_zip_size': 0, } try: - from app.services.schedule.freight_inbound_rpa_archive import persist_receipt_rpa_raw_zip_archive + from app.services.schedule.freight_rpa_inbound_archive import persist_receipt_rpa_raw_zip_archive archive_summary = persist_receipt_rpa_raw_zip_archive(run) except Exception as archive_exc: @@ -381,7 +381,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool: ) -def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime: +def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime: """收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。 语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过 @@ -399,7 +399,7 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR def _fail_receipt_unit_with_timeout( - unit: ShippingReceiptRpaUnitRun, *, now: datetime, timeout_seconds: int, + unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int, run_no: str | None = None, ) -> None: """单个收料单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。 @@ -422,7 +422,7 @@ def _fail_receipt_unit_with_timeout( unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds' unit.finished_at = now append_shipping_audit_event( - event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit', + event_type='shipping_inbound_rpa_callback_timeout', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery', unit_id=unit.id, result='failure', before=before, after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}, @@ -442,7 +442,7 @@ def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_se task = run.task or db.session.get(ScheduleTask, run.schedule_task_id) if not is_freight_receipt_rpa_task(task): return False - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() + units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() if _receipt_last_activity(run, units) > cutoff: return False now = datetime.utcnow() @@ -516,11 +516,11 @@ def recover_all_stale_orphan_receipt_units() -> int: timeout_seconds = _receipt_timeout_seconds() cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) orphans = ( - ShippingReceiptRpaUnitRun.query + FreightRpaInboundUnitRun.query .filter( - ShippingReceiptRpaUnitRun.schedule_run_id.is_(None), - ShippingReceiptRpaUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')), - func.coalesce(ShippingReceiptRpaUnitRun.started_at, ShippingReceiptRpaUnitRun.created_at) < cutoff, + FreightRpaInboundUnitRun.schedule_run_id.is_(None), + FreightRpaInboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')), + func.coalesce(FreightRpaInboundUnitRun.started_at, FreightRpaInboundUnitRun.created_at) < cutoff, ) .all() ) diff --git a/backend/app/services/schedule/freight_inbound_rpa_job.py b/backend/app/services/schedule/freight_rpa_inbound_job.py similarity index 85% rename from backend/app/services/schedule/freight_inbound_rpa_job.py rename to backend/app/services/schedule/freight_rpa_inbound_job.py index 536243ea..e1593f5b 100644 --- a/backend/app/services/schedule/freight_inbound_rpa_job.py +++ b/backend/app/services/schedule/freight_rpa_inbound_job.py @@ -1,9 +1,9 @@ """ -backend/app/services/schedule/freight_inbound_rpa_job.py +backend/app/services/schedule/freight_rpa_inbound_job.py 用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。 依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_receipt_rpa_worker_ready、 - ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、 + FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaInboundUnitRun、 ScheduleTask/Run。 逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast; 口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。 @@ -16,7 +16,7 @@ from typing import Any from app import db from app.core.errors import ServiceUnavailableError -from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun +from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger from app.services.freight_rpa.common.worker_heartbeat import ( RPA_WORKER_OFFLINE_MESSAGE, @@ -37,16 +37,16 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]: return {str(value).strip().upper() for value in values if str(value).strip()} -def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]: +def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]: """读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" wanted = _wanted_source_codes(task) - rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join( - ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, - ).filter(ShippingInventorySource.enabled.is_(True)).all() + rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join( + FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).all() return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted] -def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str, Any]]: +def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]: """浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" return [ dict(item) for item in (config.query_parameters_json or []) @@ -55,8 +55,8 @@ def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str def _build_unit( - source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int, -) -> ShippingReceiptRpaUnitRun: + source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int, +) -> FreightRpaInboundUnitRun: """冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。""" callback_id = f'receipt:{uuid.uuid4().hex}' snapshot = { @@ -64,16 +64,16 @@ def _build_unit( 'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config), 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, } - return ShippingReceiptRpaUnitRun( - schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code, + return FreightRpaInboundUnitRun( + schedule_run_id=schedule_run_id, source_id=source.id, source_code=source.source_code, connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id, status='awaiting_rpa', config_snapshot_json=snapshot, ) -def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]: +def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]: """生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。""" - source = unit.inventory_source + source = unit.source profile = source.rpa_profile if source is not None else None if source is None or profile is None or not profile.enabled: raise RuntimeError(f'receipt source profile unavailable: {unit.source_code}') @@ -105,7 +105,7 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc 核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed, 不创建 unit、不进入 awaiting_receipt_rpa。 """ - units: list[ShippingReceiptRpaUnitRun] = [ + units: list[FreightRpaInboundUnitRun] = [ _build_unit(source, config, run.id) for source, config in _eligible_sources(task) ] if not units: diff --git a/backend/app/services/schedule/freight_inbound_rpa_retention.py b/backend/app/services/schedule/freight_rpa_inbound_retention.py similarity index 74% rename from backend/app/services/schedule/freight_inbound_rpa_retention.py rename to backend/app/services/schedule/freight_rpa_inbound_retention.py index ad0c8805..a117bce4 100644 --- a/backend/app/services/schedule/freight_inbound_rpa_retention.py +++ b/backend/app/services/schedule/freight_rpa_inbound_retention.py @@ -1,9 +1,9 @@ """收料原样归档三年到期对象清理(排程壳)。 批次 R Task 10 起,清理能力本体已下沉 freight_rpa.inbound.report_archive -(run_freight_inbound_rpa_retention_schedule,函数名 receipt 词根→inbound); +(run_freight_rpa_inbound_retention_schedule,函数名 receipt 词根→inbound); 本文件仅保留排程平台 Job 处理器接缝(job_registry 按 schedule 包路径注册, -Task 11 已随排程壳平移改名为 freight_inbound_rpa_retention,git mv 保留历史)。 +Task 11 已随排程壳平移改名为 freight_rpa_inbound_retention,git mv 保留历史)。 """ from __future__ import annotations @@ -13,6 +13,6 @@ from typing import Any def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: """排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。""" - from app.services.freight_rpa.inbound.report_archive import run_freight_inbound_rpa_retention_schedule + from app.services.freight_rpa.inbound.report_archive import run_freight_rpa_inbound_retention_schedule - return run_freight_inbound_rpa_retention_schedule(task, run) + return run_freight_rpa_inbound_retention_schedule(task, run) diff --git a/backend/app/services/schedule/freight_onhand_rpa_archive.py b/backend/app/services/schedule/freight_rpa_onhand_archive.py similarity index 93% rename from backend/app/services/schedule/freight_onhand_rpa_archive.py rename to backend/app/services/schedule/freight_rpa_onhand_archive.py index ffca1f9c..028cd092 100644 --- a/backend/app/services/schedule/freight_onhand_rpa_archive.py +++ b/backend/app/services/schedule/freight_rpa_onhand_archive.py @@ -1,8 +1,8 @@ """ -backend/app/services/schedule/freight_onhand_rpa_archive.py +backend/app/services/schedule/freight_rpa_onhand_archive.py 用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 -依赖:ScheduleRun、ShippingInventoryFile、freight_onhand_rpa_finalize.is_shipping_inventory_rpa_task。 +依赖:ScheduleRun、FreightRpaOnhandReportFile、freight_rpa_onhand_finalize.is_shipping_inventory_rpa_task。 逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary; 企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」; 完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。 @@ -21,8 +21,8 @@ from flask import current_app from app import db from app.core.errors import NotFoundError -from app.models import ScheduleRun, ShippingInventoryFile -from app.services.schedule.freight_onhand_rpa_finalize import is_shipping_inventory_rpa_task +from app.models import ScheduleRun, FreightRpaOnhandReportFile +from app.services.schedule.freight_rpa_onhand_finalize import is_shipping_inventory_rpa_task from app.services.schedule.timezone_util import resolve_schedule_tzinfo _RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员" @@ -98,7 +98,7 @@ def inventory_rpa_attachment_stem(run: ScheduleRun) -> str: def inventory_rpa_result_excel_name(run: ScheduleRun) -> str: """库存 RPA 结果 Excel 的企微/下载展示名。""" - return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx" + return f"{onhand_rpa_attachment_stem(run)}-结果.xlsx" def inventory_raw_zip_download_name(run: ScheduleRun) -> str: @@ -107,7 +107,7 @@ def inventory_raw_zip_download_name(run: ScheduleRun) -> str: 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 """ - return f"{inventory_rpa_attachment_stem(run)}-库存.zip" + return f"{onhand_rpa_attachment_stem(run)}-库存.zip" def _inventory_raw_zip_archive_path(run_no: str) -> Path: @@ -139,10 +139,10 @@ def _iter_packable_inventory_files( """ 遍历可实际打包的库存快照。 - 核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。 + 核心逻辑:需存在 FreightRpaOnhandReportFile 且 storage_path 指向可读文件。 Yields: - tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。 + tuple[dict, FreightRpaOnhandReportFile, Path]: created 项、快照记录、可读路径。 """ if not is_shipping_inventory_rpa_task(getattr(run, "task", None)): return @@ -154,8 +154,8 @@ def _iter_packable_inventory_files( continue inv_file = ( - db.session.query(ShippingInventoryFile) - .filter(ShippingInventoryFile.inventory_file_no == inventory_file_no) + db.session.query(FreightRpaOnhandReportFile) + .filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no) .first() ) if not inv_file: diff --git a/backend/app/services/schedule/freight_onhand_rpa_finalize.py b/backend/app/services/schedule/freight_rpa_onhand_finalize.py similarity index 98% rename from backend/app/services/schedule/freight_onhand_rpa_finalize.py rename to backend/app/services/schedule/freight_rpa_onhand_finalize.py index 62f4b0cb..475313d9 100644 --- a/backend/app/services/schedule/freight_onhand_rpa_finalize.py +++ b/backend/app/services/schedule/freight_rpa_onhand_finalize.py @@ -1,9 +1,9 @@ """ -backend/app/services/schedule/freight_onhand_rpa_finalize.py +backend/app/services/schedule/freight_rpa_onhand_finalize.py 用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。 依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。 -逻辑:freight_onhand_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize; +逻辑:freight_rpa_onhand_job 写 trigger 后 defer;onhand_rpa_workflow 回调后 finalize; run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。 """ @@ -276,7 +276,7 @@ def _try_recover_stale_awaiting_run( finished_at = datetime.utcnow() step_logs = list(run.step_logs or []) step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "failed", "detail": {"message": "RPA 库存导出等待超时", "timeout_seconds": timeout_seconds}, }) @@ -495,13 +495,13 @@ def _finalize_shipping_inventory_schedule_run_impl( status = "partial_failed" else: # 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 - from app.services.schedule.freight_onhand_rpa_archive import inventory_rpa_result_excel_name + from app.services.schedule.freight_rpa_onhand_archive import inventory_rpa_result_excel_name file_name = inventory_rpa_result_excel_name(run) step_logs = list(run.step_logs or []) step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed", "detail": { "created_count": success_count, @@ -537,7 +537,7 @@ def _finalize_shipping_inventory_schedule_run_impl( "raw_inventory_zip_size": 0, } try: - from app.services.schedule.freight_onhand_rpa_archive import persist_inventory_rpa_raw_zip_archive + from app.services.schedule.freight_rpa_onhand_archive import persist_inventory_rpa_raw_zip_archive archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created) except Exception as archive_exc: diff --git a/backend/app/services/schedule/freight_onhand_rpa_job.py b/backend/app/services/schedule/freight_rpa_onhand_job.py similarity index 87% rename from backend/app/services/schedule/freight_onhand_rpa_job.py rename to backend/app/services/schedule/freight_rpa_onhand_job.py index d0b4585a..dd91e113 100644 --- a/backend/app/services/schedule/freight_onhand_rpa_job.py +++ b/backend/app/services/schedule/freight_rpa_onhand_job.py @@ -1,10 +1,10 @@ """ -backend/app/services/schedule/freight_onhand_rpa_job.py +backend/app/services/schedule/freight_rpa_onhand_job.py 用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。 -依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。 +依赖:onhand_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。 逻辑:platform_api_path=freight-rpa-onhand 时由 job_registry 调用; - 写 trigger 后返回 awaiting_rpa_callback;终态由 freight_onhand_rpa_finalize 在 RPA 回调时写入。 + 写 trigger 后返回 awaiting_rpa_callback;终态由 freight_rpa_onhand_finalize 在 RPA 回调时写入。 """ from __future__ import annotations @@ -16,8 +16,8 @@ from typing import Any from app import db from app.core.errors import ServiceUnavailableError from app.models import ScheduleRun, ScheduleTask -from app.services.schedule.freight_onhand_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS -from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources +from app.services.schedule.freight_rpa_onhand_finalize import AWAITING_RPA_CALLBACK_STATUS +from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger from app.services.freight_rpa.common.worker_heartbeat import ( RPA_WORKER_OFFLINE_MESSAGE, @@ -105,21 +105,21 @@ def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]: return enabled -def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: +def run_freight_rpa_onhand_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ 写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。 核心逻辑:写 trigger 后返回 awaiting_rpa_callback;终态由 finalize 在回调时写入。 """ sources = _filter_sources(task) step_logs: list[dict[str, Any]] = [{ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "started", "detail": {"source_count": len(sources)}, }] if not sources: message = "no enabled inventory sources" - step_logs.append({"step": "shipping_inventory_rpa", "status": "skipped", "detail": {"message": message}}) + step_logs.append({"step": "freight_rpa_onhand", "status": "skipped", "detail": {"message": message}}) return 0, 0, 0, 1, [], [message], step_logs run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}" @@ -139,7 +139,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE) detail_message = str((exc.details or {}).get("detail_message") or message) step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "failed", "detail": { "message": message, @@ -151,7 +151,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> return len(sources), 0, len(sources), 0, [], [detail_message], step_logs if not trigger_path: message = "inventory RPA trigger dir not configured" - step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}}) + step_logs.append({"step": "freight_rpa_onhand", "status": "failed", "detail": {"message": message}}) return len(sources), 0, len(sources), 0, [], [message], step_logs run.api_request_json = { @@ -162,7 +162,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> db.session.commit() step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": AWAITING_RPA_CALLBACK_STATUS, "detail": {"trigger_path": trigger_path, "run_no": run_no}, }) diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 63fb0b38..879e5232 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -2,9 +2,10 @@ backend/app/services/schedule/job_options.py 用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。 -依赖:models.Agent、shipping_notice.inventory_source_repository。 +依赖:models.Agent、shipping_notice.onhand_source_repository。 逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用; 前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。 + 货代 RPA 注册键为 freight_rpa_sources 与 freight_rpa_inbound_sources。 """ from __future__ import annotations @@ -35,7 +36,7 @@ def _agent_apps_options() -> list[dict[str, Any]]: def _shipping_inventory_sources_options() -> list[dict[str, Any]]: """启用中的货代库存源(value=source_code,来自数据库主数据)。""" - from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources + from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources return [ { @@ -53,11 +54,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]: def _shipping_receipt_sources_options() -> list[dict[str, Any]]: """已启用且已配置收料报表的站点,供独立收料排程选择。""" - from app.models import ShippingInventorySource, ShippingReceiptReportConfig + from app.models import FreightRpaSource, FreightRpaInboundReportConfig - rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join( - ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, - ).filter(ShippingInventorySource.enabled.is_(True)).all() + rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join( + FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).all() return [{ 'label': source.display_name or source.source_code, 'value': source.source_code, 'description': f'{source.connector_type} · 收料已配置', @@ -101,8 +102,8 @@ def _users_options() -> list[dict[str, Any]]: # options_source 注册表:新增来源只需在此登记 provider,不动 API 层 _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = { "agent_apps": _agent_apps_options, - "shipping_inventory_sources": _shipping_inventory_sources_options, - "shipping_receipt_sources": _shipping_receipt_sources_options, + "freight_rpa_sources": _shipping_inventory_sources_options, + "freight_rpa_inbound_sources": _shipping_receipt_sources_options, "hxops_users": _hxops_users_options, "users": _users_options, } diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index c769052a..e1ff4e33 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -2,7 +2,7 @@ backend/app/services/schedule/job_registry.py 用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。 -依赖:freight_onhand_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。 +依赖:freight_rpa_onhand_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。 逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key; api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。 """ @@ -34,7 +34,7 @@ class PlatformJobDefinition: "label_key": "...", # 前端 i18n key(可选) "required": False, "default": [], - "options_source": "shipping_inventory_sources", # select/multi_select 动态选项来源(可选) + "options_source": "freight_rpa_sources", # select/multi_select 动态选项来源(可选) "placeholder": "...", "placeholder_key": "...", "help": "...", "help_key": "...", } @@ -44,7 +44,7 @@ class PlatformJobDefinition: label: str handler: PlatformJobHandler description: str = "" - # 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory); + # 前端 i18n key(如 admin.schedule.form.platformJobFreightRpaOnhand); # 前端下拉优先 $t(label_key),label 仅作 fallback/debug。 label_key: str = "" description_key: str = "" @@ -132,9 +132,9 @@ def _register_builtin_platform_jobs() -> None: from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule - from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule - from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule - from app.services.schedule.freight_inbound_rpa_retention import run_freight_receipt_rpa_retention_schedule + from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule + from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule + from app.services.schedule.freight_rpa_inbound_retention import run_freight_receipt_rpa_retention_schedule from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import ( run_shipping_post_ot_auto_fulfill_compensation_schedule, @@ -373,25 +373,25 @@ def _register_builtin_platform_jobs() -> None: register_platform_job(PlatformJobDefinition( key="freight-rpa-onhand", label="货代库存 RPA", - label_key="admin.schedule.form.platformJobShippingInventory", - handler=run_shipping_inventory_rpa_schedule, + label_key="admin.schedule.form.platformJobFreightRpaOnhand", + handler=run_freight_rpa_onhand_schedule, description="按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。", - description_key="admin.schedule.form.shippingInventoryJobHint", + description_key="admin.schedule.form.freightRpaOnhandJobHint", category="shipping", params_schema=( { "key": "source_codes", "type": "multi_select", "label": "库存源", - "label_key": "admin.schedule.form.shippingInventorySources", + "label_key": "admin.schedule.form.freightRpaSources", # 兼容历史任务语义:留空 = 导出全部启用库存源,故不设 required "required": False, "default": [], - "options_source": "shipping_inventory_sources", + "options_source": "freight_rpa_sources", "placeholder": "留空则导出全部启用库存源", - "placeholder_key": "admin.schedule.form.shippingInventorySourcesPlaceholder", + "placeholder_key": "admin.schedule.form.freightRpaSourcesPlaceholder", "help": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。", - "help_key": "admin.schedule.form.shippingInventorySourcesHelp", + "help_key": "admin.schedule.form.freightRpaSourcesHelp", }, ), defaults={"source_codes": []}, @@ -404,7 +404,7 @@ def _register_builtin_platform_jobs() -> None: category="shipping", params_schema=({ "key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False, - "default": [], "options_source": "shipping_receipt_sources", + "default": [], "options_source": "freight_rpa_inbound_sources", "help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。", },), defaults={"source_codes": []}, @@ -596,7 +596,7 @@ def _register_builtin_platform_jobs() -> None: "label_key": "admin.schedule.form.transferSourceCodes", "required": False, "default": [], - "options_source": "shipping_inventory_sources", + "options_source": "freight_rpa_sources", }, { "key": "recover_history", diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index 5a7038c3..d6ac09e3 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -9,8 +9,8 @@ from sqlalchemy.orm import joinedload from app import db from app.models import ScheduleRun, ScheduleTask from app.core.response import utc_iso -from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary -from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary +from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary +from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary from app.services.schedule.timezone_util import ( DEFAULT_SCHEDULE_TIMEZONE, compute_next_run_at, diff --git a/backend/app/services/schedule/queue_service.py b/backend/app/services/schedule/queue_service.py index 418ca193..f14db6cb 100644 --- a/backend/app/services/schedule/queue_service.py +++ b/backend/app/services/schedule/queue_service.py @@ -19,11 +19,11 @@ from app import db from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs from app.jobs.types import JobType from app.models import Job, ScheduleRun, ScheduleTask -from app.services.schedule.freight_onhand_rpa_finalize import ( +from app.services.schedule.freight_rpa_onhand_finalize import ( recover_all_stale_awaiting_rpa_schedule_runs, recover_stale_awaiting_rpa_schedule_runs, ) -from app.services.schedule.freight_inbound_rpa_finalize import ( +from app.services.schedule.freight_rpa_inbound_finalize import ( recover_all_stale_orphan_receipt_units, recover_all_stale_receipt_rpa_schedule_runs, recover_stale_receipt_rpa_schedule_runs, @@ -332,7 +332,7 @@ def prepare_schedule_queue() -> int: if not _worker_initialized: # [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。 - from app.services.schedule.freight_onhand_rpa_finalize import is_awaiting_rpa_schedule_run + from app.services.schedule.freight_rpa_onhand_finalize import is_awaiting_rpa_schedule_run legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all() interrupted = 0 @@ -379,7 +379,7 @@ def prepare_schedule_queue() -> int: # 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出): # 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。 - # 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_inbound_rpa_finalize。 + # 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_finalize。 receipt_stale = recover_all_stale_receipt_rpa_schedule_runs() if receipt_stale: current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale) diff --git a/backend/app/services/schedule/schedule_contract.py b/backend/app/services/schedule/schedule_contract.py index 34f9e346..ad90d754 100644 --- a/backend/app/services/schedule/schedule_contract.py +++ b/backend/app/services/schedule/schedule_contract.py @@ -23,8 +23,9 @@ VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTER LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"}) +# 仍在导入 JSON 里出现的历史 data_source。货代在手任务的旧键已由 s17c 整列改写, +# 运行期只认 platform job key freight-rpa-onhand。 LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = { - "shipping_inventory_rpa": "freight-rpa-onhand", "faq_hot_aggregate": "faq-aggregate-hot", } diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index a13044be..a1d08e16 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -18,19 +18,19 @@ from typing import Any from flask import current_app from app import db -from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User +from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundReportFile, User from app.services.schedule.cron_util import normalize_cron_expr from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot from app.services.schedule.excel_service import export_schedule_result_excel from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path -from app.services.schedule.freight_inbound_rpa_job import INBOUND_RPA_JOB_KEY -from app.services.schedule.freight_onhand_rpa_finalize import ( +from app.services.schedule.freight_rpa_inbound_job import INBOUND_RPA_JOB_KEY +from app.services.schedule.freight_rpa_onhand_finalize import ( apply_deferred_schedule_run_state, is_awaiting_rpa_schedule_run, recover_stale_awaiting_rpa_schedule_runs, should_defer_schedule_run_finalization, ) -from app.services.schedule.freight_inbound_rpa_finalize import ( +from app.services.schedule.freight_rpa_inbound_finalize import ( apply_deferred_receipt_schedule_run_state, recover_stale_receipt_rpa_schedule_runs, should_defer_receipt_schedule_run, @@ -106,8 +106,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) 核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1 与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。 """ - from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary - from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} params: dict[str, Any] = { @@ -123,7 +123,7 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) return params -def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]: +def _receipt_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]: """ 收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。 @@ -131,7 +131,7 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor 未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP, 本函数保留给管理员单文件重发等旁路读取。 """ - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun task = run.task if ( @@ -141,14 +141,14 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor ): return [] return ( - ShippingReceiptReportFile.query.join( - ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id, + FreightRpaInboundReportFile.query.join( + FreightRpaInboundUnitRun, FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id, ) .filter( - ShippingReceiptRpaUnitRun.schedule_run_id == run.id, - ShippingReceiptReportFile.archive_deleted_at.is_(None), + FreightRpaInboundUnitRun.schedule_run_id == run.id, + FreightRpaInboundReportFile.archive_deleted_at.is_(None), ) - .order_by(ShippingReceiptReportFile.id) + .order_by(FreightRpaInboundReportFile.id) .all() ) @@ -171,8 +171,8 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed': description += '\n备注: 库存源已成功,但排程 Excel 生成失败' - from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary - from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary if inventory_raw_zip_available_from_summary(summary): description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载' @@ -238,7 +238,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: raw_zip_media_id = None raw_zip_file_name = None try: - from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download + from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run) raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name) @@ -251,7 +251,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: receipt_zip_media_id = None receipt_zip_file_name = None try: - from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download + from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run) receipt_zip_media_id = upload_wecom_temp_media( diff --git a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py index 37dfb9a0..bc052a85 100644 --- a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py +++ b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py @@ -16,7 +16,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import ( coordinate_post_ot_auto_fulfill, enqueue_post_ot_auto_fulfill_job, ) -from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled +from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( list_eligible_post_ot_snapshot_line_ids, ) diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index 2f8a1b8a..e82a952e 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -5,7 +5,7 @@ services/shipping_notice/auto_progress_controller.py 依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务; process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。 逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job - 在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时 + 在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 onhand_preparation 时 覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。 库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 """ @@ -22,7 +22,7 @@ from app import db from app.jobs.queue import enqueue from app.jobs.types import JobType from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt -from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set +from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate from app.services.shipping_notice.tool_common import log_task_event @@ -149,8 +149,8 @@ def determine_formal_start_gate( return 'field_conflict_resolution' candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task) if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen': - return 'inventory_source_routing' - return 'inventory_preparation' + return 'onhand_source_routing' + return 'onhand_preparation' def _create_formal_execution_for_task( @@ -418,7 +418,7 @@ def submit_auto_progress( # (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照), # 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。 explicit_inventory_retry = ( - str(resume_gate_code or '').strip() == 'inventory_preparation' + str(resume_gate_code or '').strip() == 'onhand_preparation' and ( str(inventory_mode or '').strip() == 'retry_rpa' or str(trigger or '').strip() == 'manual_override_source' @@ -433,7 +433,7 @@ def submit_auto_progress( db.session.flush() execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one() current_gate = ( - 'inventory_preparation' + 'onhand_preparation' if explicit_inventory_retry else str(execution.current_gate_code or '').strip() or None ) @@ -479,16 +479,16 @@ def submit_auto_progress( stale_job.message = '显式库存重抓:取消残留活动 Job' gate.status = 'blocked_retryable' gate.passed_at = None - gate.blocking_reason_code = 'inventory_rpa_retry_requested' - gate.next_action_code = 'retry_inventory_preparation' + gate.blocking_reason_code = 'onhand_rpa_retry_requested' + gate.next_action_code = 'retry_onhand_preparation' gate.evaluation_version = int(gate.evaluation_version) + 1 gate.lock_version = int(gate.lock_version) + 1 gate.updated_at = _utc_now() - execution.current_gate_code = 'inventory_preparation' + execution.current_gate_code = 'onhand_preparation' # 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate # 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。 execution.responsible_party = 'worker' - execution.primary_next_action_code = 'retry_inventory_preparation' + execution.primary_next_action_code = 'retry_onhand_preparation' execution.updated_at = _utc_now() db.session.flush() active_attempt = ( @@ -532,7 +532,7 @@ def submit_auto_progress( # 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的 # system/worker Gate 才可自动创建 Attempt 并入队。 # 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。 - # upload_inventory_file 等导航动作必须保留给用户;否则成功回调已同步 + # upload_onhand_file 等导航动作必须保留给用户;否则成功回调已同步 # 的库存事实会被旧人工阻断动作再次覆盖。 if ( gate is not None diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index ae577d7a..6167bc84 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -57,7 +57,7 @@ def _unmark_running(bucket: set[str], key: str) -> None: def _should_orchestrate_task(task: Any) -> bool: from app.services.shipping_notice.task_disposition_service import task_is_active - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if not task_is_active(task): return False @@ -100,7 +100,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: return {"status": "skipped", "message": "task already running"} try: - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task task = get_task_by_ref(normalized_task_no) if not task: @@ -130,7 +130,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: ): # [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落 # rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。 - from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait + from app.services.shipping_notice.onhand_rpa_workflow import maybe_recheck_inventory_rpa_wait recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator') if recheck is not None: diff --git a/backend/app/services/shipping_notice/conversation_processing_projection.py b/backend/app/services/shipping_notice/conversation_processing_projection.py index 9f1a65f0..9a91937a 100644 --- a/backend/app/services/shipping_notice/conversation_processing_projection.py +++ b/backend/app/services/shipping_notice/conversation_processing_projection.py @@ -65,7 +65,7 @@ _PROCESSING_ITEM_LIFECYCLES = frozenset({ 'layout_parsing', 'extracting', 'building_order', - 'inventory_matching', + 'onhand_matching', 'generating_excel', }) diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 3bfe2ba1..979c2c62 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -13,7 +13,7 @@ from __future__ import annotations from datetime import datetime from typing import Any -from app.models import ShippingOrderTask, ShippingTemporaryInventorySession +from app.models import ShippingOrderTask, ShippingTemporaryOnhandSession 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 @@ -40,18 +40,18 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N normalized = str(conversation_id or '').strip() if not normalized: return None - item = ShippingTemporaryInventorySession.query.filter( - ShippingTemporaryInventorySession.conversation_id == normalized, - ShippingTemporaryInventorySession.status.in_([ + item = ShippingTemporaryOnhandSession.query.filter( + ShippingTemporaryOnhandSession.conversation_id == normalized, + ShippingTemporaryOnhandSession.status.in_([ 'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion', 'awaiting_mapping_confirmation', ]), - ShippingTemporaryInventorySession.expires_at > datetime.utcnow(), + ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(), ).order_by( - ShippingTemporaryInventorySession.updated_at.desc(), - ShippingTemporaryInventorySession.id.desc(), + ShippingTemporaryOnhandSession.updated_at.desc(), + ShippingTemporaryOnhandSession.id.desc(), ).first() return str(item.session_no or '').strip().upper() or None if item else None diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index f8bc8091..81f29477 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -145,7 +145,7 @@ INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES: Final[frozenset[str]] = frozenset({ 'manual_inventory_source_invalid', 'inventory_source_conflicted', 'inventory_source_changed', - 'inventory_source_identity_mismatch', + 'onhand_source_identity_mismatch', }) # 库存源路由 — 单源不可用明细(写入 unavailable_reasons[source_code]) @@ -162,11 +162,11 @@ INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES: Final[frozenset[str]] = frozenset({ INVENTORY_PREP_REASON_CODES: Final[frozenset[str]] = frozenset({ 'inventory_preparation_waiting', 'inventory_preparation_failed', - 'inventory_rpa_queued', - 'inventory_rpa_timeout', - 'inventory_rpa_login_failed', - 'inventory_rpa_export_failed', - 'inventory_rpa_exhausted', + 'onhand_rpa_queued', + 'onhand_rpa_timeout', + 'onhand_rpa_login_failed', + 'onhand_rpa_export_failed', + 'onhand_rpa_exhausted', 'inventory_file_missing', 'inventory_file_identity_mismatch', 'inventory_file_empty', @@ -292,7 +292,7 @@ INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED: Final[frozenset[str]] = frozen 'manual_inventory_source_invalid', 'inventory_source_conflicted', 'inventory_source_changed', - 'inventory_source_identity_mismatch', + 'onhand_source_identity_mismatch', }) # 附件告警已映射并可出现在审计 / Intake 投影中的子集 @@ -310,11 +310,11 @@ ATTACHMENT_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({ INVENTORY_PREP_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({ 'inventory_preparation_waiting', 'inventory_preparation_failed', - 'inventory_rpa_queued', - 'inventory_rpa_timeout', - 'inventory_rpa_login_failed', - 'inventory_rpa_export_failed', - 'inventory_rpa_exhausted', + 'onhand_rpa_queued', + 'onhand_rpa_timeout', + 'onhand_rpa_login_failed', + 'onhand_rpa_export_failed', + 'onhand_rpa_exhausted', 'inventory_file_missing', 'inventory_file_empty', 'inventory_file_identity_mismatch', @@ -560,25 +560,25 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'source_excel_template_unavailable': _meta('admin', 'retry_with_latest_rules', '库存 Excel 模板未发布'), 'inventory_source_conflicted': _meta('system', 'retry_with_latest_rules', '多条规则产生冲突,需修复规则后自动重新裁决'), 'inventory_source_changed': _meta('system', 'retry_with_latest_rules', '库存源配置已变化,系统将重新裁决'), - 'inventory_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'), + 'onhand_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'), 'effective_reservation_missing': _meta('owner', 'edit_reservation', '缺少有效的预约单号'), # 库存准备 / RPA / 匹配 / Excel / 上传 - 'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'), - 'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'), - 'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'), - 'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'), - 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), - 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), - 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), - 'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'), + 'inventory_preparation_waiting': _meta('worker', 'poll_onhand_preparation', '库存文件准备中,请稍后刷新'), + 'inventory_preparation_failed': _meta('owner', 'retry_onhand_preparation', '库存准备失败,请重试或上传库存文件'), + 'onhand_rpa_queued': _meta('worker', 'poll_onhand_preparation', 'RPA 任务已排队等待执行'), + 'onhand_rpa_timeout': _meta('worker', 'reload_onhand_result', 'RPA 执行超时'), + 'onhand_rpa_login_failed': _meta('admin', 'retry_onhand_preparation', '库存平台登录失败'), + 'onhand_rpa_export_failed': _meta('worker', 'retry_onhand_preparation', '库存报表导出失败'), + 'onhand_rpa_exhausted': _meta('owner', 'reload_onhand_result', '库存源重试次数已耗尽'), + 'inventory_file_missing': _meta('owner', 'retry_onhand_preparation', '未生成库存文件'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), 'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'), 'inventory_match_out_of_candidate_scope': _meta('system', 'retry_with_latest_rules', '库存命中超出当前候选范围'), - 'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'), - 'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'), - 'inventory_mapping_required': _meta('system', 'retry_inventory_field_mapping', '库存字段映射待自动校验'), - 'inventory_match_failed': _meta('owner', 'open_inventory_match_review', '库存匹配失败'), + 'inventory_file_identity_mismatch': _meta('owner', 'retry_onhand_preparation', '返回文件与所选库存源不一致'), + 'inventory_file_empty': _meta('owner', 'retry_onhand_preparation', '库存文件为空或没有有效库存记录'), + 'inventory_mapping_required': _meta('system', 'retry_onhand_field_mapping', '库存字段映射待自动校验'), + 'inventory_match_failed': _meta('owner', 'open_onhand_match_review', '库存匹配失败'), 'inventory_insufficient': _meta('owner', 'open_shortage_review', '库存不足'), 'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'), 'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'), @@ -607,13 +607,13 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'), 'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'), 'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'), - 'inventory_required_column_missing': _meta('system', 'retry_inventory_field_mapping', '库存文件缺少必填列'), - 'inventory_column_ambiguous': _meta('system', 'retry_inventory_field_mapping', '库存列映射存在歧义'), - 'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'), - 'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'), - 'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'), - 'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'), - 'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'), + 'inventory_required_column_missing': _meta('system', 'retry_onhand_field_mapping', '库存文件缺少必填列'), + 'inventory_column_ambiguous': _meta('system', 'retry_onhand_field_mapping', '库存列映射存在歧义'), + 'inventory_sku_not_found': _meta('owner', 'open_onhand_match_review', '库存中未找到对应 SKU'), + 'inventory_reservation_not_found': _meta('owner', 'open_onhand_match_review', '库存中未找到对应 Reservation'), + 'inventory_warehouse_mismatch': _meta('owner', 'open_onhand_match_review', '仓库与订单要求不一致'), + 'inventory_uom_conversion_failed': _meta('owner', 'open_onhand_match_review', '单位换算失败'), + 'inventory_multi_file_conflict': _meta('owner', 'override_line_onhand_source', '多库存文件结果冲突'), } @@ -970,7 +970,7 @@ AUDIT_COVERAGE_MATRIX: Final[tuple[dict[str, Any], ...]] = ( 'node': 'late_rpa_callback_ignored', 'event_type': 'rpa_callback_rejected', 'reason_code': 'late_callback_ignored', - 'source_module': 'inventory_rpa_workflow.py', + 'source_module': 'onhand_rpa_workflow.py', 'wire_marker': '"reason_code": "late_callback_ignored"', 'allow_empty': False, }, @@ -1035,8 +1035,8 @@ def assert_error_explainability_contract_integrity() -> None: 'inventory_source_unavailable', 'require_manual_review', ): - assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'inventory_source_routing', ( - f'{code} must own inventory_source_routing' + assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'onhand_source_routing', ( + f'{code} must own onhand_source_routing' ) # [STEP 4] meta 责任方与动作合法性 diff --git a/backend/app/services/shipping_notice/excel_template.py b/backend/app/services/shipping_notice/excel_template.py index 53f78b5a..2dc569ab 100644 --- a/backend/app/services/shipping_notice/excel_template.py +++ b/backend/app/services/shipping_notice/excel_template.py @@ -26,8 +26,8 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, - ShippingInventoryField, - ShippingInventorySource, + FreightRpaOnhandField, + FreightRpaSource, ShippingOrderField, ) from app.services.file_assets.storage import file_asset_storage @@ -327,7 +327,7 @@ def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]: 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) + inventory_field = db.session.get(FreightRpaOnhandField, 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) @@ -371,7 +371,7 @@ def retire(template_id: int) -> dict[str, Any]: 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(): + if FreightRpaSource.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() diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index b26caaac..efc96770 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -33,9 +33,9 @@ from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, ShippingNoticeLine, - ShippingNoticeLineInventoryMatch, - ShippingInventoryField, - ShippingInventorySource, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandField, + FreightRpaSource, ShippingOrderSnapshot, ShippingOrderField, ShippingNotice, @@ -58,11 +58,11 @@ def _notice_source_code(task: ShippingNotice) -> str | None: task_id = int(task_id) codes = [ str(row[0]).strip().upper() - for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter( - ShippingNoticeLineInventoryMatch.task_id == task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result == 'matched', - ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None), + for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter( + ShippingNoticeLineOnhandMatch.task_id == task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.match_result == 'matched', + ShippingNoticeLineOnhandMatch.source_code.isnot(None), ).distinct().all() if row[0] ] @@ -76,10 +76,10 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None: return None values = [ str(row[0]).strip() - for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter( - ShippingNoticeLineInventoryMatch.task_id == int(task_id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None), + for row in db.session.query(ShippingNoticeLineOnhandMatch.chosen_odm_id).filter( + ShippingNoticeLineOnhandMatch.task_id == int(task_id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.chosen_odm_id.isnot(None), ).distinct().all() if row[0] ] @@ -93,11 +93,11 @@ def _notice_inventory_file_id(task: ShippingNotice) -> int | None: return None task_id = int(task_id) ids = [ - int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter( - ShippingNoticeLineInventoryMatch.task_id == task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result == 'matched', - ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter( + ShippingNoticeLineOnhandMatch.task_id == task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.match_result == 'matched', + ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None), ).distinct().all() ] return ids[0] if len(ids) == 1 else None @@ -395,8 +395,8 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> 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', + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active', ).all() if ids else [] if len(rows) != len(ids): raise ValueError('发货模板引用的库存字段已不存在') @@ -407,7 +407,7 @@ def _inventory_field_user_label(field_id: str) -> str: """把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。""" normalized = str(field_id or '').strip() if normalized.isdigit(): - row = ShippingInventoryField.query.filter_by(id=int(normalized)).first() + row = FreightRpaOnhandField.query.filter_by(id=int(normalized)).first() display_name = str(getattr(row, 'display_name', '') or '').strip() if row else '' if display_name: return display_name @@ -572,17 +572,20 @@ def _filename( def _input_checksum( - task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate, + task: ShippingNotice, source: FreightRpaSource, template: ShippingExcelTemplate, snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], notice_id: int | None = None, ) -> str: """以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。""" + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该外键。 + report_config = source.onhand_report_config 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': snapshot.schema_version_id, 'snapshot_id': snapshot.id, - 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task), + 'parsing_profile_id': report_config.parsing_profile_id if report_config is not None else None, + 'inventory_snapshot_id': _notice_inventory_file_id(task), 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, 'notice_id': notice_id, } @@ -592,7 +595,7 @@ def _input_checksum( def _resolve_odm_inventory_field_id() -> int | None: """返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。""" - field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first() + field = FreightRpaOnhandField.query.filter_by(field_code='odm_id', status='active').first() return int(field.id) if field is not None else None @@ -610,7 +613,7 @@ def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, st } catalog = { str(item.id): str(item.id) - for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all() + for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(ids)).all() } normalized_keys: list[dict[str, str]] = [] for item in match_keys: @@ -762,7 +765,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: ) # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 source_code = str(_notice_source_code(task) or '').strip().upper() - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + source = FreightRpaSource.query.filter_by(source_code=source_code, enabled=True).first() if source is None: source = None if source is None: @@ -770,7 +773,10 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: 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': + # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 + report_config = source.onhand_report_config + profile = report_config.parsing_profile if report_config is not None else None + if profile is None or profile.status != 'published': raise ValueError('库存源未绑定已发布的库存解析模板') definition = template.definition_json or {} mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] @@ -784,7 +790,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: raise ValueError('任务没有可用于导出的冻结订单快照') from app.services.shipping_notice.effective_order_view import effective_order_field_values header_values, all_line_values = effective_order_field_values(task) - profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {} + profile_definition = profile.definition_json if isinstance(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') @@ -801,7 +807,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: .filter( ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) @@ -861,7 +867,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: row['__order_line_index'] = source_index row['__snapshot_line_id'] = int(line.id) line_values.append(row) - from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution + from app.services.shipping_notice.onhand_file_store import resolve_inventory_lines_for_execution # [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part) # 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。 @@ -874,7 +880,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: } catalog = { str(item.id): str(item.id) - for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all() + for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(match_field_ids)).all() } if match_field_ids else {} order_field_ids: list[str] = [] inventory_field_keys: list[str] = [] @@ -958,6 +964,8 @@ def generate_shipment_excel( assert_notice_has_no_export_artifact(task) inputs = prepare_export_match_inputs(task) source = inputs['source'] + # s18 起解析方案绑定归 onhand_report_config 配置行;Artifact 审计外键同样取自配置行。 + report_config = source.onhand_report_config template = inputs['template'] snapshot = inputs['snapshot'] mappings = inputs['mappings'] @@ -1090,7 +1098,8 @@ def generate_shipment_excel( artifact_no=artifact_no, task_id=task.id, template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, - inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task), + inventory_parsing_profile_id=report_config.parsing_profile_id if report_config is not None else None, + inventory_snapshot_id=_notice_inventory_file_id(task), input_checksum=_input_checksum( task, source, template, snapshot, header_values, line_values, inventory_lines, notice_id=int(task.id), diff --git a/backend/app/services/shipping_notice/field_alignment_summary.py b/backend/app/services/shipping_notice/field_alignment_summary.py index 53fba6ce..4ae09739 100644 --- a/backend/app/services/shipping_notice/field_alignment_summary.py +++ b/backend/app/services/shipping_notice/field_alignment_summary.py @@ -3,7 +3,7 @@ services/shipping_notice/field_alignment_summary.py 用途:把库存字段对齐结果格式化成适合聊天区和人工确认的摘要文本。 依赖:shipping_notice.i18n、多语言文案与字段对齐 payload。 -逻辑:由 inventory_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。 +逻辑:由 onhand_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/field_impact_analysis.py b/backend/app/services/shipping_notice/field_impact_analysis.py index 3e74806c..d0cf2bac 100644 --- a/backend/app/services/shipping_notice/field_impact_analysis.py +++ b/backend/app/services/shipping_notice/field_impact_analysis.py @@ -15,9 +15,9 @@ from typing import Any from app.extensions import db from app.models import ( ShippingExcelTemplate, - ShippingInventoryParsingProfile, - ShippingInventoryRoutingRule, - ShippingInventoryRoutingRuleCondition, + FreightRpaParsingProfile, + FreightRpaOnhandRoutingRule, + FreightRpaOnhandRoutingRuleCondition, ShippingOrderDocumentProfile, ShippingOrderField, ShippingOrderFieldDecision, @@ -93,11 +93,11 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]: # [STEP 1] 库存路由条件 routing_rows = ( - db.session.query(ShippingInventoryRoutingRuleCondition, ShippingInventoryRoutingRule) - .join(ShippingInventoryRoutingRule) + db.session.query(FreightRpaOnhandRoutingRuleCondition, FreightRpaOnhandRoutingRule) + .join(FreightRpaOnhandRoutingRule) .filter( - ShippingInventoryRoutingRuleCondition.order_field_id == field_id, - ShippingInventoryRoutingRule.status.in_(['draft', 'published']), + FreightRpaOnhandRoutingRuleCondition.order_field_id == field_id, + FreightRpaOnhandRoutingRule.status.in_(['draft', 'published']), ) .all() ) @@ -114,8 +114,8 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]: )) # [STEP 2] 库存解析档案 match_keys - for profile in ShippingInventoryParsingProfile.query.filter( - ShippingInventoryParsingProfile.status.in_(['draft', 'published']), + for profile in FreightRpaParsingProfile.query.filter( + FreightRpaParsingProfile.status.in_(['draft', 'published']), ).all(): for index, item in enumerate((profile.definition_json or {}).get('match_keys', []) or []): if not isinstance(item, dict): @@ -123,7 +123,7 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]: if str(item.get('order_field_id') or '') != field_id: continue references.append(_ref( - kind='inventory_parsing_profile', + kind='onhand_parsing_profile', object_id=profile.id, display_name=profile.display_name or profile.profile_code, status=profile.status, diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 18afed8d..92144ca6 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -2,8 +2,8 @@ services/shipping_notice/fulfillment_workflow.py 用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。 -依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、 - inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、freight_rpa.upload.trigger_io、 +依赖:customer_identity_gate、reservation_gate、match、export、query_service、onhand_workflow、 + onhand_mapping_workflow、stp_line_onhand_match、upload_attempt_service、freight_rpa.upload.trigger_io、 tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、 order_task_stage_machine。 逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload, @@ -29,14 +29,14 @@ from flask import current_app from app import db from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError -from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingOrderTask +from app.models import ShippingNotice, ShippingNoticeLineOnhandMatch, ShippingOrderTask from app.services.shipping_notice.constants import POSITION_UPLOADED from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values -from app.services.shipping_notice.inventory_file_store import ( +from app.services.shipping_notice.onhand_file_store import ( active_inventory_file_for_task, resolve_inventory_lines_for_execution, ) -from app.services.shipping_notice.inventory_workflow import ( +from app.services.shipping_notice.onhand_workflow import ( ensure_inventory, parse_inventory_lines, ) @@ -70,10 +70,10 @@ from app.services.freight_rpa.onhand.attempts import ( upload_rpa_attempts, ) from app.services.freight_rpa.upload.trigger_io import write_upload_trigger -from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source -from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source +from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source +from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash -from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import log_task_event, prepend_tool_message, set_task_step_progress @@ -83,9 +83,9 @@ from app.services.shipping_notice.task_disposition_service import task_execution def _single_candidate_source_code(task: ShippingNotice) -> str | None: """返回当前 CandidateSet 的唯一源;多源由行级匹配事实决定,不能伪造任务级源。""" - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_codes = task_frozen_inventory_source_codes(task) + source_codes = task_frozen_onhand_source_codes(task) return source_codes[0] if len(source_codes) == 1 else None @@ -687,7 +687,7 @@ def _sync_workflow_stage( def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]: """读取当前任务已审计的短缺放行冻结行 ID,供满足性与聚合重算共用。 - 核心逻辑:只认活动 ``release_inventory_shortage`` 决定;无放行事实时返回空集, + 核心逻辑:只认活动 ``release_onhand_shortage`` 决定;无放行事实时返回空集, 保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。 """ from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision @@ -702,7 +702,7 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]: .filter( ShippingOrderReviewCase.confirmed_task_id == int(task.id), ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) @@ -760,11 +760,11 @@ def match_completed(task: ShippingNotice) -> bool: 已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求, 从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。 """ - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch if task.id is None: return False - rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() if not rows: return False from app.models import ShippingOrderSnapshot @@ -802,14 +802,14 @@ def match_completed(task: ShippingNotice) -> bool: def inventory_match_facts_complete(task: ShippingNotice) -> bool: """判断当前行级匹配是否覆盖冻结订单全部项次且不再处于准备中。""" - from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderSnapshot + from app.models import ShippingNoticeLineOnhandMatch, ShippingOrderSnapshot if task.id is None or not getattr(task, 'order_snapshot_id', None): return False snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if snapshot is None or not snapshot.lines: return False - rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() by_line_id = { int(row.snapshot_line_id): row for row in rows @@ -839,7 +839,7 @@ def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]: .filter( ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) @@ -916,12 +916,12 @@ def excel_gate_error(task: ShippingNotice) -> str | None: """校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。""" # 库存准备失败是硬门禁:即使任务上残留旧的 match/export 投影,也不得继续生成 # 发货 Excel。恢复只能由显式库存准备重试或人工上传重新建立成功事实。 - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt latest_preparation = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(task.id)) - .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()) .first() ) if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed': @@ -1060,7 +1060,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, task_no, trigger=trigger, expected_version=None, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, - resume_gate_code='inventory_matching', + resume_gate_code='onhand_matching', operator_id=operator_id, line_scope_key=str(line_no) if line_no is not None else None, ) @@ -1076,7 +1076,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) # 正式候选冻结任务必须绑定当前 frozen CandidateSet;缺失时禁止回退旧单源/JSON 路径。 - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( build_inventory_candidate_blocking_reason, build_inventory_candidate_primary_action, get_active_candidate_set, @@ -1150,7 +1150,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, if str(code).strip() ] if not scoped_codes: - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines candidate_line = next( ( line for line in get_active_candidate_lines(task) @@ -1181,11 +1181,11 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, position="inventory_source_review", stop_agent_turn=True, ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import ( + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import ( attach_candidate_scope_to_order_lines, apply_forced_match_source_filter, - apply_line_inventory_resolutions, + apply_line_onhand_resolutions, match_order_lines_across_candidates, snapshot_header_reservation_id, ) @@ -1229,7 +1229,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, _sync_workflow_stage( task, - lifecycle_status='inventory_matching', + lifecycle_status='onhand_matching', event_code='inventory_match_line_started', actor_id=actor_id, payload={'task_no': task.task_no, 'line_no': target_line_no, 'line_index': orig_idx}, @@ -1266,7 +1266,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, if isinstance(res, dict): res['line_no'] = target_line_no # [STEP 4] 持久化仅本行(其他行 is_current 保持不变) - from app.services.shipping_notice.line_inventory_match_persistence import ( + from app.services.shipping_notice.line_onhand_match_persistence import ( persist_line_inventory_match_facts, ) persist_line_inventory_match_facts( @@ -1299,7 +1299,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, line_result_status = str(match_payload.get('match_status') or 'unfulfillable') set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1391,14 +1391,14 @@ def _merge_line_inventory_resolutions( def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]: """根据当前 LineMatch 重新计算门禁结果(fulfillable/partial/unfulfillable)与缺口。 - 核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage) + 核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_onhand_shortage) 且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂, 出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。 已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表, 但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。 """ rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), is_current=True) .all() ) @@ -1423,7 +1423,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), 'unit': getattr(row, 'unit', None), - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), 'required_qty': float(required_qty) if required_qty is not None else 0.0, 'available_qty': float(available_qty) if available_qty is not None else 0.0, 'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0, @@ -1474,9 +1474,9 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: """返回当前行级 Match 聚合结果;OT 不回读 step_payload_json 缓存。""" if task.__class__.__name__ == 'ShippingOrderTask': rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), is_current=True) - .order_by(ShippingNoticeLineInventoryMatch.line_no.asc()) + .order_by(ShippingNoticeLineOnhandMatch.line_no.asc()) .all() ) return [ @@ -1486,21 +1486,21 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: 'snapshot_line_id': getattr(row, 'snapshot_line_id', None), 'disposition': getattr(row, 'match_result', None), 'match_result': getattr(row, 'match_result', None), - 'inventory_status': getattr(row, 'inventory_status', None), + 'inventory_status': getattr(row, 'onhand_status', None), 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), 'required_qty': getattr(row, 'required_qty', None), 'available_qty': getattr(row, 'available_qty', None), 'shortage_qty': getattr(row, 'shortage_qty', None), - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), 'candidate_source_codes': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), } for row in rows ] rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), is_current=True) - .order_by(ShippingNoticeLineInventoryMatch.line_no.asc()) + .order_by(ShippingNoticeLineOnhandMatch.line_no.asc()) .all() ) return [ @@ -1510,13 +1510,13 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: 'snapshot_line_id': getattr(row, 'snapshot_line_id', None), 'disposition': getattr(row, 'match_result', None), 'match_result': getattr(row, 'match_result', None), - 'inventory_status': getattr(row, 'inventory_status', None), + 'inventory_status': getattr(row, 'onhand_status', None), 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), 'required_qty': getattr(row, 'required_qty', None), 'available_qty': getattr(row, 'available_qty', None), 'shortage_qty': getattr(row, 'shortage_qty', None), - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), } for row in rows ] @@ -1618,7 +1618,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task_no, trigger=trigger, expected_version=None, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, - resume_gate_code='inventory_matching', + resume_gate_code='onhand_matching', operator_id=operator_id, ) lang = resolve_lang(payload) @@ -1698,14 +1698,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: total_notice_lines = len(order_field_lines) _sync_workflow_stage( task, - lifecycle_status='inventory_matching', + lifecycle_status='onhand_matching', event_code='inventory_match_started', actor_id=actor_id, payload={'task_no': task.task_no}, ) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1726,11 +1726,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: stop_agent_turn=True, ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import ( + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import ( attach_candidate_scope_to_order_lines, apply_forced_match_source_filter, - apply_line_inventory_resolutions, + apply_line_onhand_resolutions, match_order_lines_across_candidates, snapshot_header_reservation_id, ) @@ -1739,7 +1739,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 人工指定源后仅保留 forced_match_source_code 对应库存行,消解多源/多文件冲突。 inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task) use_stp_cross_match = ( - len(task_frozen_inventory_source_codes(task)) >= 1 + len(task_frozen_onhand_source_codes(task)) >= 1 or any(isinstance(row, dict) and row.get('__source_code') for row in (inventory_lines or [])) ) if use_stp_cross_match: @@ -1775,9 +1775,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: inventory_lines=inventory_lines or [], header_reservation_id=header_reservation, ) - apply_line_inventory_resolutions(task, match_payload) + apply_line_onhand_resolutions(task, match_payload) # [STEP] Slice 1:持久化 OT 行匹配事实(ready+not_found=0;缺键→invalid_key) - from app.services.shipping_notice.line_inventory_match_persistence import ( + from app.services.shipping_notice.line_onhand_match_persistence import ( persist_line_inventory_match_facts, ) persist_line_inventory_match_facts( @@ -1808,7 +1808,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", **_match_step_progress_fields( match_status=match_status, @@ -1887,7 +1887,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total))) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1899,20 +1899,23 @@ 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 + from app.models import FreightRpaOnhandField, FreightRpaSource source_code = _single_candidate_source_code(task) - source = ShippingInventorySource.query.filter_by(source_code=source_code).first() - definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} + source = FreightRpaSource.query.filter_by(source_code=source_code).first() + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = source.onhand_report_config if source is not None else None + profile = config.parsing_profile if config is not None else None + definition = profile.definition_json if profile is not None 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', + quantity_fields = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(mapped_field_ids), + FreightRpaOnhandField.status == 'active', + FreightRpaOnhandField.usage_type == 'inventory_quantity', ).all() if mapped_field_ids else [] if len(quantity_fields) != 1: raise ValueError('库存解析方案必须且只能配置一个库存数量字段') @@ -1925,7 +1928,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) # 整单匹配与行级匹配必须写入同一结构化事实表;Review Projection 只读取该表。 # 仅更新 line_results_json 会导致订单明细继续显示“待确认”。 - from app.services.shipping_notice.line_inventory_match_persistence import ( + from app.services.shipping_notice.line_onhand_match_persistence import ( persist_line_inventory_match_facts, ) persist_line_inventory_match_facts( @@ -1944,7 +1947,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", **_match_step_progress_fields( match_status=match_status, diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index 85cd4c17..be190663 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -82,7 +82,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.shortage_confirm_blocked": "库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。", "workflow.decision.parse_confirmed_next": "发货通知已确认。请继续在当前任务中补充库存或等待后端继续处理,并稍后刷新任务状态。", "workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态", - "workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory", + "workflow.decision.parse_confirmed_manual_next": "ensure_onhand 或 parse_inventory", "workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。", "workflow.decision.confirm_invalid_state": "当前状态无法使用确认。请先完成库存匹配,或选择重新解析订单。", "workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。", @@ -208,7 +208,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.shortage_confirm_blocked": "Inventory is insufficient. You cannot use confirm for the whole task. Please use reparse_inventory, rematch, or reject.", "workflow.decision.parse_confirmed_next": "The shipping notice is confirmed. Please continue with inventory for the current task or wait for the backend to continue, then refresh the task status later.", "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.parse_confirmed_manual_next": "ensure_onhand 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. 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.", @@ -334,7 +334,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.shortage_confirm_blocked": "สต็อกไม่เพียงพอ จึงไม่สามารถใช้ confirm เพื่อยืนยันทั้งงานได้ โปรดใช้ reparse_inventory, rematch หรือ reject", "workflow.decision.parse_confirmed_next": "ยืนยันใบแจ้งส่งสินค้าแล้ว โปรดดำเนินการเรื่องสต็อกในงานปัจจุบันต่อ หรือรอให้ระบบหลังบ้านทำต่อ แล้วค่อยรีเฟรชสถานะงาน", "workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง", - "workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory", + "workflow.decision.parse_confirmed_manual_next": "ensure_onhand หรือ parse_inventory", "workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้", "workflow.decision.confirm_invalid_state": "ไม่สามารถยืนยันในสถานะปัจจุบันได้ โปรดจับคู่สต็อกให้เสร็จก่อน หรือแยกวิเคราะห์คำสั่งซื้อใหม่", "workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน", diff --git a/backend/app/services/shipping_notice/receipt_report_access.py b/backend/app/services/shipping_notice/inbound_report_access.py similarity index 69% rename from backend/app/services/shipping_notice/receipt_report_access.py rename to backend/app/services/shipping_notice/inbound_report_access.py index e7d54771..23e1194e 100644 --- a/backend/app/services/shipping_notice/receipt_report_access.py +++ b/backend/app/services/shipping_notice/inbound_report_access.py @@ -1,4 +1,13 @@ -"""收料归档文件的授权下载服务。""" +""" +services/shipping_notice/inbound_report_access.py + +用途:收料归档文件的授权列表与受控下载。 +依赖:FreightRpaInboundReportFile(仅查询/取回行,供授权与审计)、当前用户、 + freight_rpa/reports.read_inbound_file_bytes(归档字节唯一读取入口)。 +逻辑:工作台 /api/workspace/inbound-report-files 调用本模块;下载地址只返回受控 API 路径。 + 阶段 B Task 5 起下载字节改经 freight_rpa/reports 只读函数取得,禁止本模块 + 自持模型 + 对象存储双跳读字节。 +""" from __future__ import annotations @@ -7,8 +16,8 @@ from typing import Any from app import db from app.core.errors import ForbiddenError, NotFoundError -from app.models import ShippingReceiptReportFile, User -from app.services.file_assets.storage import file_asset_storage +from app.models import FreightRpaInboundReportFile, User +from app.services.freight_rpa.reports import read_inbound_file_bytes from app.services.shipping_notice.audit_service import append_shipping_audit_event @@ -17,7 +26,7 @@ def _is_admin(user: User) -> bool: return bool(user.is_platform_admin()) -def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, user: User) -> bool: +def can_download_receipt_report_file(report_file: FreightRpaInboundReportFile, user: User) -> bool: """仅允许管理员或所属排程通知接收人读取收料归档。""" if _is_admin(user): return True @@ -28,7 +37,7 @@ def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, use } -def _serialize_receipt_report_file(report_file: ShippingReceiptReportFile) -> dict[str, Any]: +def _serialize_receipt_report_file(report_file: FreightRpaInboundReportFile) -> dict[str, Any]: """输出可下载收料文件的脱敏列表投影,永不暴露对象存储 bucket 或 key。""" unit = report_file.unit_run run = unit.schedule_run if unit is not None else None @@ -43,20 +52,20 @@ def _serialize_receipt_report_file(report_file: ShippingReceiptReportFile) -> di 'schedule_run_no': run.run_no if run is not None else None, 'archive_expires_at': report_file.archive_expires_at.isoformat() if report_file.archive_expires_at else None, 'created_at': report_file.created_at.isoformat() if report_file.created_at else None, - 'download_url': f'/api/workspace/receipt-report-files/{report_file.id}/download', + 'download_url': f'/api/workspace/inbound-report-files/{report_file.id}/download', } def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str, Any]]: """列出管理员或当前排程接收人可见的未清理收料归档,并留存读取审计。""" bounded_limit = max(1, min(int(limit), 200)) - rows = ShippingReceiptReportFile.query.filter( - ShippingReceiptReportFile.archive_deleted_at.is_(None), - ).order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()).all() + rows = FreightRpaInboundReportFile.query.filter( + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + ).order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()).all() # 先按授权过滤再截断:不能因为前 100 条属于其他排程而遗漏当前接收人的历史文件。 visible = [item for item in rows if can_download_receipt_report_file(item, user)][:bounded_limit] append_shipping_audit_event( - event_type='shipping_receipt_report_files_listed', aggregate_type='shipping_receipt_file_collection', + event_type='shipping_inbound_report_files_listed', aggregate_type='shipping_inbound_file_collection', aggregate_id=str(user.id), actor_type='user', actor_id=user.id, owner_user_id=user.id, result='success', after={'visible_count': len(visible), 'limit': bounded_limit}, metadata={'surface': 'workspace_receipt_report_files'}, @@ -67,21 +76,22 @@ def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str, def resolve_receipt_report_download(file_id: int, user: User) -> tuple[BytesIO, str, str | None]: """授权读取私有对象并记录允许或拒绝的下载审计。""" - report_file = db.session.get(ShippingReceiptReportFile, file_id) + report_file = db.session.get(FreightRpaInboundReportFile, file_id) if report_file is None or report_file.archive_deleted_at is not None: raise NotFoundError('Receipt report file not found', code='SHIPPING.RECEIPT_REPORT_FILE_NOT_FOUND') if not can_download_receipt_report_file(report_file, user): append_shipping_audit_event( - event_type='shipping_receipt_report_download_rejected', aggregate_type='shipping_receipt_file', + event_type='shipping_inbound_report_download_rejected', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id, unit_id=report_file.unit_run_id, result='rejected', reason_code='recipient_not_authorized', after={'status': 'rejected', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], ) db.session.commit() raise ForbiddenError('You are not authorized to download this receipt report') - data = file_asset_storage.get_bytes(report_file.storage_key) + # [STEP] 阶段 B Task 5:归档字节统一经 freight_rpa/reports 只读函数读取(对象存储 key 不外泄、不双跳)。 + data = read_inbound_file_bytes(file_id) append_shipping_audit_event( - event_type='shipping_receipt_report_downloaded', aggregate_type='shipping_receipt_file', + event_type='shipping_inbound_report_downloaded', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id, unit_id=report_file.unit_run_id, result='success', after={'status': 'downloaded', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], diff --git a/backend/app/services/shipping_notice/receipt_report_storage.py b/backend/app/services/shipping_notice/inbound_report_storage.py similarity index 54% rename from backend/app/services/shipping_notice/receipt_report_storage.py rename to backend/app/services/shipping_notice/inbound_report_storage.py index 508e2829..acb10cac 100644 --- a/backend/app/services/shipping_notice/receipt_report_storage.py +++ b/backend/app/services/shipping_notice/inbound_report_storage.py @@ -1,4 +1,7 @@ -"""收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。 +""" +services/shipping_notice/inbound_report_storage.py + +收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。 用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程 @@ -6,12 +9,17 @@ 已下沉 freight_rpa.inbound.report_archive(函数名 receipt 词根→inbound)。 依赖:freight_rpa.inbound.report_archive(归档能力,经 ingest_receipt_callback 委托)、 in_transit_transfer.inbound_callback_bridge / evidence_sync(惰性导入,仅桥), - schedule.freight_inbound_rpa_finalize(惰性导入,仅 finalize)。 + schedule.freight_rpa_inbound_finalize(惰性导入,仅 finalize)。 逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...} envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback - 归档(各终态分支各自 commit),并以 _finish_inbound_callback_terminal 作为 - on_terminal 钩子——commit 之后按拆分前同一顺序执行「推桥 →(success)证据同步 → - finalize」;两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。 + 归档(各终态分支各自 commit 后投递 ReportFact——批次 B Task 6 起归档入口不再收 + on_terminal 钩子)。生产链路的终态收尾自 Task 7 起由调拨侧处理函数 + in_transit_transfer.inbound_report_handler.handle_inbound_report 承担(rpa_sinks 经 + register_report_handler 注册);本模块的 _finish_inbound_callback_terminal + + _advance_transfer_source_job 留守为回归测试桥(tests/test_freight_receipt_rpa_callback. + py 经 register_report_handler 注入复刻拆分前终态收尾),其中桥推进失败 + 【不再吞异常】(Task 7 移除 except Exception: logger.warning——失败必须外抛, + 避免把调拨推进失败再次吞掉;吞异常仅保留在证据同步双保险分支)。 """ from __future__ import annotations @@ -20,44 +28,50 @@ from typing import Any from flask import current_app -from app.models import ShippingReceiptRpaUnitRun +from app.models import FreightRpaInboundUnitRun def _advance_transfer_source_job( - unit: 'ShippingReceiptRpaUnitRun', *, ok: bool, + unit: 'FreightRpaInboundUnitRun', *, ok: bool, file_no: str | None = None, file_sha256: str | None = None, error_code: str | None = None, error_message: str | None = None, ) -> None: - """收料回调终态推进调拨来源任务;失败只记日志,绝不回滚收料归档终态。 + """收料回调终态推进调拨来源任务并提交;失败外抛(Task 7 起不再吞异常)。 Args: unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。 ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。 file_no / file_sha256: success 时绑定的归档文件号与指纹。 error_code / error_message: 失败时的错误码与描述。 + Raises: + Exception: 桥推进/提交失败原样外抛(Task 7 移除 except 吞异常—— + 生产链路的推进失败改由调拨侧处理函数承担并外抛供 Worker 重试; + 本函数留守为回归测试桥,同样不再吞失败)。 """ - try: - from app import db - from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback - advanced = advance_source_job_from_inbound_callback( - source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256, - callback_ok=ok, error_code=error_code, error_message=error_message, - ) - if advanced is not None: - # 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交, - # 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。 - db.session.commit() - except Exception as exc: # noqa: BLE001 —— 桥是记账,不是收料链路的正确性依赖 - from flask import current_app - current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc) + from app import db + from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback + advanced = advance_source_job_from_inbound_callback( + source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256, + callback_ok=ok, error_code=error_code, error_message=error_message, + ) + if advanced is not None: + # 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交, + # 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。 + db.session.commit() def _finish_inbound_callback_terminal( - unit: 'ShippingReceiptRpaUnitRun', *, ok: bool, + unit: 'FreightRpaInboundUnitRun', *, ok: bool, file_no: str | None = None, file_sha256: str | None = None, error_code: str | None = None, error_message: str | None = None, ) -> None: - """终态归档 commit 之后的业务收尾(on_terminal 钩子实现),顺序与拆分前逐点一致。 + """终态归档 commit 之后的业务收尾(留守测试桥),顺序与拆分前逐点一致。 + + 定位(Task 7 起):生产链路的终态收尾已由调拨侧处理函数 + in_transit_transfer.inbound_report_handler.handle_inbound_report 承担 + (rpa_sinks 经 register_report_handler 注册);本函数留守为回归测试桥 + (tests/test_freight_receipt_rpa_callback.py 经 register_report_handler 注入), + 复刻拆分前的桥推进(不再吞异常)+ 证据同步 + 排程收口三段语义。 核心逻辑:[STEP 1] 推进在途调拨来源任务(_advance_transfer_source_job,原 B3 接线); [STEP 2] 仅 success 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路, @@ -82,7 +96,7 @@ def _finish_inbound_callback_terminal( ) except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常 current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc) - from app.services.schedule.freight_inbound_rpa_finalize import ( + from app.services.schedule.freight_rpa_inbound_finalize import ( finalize_receipt_schedule_run_if_complete, refresh_receipt_schedule_run_progress, ) @@ -92,13 +106,17 @@ def _finish_inbound_callback_terminal( def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]: - """幂等接收单个收料单元回调:委托 report_archive 原样归档,终态后执行业务桥收尾。 + """幂等接收单个收料单元回调:委托 report_archive 原样归档(终态后投递事实)。 Args: payload: Worker 回调载荷;schema_version 必须等于 freight_rpa.inbound.v1。 Returns: dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。 + 业务顺序(Task 6 起):归档各终态 commit 后由 report_archive 直接投递 + ReportFact(dispatch_report_fact);本域桥/finalize 收尾改经 + register_report_handler 注册的处理函数承担(Task 7 接线),不再走 + on_terminal 钩子。 """ from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback - return ingest_inbound_callback(payload, on_terminal=_finish_inbound_callback_terminal) + return ingest_inbound_callback(payload) diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 08377db7..1f933f58 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -42,11 +42,11 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { # 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。 'order_review_build': 'order_review', 'task_creation': 'order_review', - 'inventory_source_routing': 'fulfillment_prep', - 'inventory_preparation': 'fulfillment_prep', - 'inventory_field_mapping': 'fulfillment_prep', - 'inventory_matching': 'fulfillment_prep', - 'inventory_sufficiency': 'fulfillment_prep', + 'onhand_source_routing': 'fulfillment_prep', + 'onhand_preparation': 'fulfillment_prep', + 'onhand_field_mapping': 'fulfillment_prep', + 'onhand_matching': 'fulfillment_prep', + 'onhand_sufficiency': 'fulfillment_prep', 'excel_readiness': 'fulfillment_prep', 'artifact_generation': 'fulfillment_prep', 'freight_upload_rpa': 'freight_upload', @@ -65,12 +65,12 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { 'waiting_review': 'order_review', 'customer_resolving': 'order_review', 'duplicate_checking': 'order_review', - 'inventory_source_resolving': 'fulfillment_prep', + 'onhand_source_resolving': 'fulfillment_prep', 'order_creating': 'fulfillment_prep', - 'inventory_fetching': 'fulfillment_prep', - 'inventory_preparation': 'fulfillment_prep', - 'inventory_matching': 'fulfillment_prep', - 'inventory_sufficiency': 'fulfillment_prep', + 'onhand_fetching': 'fulfillment_prep', + 'onhand_preparation': 'fulfillment_prep', + 'onhand_matching': 'fulfillment_prep', + 'onhand_sufficiency': 'fulfillment_prep', 'excel_generating': 'fulfillment_prep', 'freight_uploading': 'freight_upload', 'manual_upload_handoff': 'freight_upload', diff --git a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py index be7ff00b..75fc97c8 100644 --- a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -3,9 +3,9 @@ services/shipping_notice/line_auto_fulfill_coordinator.py 用途:OT 后行级自动履约幂等协调器——统一 matching ready / OT 回调 / 补偿入口。 依赖:line_auto_fulfill_enabled、post_ot_fulfillment_wave_service、post_ot_wave_progress_service、 - ShippingNoticeLineInventoryMatch / LineDecision snapshot。 + ShippingNoticeLineOnhandMatch / LineDecision snapshot。 逻辑:flag 关闭时 skipped;开启时整波创建+专用推进;失败整波回滚后独立写 auto_fulfill_failed 列; - 不创建 wait_inventory 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。 + 不创建 wait_onhand 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。 """ from __future__ import annotations @@ -16,12 +16,12 @@ from typing import Any from app import db from app.models import ( ShippingNotice, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ) -from app.services.shipping_notice.line_inventory_match_persistence import resolve_review_case_for_task -from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled +from app.services.shipping_notice.line_onhand_match_persistence import resolve_review_case_for_task +from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, list_eligible_post_ot_snapshot_line_ids, @@ -40,9 +40,9 @@ def _mark_auto_fulfill_failed( message: str, ) -> None: """ - 独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_inventory。 + 独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_onhand。 - 核心逻辑:写 ShippingNoticeLineInventoryMatch.auto_fulfill_failed* 列;可选同步 snapshot。 + 核心逻辑:写 ShippingNoticeLineOnhandMatch.auto_fulfill_failed* 列;可选同步 snapshot。 """ now = datetime.utcnow() formal_task_id = getattr(case, 'confirmed_task_id', None) @@ -56,7 +56,7 @@ def _mark_auto_fulfill_failed( key_s = str(key) if formal_task_id is not None: fact = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True) .first() ) diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_onhand_match_persistence.py similarity index 87% rename from backend/app/services/shipping_notice/line_inventory_match_persistence.py rename to backend/app/services/shipping_notice/line_onhand_match_persistence.py index 2ef9fc87..6b11cf2b 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_onhand_match_persistence.py @@ -1,11 +1,11 @@ """ -services/shipping_notice/line_inventory_match_persistence.py +services/shipping_notice/line_onhand_match_persistence.py -用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。 -依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。 +用途:onhand_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。 +依赖:ShippingNoticeLineOnhandMatch、ShippingOrderReviewCase、normalize 投影语义。 逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库; 新快照新增行并切换 is_current;不覆盖历史快照事实。 - 行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」; + 行级 onhand_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」; 仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件 ≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。 匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列, @@ -20,12 +20,12 @@ from typing import Any from app import db from app.models import ( - ShippingInventoryFile, + FreightRpaOnhandReportFile, ShippingNotice, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingOrderReviewCase, ) -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, ) @@ -87,9 +87,9 @@ def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) -> src = str(result.get('resolved_inventory_source_code') or '')[:64] or None if src: return src - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_codes = task_frozen_inventory_source_codes(task) + source_codes = task_frozen_onhand_source_codes(task) if len(source_codes) == 1: return source_codes[0][:64] return None @@ -101,7 +101,7 @@ def persist_line_inventory_match_facts( match_payload: dict[str, Any], inventory_snapshot_id: int | None = None, matching_rule_version: str | None = 'stp_line_v2', -) -> list[ShippingNoticeLineInventoryMatch]: +) -> list[ShippingNoticeLineOnhandMatch]: """ 将 match_order_lines_across_candidates 结果持久化为当前事实。 @@ -111,14 +111,14 @@ def persist_line_inventory_match_facts( case = resolve_review_case_for_task(task) snap_id = inventory_snapshot_id if snap_id is None: - from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts + from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts snap_id = active_inventory_runtime_facts(task).get('inventory_file_id') # 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。 snapshot_file_no = None if snap_id is not None: - snapshot = ShippingInventoryFile.query.get(int(snap_id)) - snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None + snapshot = FreightRpaOnhandReportFile.query.get(int(snap_id)) + snapshot_file_no = str(getattr(snapshot, 'onhand_file_no', '') or '').strip() or None # 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照 # (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。 file_id_by_no: dict[str, int | None] = {} @@ -135,7 +135,7 @@ def persist_line_inventory_match_facts( if item.get('line_index') is not None } - written: list[ShippingNoticeLineInventoryMatch] = [] + written: list[ShippingNoticeLineOnhandMatch] = [] now = datetime.utcnow() current_candidate_set = get_active_candidate_set(task) candidate_lines_by_no = { @@ -169,8 +169,8 @@ def persist_line_inventory_match_facts( if line_file_no is not None: if line_file_no not in file_id_by_no: hit_file = ( - ShippingInventoryFile.query - .filter_by(inventory_file_no=line_file_no) + FreightRpaOnhandReportFile.query + .filter_by(onhand_file_no=line_file_no) .first() ) file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None @@ -221,32 +221,32 @@ def persist_line_inventory_match_facts( existing = None if line_snap_id is not None: existing = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by( task_id=int(task.id), snapshot_line_id=snapshot_line_id, line_no=line_no, - inventory_snapshot_id=int(line_snap_id), + onhand_snapshot_id=int(line_snap_id), ) .first() ) if existing is None and line_snap_id is None: existing = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) - .filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None)) + .filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id.is_(None)) .first() ) if existing is None: ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) # 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。 ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), line_index=index, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) @@ -278,7 +278,7 @@ def persist_line_inventory_match_facts( 'snapshot_missing': line_snap_id is None, 'evidence_ref_plain': evidence_plain if evidence_ref else None, } - row = ShippingNoticeLineInventoryMatch( + row = ShippingNoticeLineOnhandMatch( task_id=int(task.id), review_case_id=int(case.id) if case is not None else None, snapshot_line_id=snapshot_line_id, @@ -295,9 +295,9 @@ def persist_line_inventory_match_facts( else None ), candidate_line_id=int(candidate_line.id) if candidate_line is not None else None, - inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None, + onhand_snapshot_id=int(line_snap_id) if line_snap_id is not None else None, match_result=match_result, - inventory_status=inventory_status, + onhand_status=inventory_status, required_qty=str(required) if required is not None else None, available_qty=str(available) if available is not None else None, shortage_qty=str(shortage) if shortage is not None else None, @@ -311,7 +311,7 @@ def persist_line_inventory_match_facts( part_number=pn, unit=unit_value, matching_rule_version=str(matching_rule_version or '')[:64] or None, - inventory_source_code=src_code, + source_code=src_code, is_current=True, matched_at=now, # T6 行级证据 @@ -368,7 +368,7 @@ def persist_line_inventory_match_facts( 'evidence_ref_plain': evidence_plain if evidence_ref else None, } existing.match_result = match_result - existing.inventory_status = inventory_status + existing.onhand_status = inventory_status existing.required_qty = str(required) if required is not None else None existing.available_qty = str(available) if available is not None else None existing.shortage_qty = str(shortage) if shortage is not None else None @@ -381,7 +381,7 @@ def persist_line_inventory_match_facts( existing.part_number = pn existing.unit = unit_value existing.matching_rule_version = str(matching_rule_version or '')[:64] or None - existing.inventory_source_code = src_code + existing.source_code = src_code existing.is_current = True existing.invalidated_at = None existing.invalidated_by_attempt_id = None @@ -415,23 +415,23 @@ def persist_line_inventory_match_facts( existing.detail_json = detail_json # 确保同 task+line 仅本条 current ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id, - ShippingNoticeLineInventoryMatch.id != int(existing.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.snapshot_line_id == snapshot_line_id, + ShippingNoticeLineOnhandMatch.id != int(existing.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) # 同一订单行更新时关闭旧事实,保证 current 投影唯一。 ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.line_index == index, - ShippingNoticeLineInventoryMatch.id != int(existing.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.line_index == index, + ShippingNoticeLineOnhandMatch.id != int(existing.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_onhand_match_projection.py similarity index 95% rename from backend/app/services/shipping_notice/line_inventory_match_projection.py rename to backend/app/services/shipping_notice/line_onhand_match_projection.py index 8a150b4b..9da98c9e 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_onhand_match_projection.py @@ -1,15 +1,15 @@ """ -services/shipping_notice/line_inventory_match_projection.py +services/shipping_notice/line_onhand_match_projection.py 用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。 -依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。 +依赖:ShippingNoticeLineOnhandMatch、FreightRpaOnhandTaskAttempt、Config 自动履约开关。 逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用; ready+not_found→available=0;result_missing 不得转 0; part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None, 不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算); inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮); line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail; - load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo, + load_current_match_facts_by_task / onhand_rpa_is_running 在同一 HTTP 请求内 memo, 禁止按行重复查库。 """ @@ -19,9 +19,9 @@ from decimal import Decimal, InvalidOperation from typing import Any from app.models import ( - ShippingInventoryFile, - ShippingNoticeLineInventoryMatch, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandReportFile, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandTaskAttempt, ) @@ -41,10 +41,10 @@ STATUS_SOURCE_CONFLICT = 'source_conflict' STATUS_UNAVAILABLE = 'unavailable' STATUS_INVALID_KEY = 'invalid_key' -ACTION_RETRY_PREPARATION = 'retry_inventory_preparation' -ACTION_RETRY_MATCHING = 'retry_inventory_matching' +ACTION_RETRY_PREPARATION = 'retry_onhand_preparation' +ACTION_RETRY_MATCHING = 'retry_onhand_matching' ACTION_CLOSE = 'close_unfulfillable' -ACTION_RELEASE_SHORTAGE = 'release_inventory_shortage' +ACTION_RELEASE_SHORTAGE = 'release_onhand_shortage' ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI @@ -455,10 +455,10 @@ def inventory_rpa_is_running(task: Any) -> bool: try: running = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')), ) .first() is not None @@ -496,7 +496,7 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, cache = None rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=key, is_current=True) .all() ) @@ -519,7 +519,7 @@ def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dic if task_id is None: return {} rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task_id), is_current=True) .all() ) @@ -543,11 +543,11 @@ def aggregate_match_status_for_task(task_id: int | None) -> str | None: return 'unfulfillable' if blocked else 'fulfillable' -def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]: +def serialize_match_fact(row: ShippingNoticeLineOnhandMatch) -> dict[str, Any]: """将 ORM 行序列化为投影输入。""" snapshot = ( - ShippingInventoryFile.query.get(int(row.inventory_snapshot_id)) - if row.inventory_snapshot_id is not None else None + FreightRpaOnhandReportFile.query.get(int(row.onhand_snapshot_id)) + if row.onhand_snapshot_id is not None else None ) return { 'id': int(row.id), @@ -557,10 +557,10 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'line_no': int(row.line_no), 'line_index': row.line_index, 'inventory_snapshot_id': ( - int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None + int(row.onhand_snapshot_id) if row.onhand_snapshot_id is not None else None ), 'match_result': str(row.match_result or ''), - 'inventory_status': str(row.inventory_status or ''), + 'inventory_status': str(row.onhand_status or ''), 'required_qty': row.required_qty, 'available_qty': row.available_qty, 'shortage_qty': row.shortage_qty, @@ -569,7 +569,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'part_number': row.part_number, 'unit': row.unit, 'matching_rule_version': row.matching_rule_version, - 'inventory_source_code': row.inventory_source_code, + 'inventory_source_code': row.source_code, 'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), 'inventory_file_no': getattr(row, 'matched_file_no', None), 'inventory_file_sha256': ( diff --git a/backend/app/services/shipping_notice/match_rule_desc.py b/backend/app/services/shipping_notice/match_rule_desc.py index a9481271..578067cc 100644 --- a/backend/app/services/shipping_notice/match_rule_desc.py +++ b/backend/app/services/shipping_notice/match_rule_desc.py @@ -3,7 +3,7 @@ services/shipping_notice/match_rule_desc.py 用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。 依赖:标准类型能力。 -逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。 +逻辑:由 onhand_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/notice_line_table.py b/backend/app/services/shipping_notice/notice_line_table.py index 8b98a9a2..4a0d3379 100644 --- a/backend/app/services/shipping_notice/notice_line_table.py +++ b/backend/app/services/shipping_notice/notice_line_table.py @@ -2,7 +2,7 @@ services/shipping_notice/notice_line_table.py 用途:从发货通知表格文本或二维行数据中解析订单行。 -依赖:notice_line_values、动态 Schema 表头契约、reservation_id、inventory_snapshot(懒加载表格拆行)。 +依赖:notice_line_values、动态 Schema 表头契约、reservation_id、onhand_snapshot(懒加载表格拆行)。 逻辑:调用方显式传入冻结契约;歧义表头不静默选列,输出诊断供 Run 进入复核。 """ @@ -229,7 +229,7 @@ def inspect_notice_table_text( Returns: `lines`、`header_found`、`ambiguous_fields` 和表头索引。 """ - from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text + from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text text = str(raw_text or '').strip() if not text or contract is None: @@ -257,6 +257,6 @@ def parse_notice_table_text( """ 从发货通知原始文本中的表格片段解析订单行。 - 核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。 + 核心逻辑:先借助 onhand_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。 """ return list(inspect_notice_table_text(raw_text, contract=contract)['lines']) diff --git a/backend/app/services/shipping_notice/notice_odm_choice_service.py b/backend/app/services/shipping_notice/notice_odm_choice_service.py index 38eef103..b7e0f698 100644 --- a/backend/app/services/shipping_notice/notice_odm_choice_service.py +++ b/backend/app/services/shipping_notice/notice_odm_choice_service.py @@ -2,10 +2,10 @@ services/shipping_notice/notice_odm_choice_service.py 用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。 -依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。 +依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineOnhandMatch、AppError。 逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一 事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行 - (shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」 + (shipping_notice_line_onhand_matches.chosen_odm_id)上,按「同一库存快照文件」 圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值); 重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。 """ @@ -16,7 +16,7 @@ from typing import Any from app import db from app.core.errors import AppError -from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch +from app.models import ShippingCustomer, ShippingNoticeLineOnhandMatch _ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID' @@ -127,7 +127,7 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s http_status=409, ) target_row = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by( task_id=int(task_id), snapshot_line_id=int(snapshot_line_id or 0), @@ -144,11 +144,11 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s ) # 同步范围:与目标行关联同一快照文件的全部当前匹配行。 scope_rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task_id), is_current=True) - .filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id) + .filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id == target_row.onhand_snapshot_id) .all() - ) if target_row.inventory_snapshot_id is not None else [target_row] + ) if target_row.onhand_snapshot_id is not None else [target_row] lines_by_sid = { str(item.get('snapshot_line_id')): item for item in options.get('lines') or [] } diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/onhand_candidate_freeze_service.py similarity index 88% rename from backend/app/services/shipping_notice/inventory_candidate_freeze_service.py rename to backend/app/services/shipping_notice/onhand_candidate_freeze_service.py index ecfd5780..1f937ea5 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py +++ b/backend/app/services/shipping_notice/onhand_candidate_freeze_service.py @@ -1,13 +1,13 @@ """ -services/shipping_notice/inventory_candidate_freeze_service.py +services/shipping_notice/onhand_candidate_freeze_service.py 用途:库存候选冻结的统一写入服务——将路由评估结果写入 Set/Source/Line 三张结构化表 (T2 新建,决策 C1 的正式业务真相),并同步写 ShippingOrderSnapshot.source_manifest_json 作为不可变审计副本。 -依赖:app.models.shipping_inventory_candidates(Set/Source/Line)、inventory_source_rules、 - inventory_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。 +依赖:app.models.shipping_onhand_candidates(Set/Source/Line)、onhand_source_rules、 + onhand_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。 逻辑:由 adjudicate_and_apply_inventory_source(裁决阶段 ambiguous→candidates_frozen) - 与 STP 建单 freeze_stp_inventory_candidates_on_task 两条路径调用; + 与 STP 建单 freeze_stp_onhand_candidates_on_task 两条路径调用; input_fingerprint 相同则直接返回旧 set_id(幂等),冻结结果不可变。 """ @@ -26,17 +26,17 @@ from sqlalchemy.orm import Session from app import db from app.models import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, ShippingNotice, ShippingOrderSnapshot, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, _task_routing_lines, compute_routing_fingerprint, @@ -90,9 +90,9 @@ def _build_input_fingerprint( def _build_manifest_snapshot( *, task: ShippingNotice, - set_db: ShippingInventoryCandidateSet, - sources_db: list[ShippingInventoryCandidateSource], - lines_db: list[ShippingInventoryCandidateLine], + set_db: ShippingOnhandCandidateSet, + sources_db: list[ShippingOnhandCandidateSource], + lines_db: list[ShippingOnhandCandidateLine], routing_rule_version_json: dict[str, Any] | None, ) -> dict[str, Any]: """ @@ -215,35 +215,35 @@ def _find_existing_frozen_set( review_case_id: int | None, input_fingerprint: str, session: Session, -) -> ShippingInventoryCandidateSet | None: +) -> ShippingOnhandCandidateSet | None: """ 根据幂等键查找已存在的冻结 Set(task 绑定或 review_case 绑定分别查询)。 PostgreSQL 部分唯一索引保证每个绑定维度的 fingerprint 唯一。 """ if task_id is not None: return ( - session.query(ShippingInventoryCandidateSet) + session.query(ShippingOnhandCandidateSet) .filter( and_( - ShippingInventoryCandidateSet.task_id == task_id, - ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint, - ShippingInventoryCandidateSet.lifecycle_status == 'frozen', + ShippingOnhandCandidateSet.task_id == task_id, + ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint, + ShippingOnhandCandidateSet.lifecycle_status == 'frozen', ) ) - .order_by(ShippingInventoryCandidateSet.id.desc()) + .order_by(ShippingOnhandCandidateSet.id.desc()) .first() ) if review_case_id is not None: return ( - session.query(ShippingInventoryCandidateSet) + session.query(ShippingOnhandCandidateSet) .filter( and_( - ShippingInventoryCandidateSet.review_case_id == review_case_id, - ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint, - ShippingInventoryCandidateSet.lifecycle_status == 'frozen', + ShippingOnhandCandidateSet.review_case_id == review_case_id, + ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint, + ShippingOnhandCandidateSet.lifecycle_status == 'frozen', ) ) - .order_by(ShippingInventoryCandidateSet.id.desc()) + .order_by(ShippingOnhandCandidateSet.id.desc()) .first() ) return None @@ -252,8 +252,8 @@ def _find_existing_frozen_set( def _next_task_set_version(*, task_id: int, session: Session) -> int: """计算 Task 维度下一个 CandidateSet.version。""" current_max = ( - session.query(func.max(ShippingInventoryCandidateSet.set_version)) - .filter(ShippingInventoryCandidateSet.task_id == int(task_id)) + session.query(func.max(ShippingOnhandCandidateSet.set_version)) + .filter(ShippingOnhandCandidateSet.task_id == int(task_id)) .scalar() ) return int(current_max or 0) + 1 @@ -269,10 +269,10 @@ def _invalidate_task_candidate_outputs( """ from app.models import ( ShippingExportArtifact, - ShippingInventoryPreparationAttempt, - ShippingNoticeLineInventoryMatch, + ShippingOnhandPreparationAttempt, + ShippingNoticeLineOnhandMatch, ShippingProcessRecoveryPlan, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandTaskAttempt, ShippingUploadAttempt, ) @@ -285,18 +285,18 @@ def _invalidate_task_candidate_outputs( task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}} ( - session.query(ShippingNoticeLineInventoryMatch) + session.query(ShippingNoticeLineOnhandMatch) .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': datetime.utcnow()}, synchronize_session=False) ) ( - session.query(ShippingTaskInventoryRpaAttempt) + session.query(FreightRpaOnhandTaskAttempt) .filter( - ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or ''), - ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or ''), + FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')), ) .update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False) ) @@ -326,19 +326,19 @@ def _invalidate_task_candidate_outputs( 'finished_at': datetime.utcnow(), 'error_code': 'candidate_set_refrozen', }, synchronize_session=False) - prep_query = session.query(ShippingInventoryPreparationAttempt).filter( - ShippingInventoryPreparationAttempt.task_id == int(task.id), - ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')), + prep_query = session.query(ShippingOnhandPreparationAttempt).filter( + ShippingOnhandPreparationAttempt.task_id == int(task.id), + ShippingOnhandPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')), ) if old_candidate_set_id is not None: prep_query = prep_query.filter( - ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id) + ShippingOnhandPreparationAttempt.candidate_set_id == int(old_candidate_set_id) ) prep_query.update({'status': 'superseded'}, synchronize_session=False) active_execution_ids = [ - row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter( - ShippingInventoryPreparationAttempt.task_id == int(task.id), - ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id, + row[0] for row in session.query(ShippingOnhandPreparationAttempt.execution_id).filter( + ShippingOnhandPreparationAttempt.task_id == int(task.id), + ShippingOnhandPreparationAttempt.candidate_set_id == old_candidate_set_id, ).all() if row[0] ] if active_execution_ids: @@ -395,7 +395,7 @@ def freeze_candidates_for_task( session = session or db.session if adjudication is None: - from app.services.shipping_notice.inventory_source_rules import adjudicate_inventory_source + from app.services.shipping_notice.onhand_source_rules import adjudicate_inventory_source adjudication = adjudicate_inventory_source(task) @@ -478,7 +478,7 @@ def freeze_candidates_for_task( 'adjudication_reason': adjudication.reason, } existing_active = ( - session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id)) if getattr(task, 'active_inventory_candidate_set_id', None) is not None and getattr(task, 'id', None) is not None else None ) @@ -487,7 +487,7 @@ def freeze_candidates_for_task( if getattr(task, 'id', None) is not None else 1 ) - new_set = ShippingInventoryCandidateSet( + new_set = ShippingOnhandCandidateSet( task_id=task.id, review_case_id=review_case_id, execution_id=execution_id, @@ -503,7 +503,7 @@ def freeze_candidates_for_task( session.add(new_set) session.flush() - created_sources: list[ShippingInventoryCandidateSource] = [] + created_sources: list[ShippingOnhandCandidateSource] = [] for idx, code in enumerate(task_source_codes_ordered): src_cfg = get_database_inventory_source(code) rule_id: int | None = None @@ -514,13 +514,13 @@ def freeze_candidates_for_task( if isinstance(matched_rule_ids, list) and matched_rule_ids: try: _rule_ids_int = int(matched_rule_ids[0]) - from app.models.shipping_inventory_config import ShippingInventoryRoutingRule + from app.models.freight_rpa_config import FreightRpaOnhandRoutingRule rule_row = ( session.query( - ShippingInventoryRoutingRule.id, - ShippingInventoryRoutingRule.version, + FreightRpaOnhandRoutingRule.id, + FreightRpaOnhandRoutingRule.version, ) - .filter(ShippingInventoryRoutingRule.id == _rule_ids_int) + .filter(FreightRpaOnhandRoutingRule.id == _rule_ids_int) .one_or_none() ) if rule_row is not None: @@ -529,7 +529,7 @@ def freeze_candidates_for_task( except (TypeError, ValueError): rule_id = None rule_version = None - source = ShippingInventoryCandidateSource( + source = ShippingOnhandCandidateSource( candidate_set_id=new_set.id, source_code=code, candidate_order=idx + 1, @@ -550,7 +550,7 @@ def freeze_candidates_for_task( for line in debug_env.read_text(encoding='utf-8').splitlines() if '=' in line } - urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'inventory_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read() + urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'onhand_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read() except Exception: pass # #endregion @@ -558,10 +558,10 @@ def freeze_candidates_for_task( created_sources.append(source) session.flush(created_sources) - created_lines: list[ShippingInventoryCandidateLine] = [] + created_lines: list[ShippingOnhandCandidateLine] = [] for sig in signatures: line_no, source_line_no, pn, resv, codes_ordered = sig - line_entity = ShippingInventoryCandidateLine( + line_entity = ShippingOnhandCandidateLine( candidate_set_id=new_set.id, line_no=line_no, source_line_no=source_line_no, @@ -671,7 +671,7 @@ def freeze_manual_line_source_selection( raise ValueError('未找到该订单项次') active_set = ( - session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id)) if task.active_inventory_candidate_set_id is not None else None ) existing_codes = { @@ -733,7 +733,7 @@ def active_candidate_set_is_manually_pinned( """ sess = session or db.session active_set = ( - sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + sess.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id)) if getattr(task, 'active_inventory_candidate_set_id', None) is not None else None ) @@ -759,8 +759,8 @@ def refresh_candidates_from_current_routing( 禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。 核心逻辑: - [守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单 - 不得自动改源,换源走 override_line_inventory_source 行级覆写。 + [守卫 1] 仅多候选未定源可刷新(task_frozen_onhand_source_codes > 1);源已定单 + 不得自动改源,换源走 override_line_onhand_source 行级覆写。 [守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override') 时跳过:人工指定即定论,禁止重路由洗掉人工裁决。 [STEP 1] 记录当前活动 set_id。 @@ -778,12 +778,12 @@ def refresh_candidates_from_current_routing( Returns: bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 """ - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set - from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes sess = session or db.session - if len(task_frozen_inventory_source_codes(task)) <= 1: + if len(task_frozen_onhand_source_codes(task)) <= 1: return False if active_candidate_set_is_manually_pinned(task, session=sess): return False @@ -804,7 +804,7 @@ def refresh_candidates_from_current_routing( 'scope': 'task', 'previous_set_id': before_set_id, 'new_set_id': after_set_id, - 'source_codes': task_frozen_inventory_source_codes(task), + 'source_codes': task_frozen_onhand_source_codes(task), }, source='system', ) @@ -820,7 +820,7 @@ def refresh_line_candidates_from_current_routing( ) -> bool: """ 行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。 - 【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带 + 【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_onhand_preparation 携带 line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。 核心逻辑: @@ -844,12 +844,12 @@ def refresh_line_candidates_from_current_routing( Returns: bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 """ - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) - from app.services.shipping_notice.inventory_source_rules import ( + from app.services.shipping_notice.onhand_source_rules import ( _task_routing_lines, compute_routing_fingerprint, evaluate_inventory_source_rules, @@ -990,7 +990,7 @@ def freeze_wave_notice_routing( """ from app.models.shipping_notice_line import ShippingNoticeLine from app.services.shipping_notice.export import order_field_id_values - from app.services.shipping_notice.inventory_routing_engine import ( + from app.services.shipping_notice.onhand_routing_engine import ( evaluate_inventory_source_rules_for_field_values, ) @@ -1048,7 +1048,7 @@ def freeze_wave_notice_routing( if not task_codes: return None - from app.services.shipping_notice.inventory_source_rules import ( + from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, _candidate, compute_routing_fingerprint, diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/onhand_candidate_projection.py similarity index 82% rename from backend/app/services/shipping_notice/inventory_candidate_projection.py rename to backend/app/services/shipping_notice/onhand_candidate_projection.py index 68dd12a2..0905f01a 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_projection.py +++ b/backend/app/services/shipping_notice/onhand_candidate_projection.py @@ -1,9 +1,9 @@ """ -services/shipping_notice/inventory_candidate_projection.py +services/shipping_notice/onhand_candidate_projection.py 用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。 -依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、 - ShippingTaskInventoryRpaAttempt。 +依赖:ShippingOrderTask、ShippingOnhandCandidateSet/Source/Line、ShippingNoticeLineOnhandMatch、 + FreightRpaOnhandTaskAttempt。 逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、 坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。 """ @@ -17,14 +17,14 @@ from sqlalchemy.orm import Session from app import db from app.models import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, - ShippingInventoryFile, + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, + FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask, - ShippingNoticeLineInventoryMatch, - ShippingTaskInventoryRpaAttempt, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandTaskAttempt, ) @@ -60,23 +60,23 @@ def _candidate_set_filter( *, include_drafts: bool = False, session: Session | None = None, -) -> list[ShippingInventoryCandidateSet]: +) -> list[ShippingOnhandCandidateSet]: """按 Task 读取候选版本列表;默认隐藏 draft。""" if getattr(task, 'id', None) is None: return [] query = ( _session(session) - .query(ShippingInventoryCandidateSet) - .filter(ShippingInventoryCandidateSet.task_id == int(task.id)) + .query(ShippingOnhandCandidateSet) + .filter(ShippingOnhandCandidateSet.task_id == int(task.id)) ) if not include_drafts: query = query.filter( - ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, + ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, ) rows = ( query.order_by( - ShippingInventoryCandidateSet.set_version.desc(), - ShippingInventoryCandidateSet.id.desc(), + ShippingOnhandCandidateSet.set_version.desc(), + ShippingOnhandCandidateSet.id.desc(), ) .all() ) @@ -114,7 +114,7 @@ def get_active_candidate_set( task: ShippingOrderTask | ShippingNotice, *, session: Session | None = None, -) -> ShippingInventoryCandidateSet | None: +) -> ShippingOnhandCandidateSet | None: """ 读取正式 Task 当前 frozen CandidateSet。 @@ -126,7 +126,7 @@ def get_active_candidate_set( candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None) if candidate_set_id is None: return None - row = _session(session).get(ShippingInventoryCandidateSet, int(candidate_set_id)) + row = _session(session).get(ShippingOnhandCandidateSet, int(candidate_set_id)) if row is None: return None if int(getattr(row, 'task_id', 0) or 0) != int(getattr(task, 'id', 0) or 0): @@ -140,18 +140,18 @@ def get_active_candidate_sources( task: ShippingOrderTask, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateSource]: +) -> list[ShippingOnhandCandidateSource]: """读取当前 frozen Set 的任务级候选源。""" current = get_active_candidate_set(task, session=session) if current is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateSource) - .filter(ShippingInventoryCandidateSource.candidate_set_id == int(current.id)) + .query(ShippingOnhandCandidateSource) + .filter(ShippingOnhandCandidateSource.candidate_set_id == int(current.id)) .order_by( - ShippingInventoryCandidateSource.candidate_order.asc(), - ShippingInventoryCandidateSource.id.asc(), + ShippingOnhandCandidateSource.candidate_order.asc(), + ShippingOnhandCandidateSource.id.asc(), ) .all() ) @@ -162,18 +162,18 @@ def get_active_candidate_lines( task: ShippingOrderTask, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateLine]: +) -> list[ShippingOnhandCandidateLine]: """读取当前 frozen Set 的行级候选。""" current = get_active_candidate_set(task, session=session) if current is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateLine) - .filter(ShippingInventoryCandidateLine.candidate_set_id == int(current.id)) + .query(ShippingOnhandCandidateLine) + .filter(ShippingOnhandCandidateLine.candidate_set_id == int(current.id)) .order_by( - ShippingInventoryCandidateLine.line_no.asc(), - ShippingInventoryCandidateLine.id.asc(), + ShippingOnhandCandidateLine.line_no.asc(), + ShippingOnhandCandidateLine.id.asc(), ) .all() ) @@ -198,7 +198,7 @@ def active_inventory_runtime_facts( Returns: source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。 """ - from app.models import ShippingTaskInventoryLink + from app.models import ShippingTaskOnhandLink sess = _session(session) candidate_set = get_active_candidate_set(task, session=sess) @@ -206,9 +206,9 @@ def active_inventory_runtime_facts( source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()] versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()] link = ( - sess.query(ShippingTaskInventoryLink) - .filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True)) - .order_by(ShippingTaskInventoryLink.id.desc()) + sess.query(ShippingTaskOnhandLink) + .filter(ShippingTaskOnhandLink.task_id == int(task.id), ShippingTaskOnhandLink.is_active.is_(True)) + .order_by(ShippingTaskOnhandLink.id.desc()) .first() if getattr(task, 'id', None) is not None else None ) @@ -218,7 +218,7 @@ def active_inventory_runtime_facts( 'source_codes': source_codes, 'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None, 'active_link': link, - 'inventory_file_id': getattr(link, 'inventory_file_id', None), + 'inventory_file_id': getattr(link, 'onhand_file_id', None), 'inventory_file': getattr(link, 'inventory_file', None), } @@ -229,26 +229,26 @@ def get_candidate_set_by_version( *, include_drafts: bool = False, session: Session | None = None, -) -> ShippingInventoryCandidateSet | None: +) -> ShippingOnhandCandidateSet | None: """按 Task + set_version 读取指定候选版本。""" if getattr(task, 'id', None) is None: return None query = ( _session(session) - .query(ShippingInventoryCandidateSet) + .query(ShippingOnhandCandidateSet) .filter( - ShippingInventoryCandidateSet.task_id == int(task.id), - ShippingInventoryCandidateSet.set_version == int(version), + ShippingOnhandCandidateSet.task_id == int(task.id), + ShippingOnhandCandidateSet.set_version == int(version), ) ) if not include_drafts: query = query.filter( - ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, + ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, ) - return query.order_by(ShippingInventoryCandidateSet.id.desc()).first() + return query.order_by(ShippingOnhandCandidateSet.id.desc()).first() -def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -> dict[str, Any] | None: +def serialize_candidate_set_summary(row: ShippingOnhandCandidateSet | None) -> dict[str, Any] | None: """序列化 CandidateSet 摘要供 API / Projection 复用。""" if row is None: return None @@ -268,7 +268,7 @@ def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) - } -def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[str, Any]: +def serialize_candidate_source(row: ShippingOnhandCandidateSource) -> dict[str, Any]: """序列化任务级候选源。""" return { 'id': int(row.id), @@ -284,7 +284,7 @@ def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[st } -def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, Any]: +def serialize_candidate_line(row: ShippingOnhandCandidateLine) -> dict[str, Any]: """序列化行级候选源与稳定行标识。""" return { 'candidate_line_id': int(row.id), @@ -300,20 +300,20 @@ def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, A def _candidate_sources_for_set( - candidate_set: ShippingInventoryCandidateSet | None, + candidate_set: ShippingOnhandCandidateSet | None, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateSource]: +) -> list[ShippingOnhandCandidateSource]: """读取指定 CandidateSet 的任务级候选源。""" if candidate_set is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateSource) - .filter(ShippingInventoryCandidateSource.candidate_set_id == int(candidate_set.id)) + .query(ShippingOnhandCandidateSource) + .filter(ShippingOnhandCandidateSource.candidate_set_id == int(candidate_set.id)) .order_by( - ShippingInventoryCandidateSource.candidate_order.asc(), - ShippingInventoryCandidateSource.id.asc(), + ShippingOnhandCandidateSource.candidate_order.asc(), + ShippingOnhandCandidateSource.id.asc(), ) .all() ) @@ -321,20 +321,20 @@ def _candidate_sources_for_set( def _candidate_lines_for_set( - candidate_set: ShippingInventoryCandidateSet | None, + candidate_set: ShippingOnhandCandidateSet | None, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateLine]: +) -> list[ShippingOnhandCandidateLine]: """读取指定 CandidateSet 的行级候选。""" if candidate_set is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateLine) - .filter(ShippingInventoryCandidateLine.candidate_set_id == int(candidate_set.id)) + .query(ShippingOnhandCandidateLine) + .filter(ShippingOnhandCandidateLine.candidate_set_id == int(candidate_set.id)) .order_by( - ShippingInventoryCandidateLine.line_no.asc(), - ShippingInventoryCandidateLine.id.asc(), + ShippingOnhandCandidateLine.line_no.asc(), + ShippingOnhandCandidateLine.id.asc(), ) .all() ) @@ -373,15 +373,15 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], return {} rows = ( _session(session) - .query(ShippingTaskInventoryRpaAttempt) + .query(FreightRpaOnhandTaskAttempt) .filter( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code.in_(source_codes), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code.in_(source_codes), ) .order_by( - ShippingTaskInventoryRpaAttempt.source_code.asc(), - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), + FreightRpaOnhandTaskAttempt.source_code.asc(), + FreightRpaOnhandTaskAttempt.attempt_no.desc(), + FreightRpaOnhandTaskAttempt.id.desc(), ) .all() ) @@ -397,7 +397,7 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], 'run_no': str(row.run_no or ''), 'error_code': getattr(row, 'error_code', None), 'error_message': getattr(row, 'error_message', None), - 'inventory_file_no': getattr(row, 'inventory_file_no', None), + 'inventory_file_no': getattr(row, 'onhand_file_no', None), 'updated_at': _iso(getattr(row, 'updated_at', None)), } return out @@ -419,20 +419,20 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str, return prepared, pending, failed -def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]: +def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineOnhandMatch]: """读取任务当前生效的行级匹配事实。""" if getattr(task, 'id', None) is None: return [] rows = ( _session(session) - .query(ShippingNoticeLineInventoryMatch) + .query(ShippingNoticeLineOnhandMatch) .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .order_by( - ShippingNoticeLineInventoryMatch.line_index.asc(), - ShippingNoticeLineInventoryMatch.id.asc(), + ShippingNoticeLineOnhandMatch.line_index.asc(), + ShippingNoticeLineOnhandMatch.id.asc(), ) .all() ) @@ -548,20 +548,20 @@ def project_inventory_candidate_facts( current_match_rows = _current_match_rows(task, session=sess) # [BE-性能] 批量预取当前匹配行引用的库存快照,避免循环内逐行 sess.get() 造成 N+1。 snapshot_ids = { - int(row.inventory_snapshot_id) + int(row.onhand_snapshot_id) for row in current_match_rows - if getattr(row, 'inventory_snapshot_id', None) is not None + if getattr(row, 'onhand_snapshot_id', None) is not None } snapshot_by_id: dict[int, Any] = {} if snapshot_ids: snapshot_by_id = { int(item.id): item - for item in sess.query(ShippingInventoryFile).filter(ShippingInventoryFile.id.in_(snapshot_ids)).all() + for item in sess.query(FreightRpaOnhandReportFile).filter(FreightRpaOnhandReportFile.id.in_(snapshot_ids)).all() } for row in current_match_rows: snapshot = ( - snapshot_by_id.get(int(row.inventory_snapshot_id)) - if getattr(row, 'inventory_snapshot_id', None) is not None else None + snapshot_by_id.get(int(row.onhand_snapshot_id)) + if getattr(row, 'onhand_snapshot_id', None) is not None else None ) allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None)) serialized = { @@ -577,11 +577,11 @@ def project_inventory_candidate_facts( # [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源), # 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。 'resolved_inventory_source_code': ( - getattr(row, 'inventory_source_code', None) + getattr(row, 'source_code', None) or (allowed_codes[0] if len(allowed_codes) == 1 else None) ), 'inventory_file_no': getattr(row, 'matched_file_no', None), - 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None), + 'inventory_snapshot_id': getattr(row, 'onhand_snapshot_id', None), 'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')), 'inventory_file_sha256': ( dict(getattr(row, 'detail_json', None) or {}).get('file_sha256') @@ -619,9 +619,9 @@ def project_inventory_candidate_facts( 'operation_id': f'match-line:{int(row.id)}', } elif ( - str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + str(getattr(row, 'source_code', '') or '').strip().upper() and allowed_codes - and str(getattr(row, 'inventory_source_code', '') or '').strip().upper() not in allowed_codes + and str(getattr(row, 'source_code', '') or '').strip().upper() not in allowed_codes ): out_of_scope_details = { 'candidate_line_id': int(candidate_line_id), @@ -631,7 +631,7 @@ def project_inventory_candidate_facts( 'actual_candidate_set_version': getattr(row, 'candidate_set_version', None), 'detected_at': datetime.utcnow().isoformat(), 'operation_id': f'match-line:{int(row.id)}', - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), 'allowed_source_codes_snapshot': allowed_codes, } diff --git a/backend/app/services/shipping_notice/inventory_combination_fingerprint.py b/backend/app/services/shipping_notice/onhand_combination_fingerprint.py similarity index 95% rename from backend/app/services/shipping_notice/inventory_combination_fingerprint.py rename to backend/app/services/shipping_notice/onhand_combination_fingerprint.py index 4ee2d573..7ea37d31 100644 --- a/backend/app/services/shipping_notice/inventory_combination_fingerprint.py +++ b/backend/app/services/shipping_notice/onhand_combination_fingerprint.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_combination_fingerprint.py +services/shipping_notice/onhand_combination_fingerprint.py 用途:为多源库存准备轮次生成稳定组合输入指纹。 依赖:标准库 hashlib/json。 diff --git a/backend/app/services/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/onhand_configuration_test.py similarity index 71% rename from backend/app/services/shipping_notice/inventory_configuration_test.py rename to backend/app/services/shipping_notice/onhand_configuration_test.py index 348c1fd4..a409f51d 100644 --- a/backend/app/services/shipping_notice/inventory_configuration_test.py +++ b/backend/app/services/shipping_notice/onhand_configuration_test.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_configuration_test.py +services/shipping_notice/onhand_configuration_test.py 用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。 依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。 @@ -16,17 +16,18 @@ from flask import current_app from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( - ShippingInventoryConfigurationTestRun, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingInventoryValidationBatch, + FreightRpaOnhandConfigurationTestRun, + FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, + FreightRpaOnhandValidationBatch, ) -def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]: +def _payload(run: FreightRpaOnhandConfigurationTestRun) -> dict[str, Any]: """投影测试运行状态,避免暴露 RPA 文件的服务器路径。""" return { - 'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id, + 'id': run.id, 'run_no': run.run_no, 'source_id': run.source_id, 'validation_batch_id': run.validation_batch_id, 'rpa_batch_run_no': run.rpa_batch_run_no, 'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version, 'status': run.status, 'stage': run.stage, @@ -36,10 +37,10 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]: } -def _batch_payload(batch: ShippingInventoryValidationBatch) -> dict[str, Any]: +def _batch_payload(batch: FreightRpaOnhandValidationBatch) -> dict[str, Any]: """投影批量验证进度及其逐站点运行,供管理端按批次轮询。""" - runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by( - ShippingInventoryConfigurationTestRun.id.asc(), + runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by( + FreightRpaOnhandConfigurationTestRun.id.asc(), ).all() return { 'id': batch.id, 'batch_no': batch.batch_no, 'status': batch.status, @@ -57,10 +58,10 @@ def _refresh_batch(batch_id: int | None) -> None: """按逐站点终态重算批次汇总;一个站点失败绝不覆盖其他站点结果。""" if not batch_id: return - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: return - runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all() + runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all() terminal = {'completed', 'completed_empty', 'failed'} batch.total_count = len(runs) batch.success_count = sum(run.status == 'completed' for run in runs) @@ -84,58 +85,61 @@ def _refresh_batch(batch_id: int | None) -> None: batch.completed_at = datetime.utcnow() -def _validate_batch_sources(source_ids: list[int]) -> list[ShippingInventorySource]: +def _validate_batch_sources(source_ids: list[int]) -> list[FreightRpaSource]: """预检批量验证站点,强制使用已发布解析定义以明确空库存的业务语义。""" ids: list[int] = [] for source_id in source_ids: try: value = int(source_id) except (TypeError, ValueError): - raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED') + raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED') if value > 0 and value not in ids: ids.append(value) if not ids: - raise ValidationError('At least one inventory source is required', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED') - sources = ShippingInventorySource.query.filter(ShippingInventorySource.id.in_(ids)).all() + raise ValidationError('At least one inventory source is required', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED') + sources = FreightRpaSource.query.filter(FreightRpaSource.id.in_(ids)).all() by_id = {source.id: source for source in sources} if len(by_id) != len(ids): - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') ordered = [by_id[source_id] for source_id in ids] for source in ordered: if source.enabled: - raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID') + raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_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') - if source.parsing_profile is None or source.parsing_profile.status != 'published': - raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 + config = source.onhand_report_config + profile = config.parsing_profile if config is not None else None + if profile is None or profile.status != 'published': + raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') _expire_timed_out_runs(source) - active = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + active = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.source_id == source.id, + FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), ).first() if active: - raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_ACTIVE') + raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_ACTIVE') return ordered def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retry_of_batch_id: int | None = None) -> dict[str, Any]: """创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。""" sources = _validate_batch_sources(source_ids) - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f') - batch = ShippingInventoryValidationBatch( + batch = FreightRpaOnhandValidationBatch( batch_no=f'CONFIG-BATCH-{stamp}', status='queued', total_count=len(sources), created_by=actor_id, retry_of_batch_id=retry_of_batch_id, ) db.session.add(batch) db.session.flush() - grouped: dict[tuple[int, str], list[tuple[ShippingInventoryConfigurationTestRun, dict[str, Any]]]] = {} + grouped: dict[tuple[int, str], list[tuple[FreightRpaOnhandConfigurationTestRun, dict[str, Any]]]] = {} for source in sources: - run = ShippingInventoryConfigurationTestRun( + run = FreightRpaOnhandConfigurationTestRun( run_no=f'CONFIG-{source.source_code}-{stamp}-{source.id}', validation_batch_id=batch.id, - inventory_source_id=source.id, + source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version, status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id, ) @@ -143,7 +147,7 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr 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') + raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') source_payload = {**source_payload, 'validation_run_no': run.run_no} grouped.setdefault((source.rpa_profile_id, source.connector_type), []).append((run, source_payload)) db.session.commit() @@ -171,11 +175,11 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr def get_validation_batch(batch_id: int) -> dict[str, Any]: """返回批量验证当前汇总与逐站点结果,读取时同时收口超时任务。""" - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') - for run in ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all(): - source = db.session.get(ShippingInventorySource, run.inventory_source_id) + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') + for run in FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all(): + source = db.session.get(FreightRpaSource, run.source_id) if source is not None: _expire_timed_out_runs(source) _refresh_batch(batch.id) @@ -185,26 +189,26 @@ def get_validation_batch(batch_id: int) -> dict[str, Any]: def get_latest_active_validation_batch() -> dict[str, Any] | None: """恢复最近仍在执行的批量验证,供管理端刷新后继续查看真实进度。""" - batch = ShippingInventoryValidationBatch.query.filter( - ShippingInventoryValidationBatch.status.in_(['queued', 'running']), - ).order_by(ShippingInventoryValidationBatch.id.desc()).first() + batch = FreightRpaOnhandValidationBatch.query.filter( + FreightRpaOnhandValidationBatch.status.in_(['queued', 'running']), + ).order_by(FreightRpaOnhandValidationBatch.id.desc()).first() return get_validation_batch(batch.id) if batch is not None else None def retry_failed_validation_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]: """仅重新投递失败或配置已变更的站点,已成功及空库存站点不重复执行。""" - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') - failed_ids = [run.inventory_source_id for run in ShippingInventoryConfigurationTestRun.query.filter_by( + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') + failed_ids = [run.source_id for run in FreightRpaOnhandConfigurationTestRun.query.filter_by( validation_batch_id=batch.id, status='failed', ).all()] if not failed_ids: - raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NO_FAILURE') + raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.ONHAND_VALIDATION_BATCH_NO_FAILURE') return start_batch_test_export(failed_ids, actor_id=actor_id, retry_of_batch_id=batch.id) -def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool: +def _matches_current_configuration(run: FreightRpaOnhandConfigurationTestRun, source: FreightRpaSource) -> bool: """判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。""" return bool( source.rpa_profile @@ -213,23 +217,23 @@ def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, s ) -def _expire_timed_out_runs(source: ShippingInventorySource) -> None: +def _expire_timed_out_runs(source: FreightRpaSource) -> None: """按批量队列长度延长等待窗口,避免串行站点被单站超时误判。 同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站 等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。 """ timeout = max(1, int(current_app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS'])) - runs = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + runs = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.source_id == source.id, + FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), ).all() for run in runs: multiplier = 1 if run.validation_batch_id: - same_worker_queue = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.validation_batch_id == run.validation_batch_id, - ShippingInventoryConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no, + same_worker_queue = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.validation_batch_id == run.validation_batch_id, + FreightRpaOnhandConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no, ).count() multiplier = max(1, same_worker_queue) deadline = datetime.utcnow() - timedelta(seconds=timeout * multiplier) @@ -243,43 +247,43 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None: def get_latest_test_run(source_id: int) -> dict[str, Any] | None: """返回站点当前配置对应的最近测试运行,供管理端刷新或重开抽屉后恢复真实状态。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') _expire_timed_out_runs(source) db.session.commit() - run = ShippingInventoryConfigurationTestRun.query.filter_by( - inventory_source_id=source.id, + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( + source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version if source.rpa_profile else -1, - ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + ).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first() return _payload(run) if run else None def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]: """为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') if source.enabled: - raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID') + raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_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') _expire_timed_out_runs(source) - active = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.source_config_version == source.config_version, - ShippingInventoryConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version, - ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), - ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + active = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.source_id == source.id, + FreightRpaOnhandConfigurationTestRun.source_config_version == source.config_version, + FreightRpaOnhandConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version, + FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + ).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first() if active: return _payload(active) from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_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, + run = FreightRpaOnhandConfigurationTestRun( + run_no=run_no, source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version, status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id, ) @@ -287,7 +291,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any] 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') + raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_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, @@ -297,7 +301,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any] raise if not trigger: db.session.rollback() - raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE') + raise ConflictError('RPA Worker is not ready', code='SHIPPING.ONHAND_CONFIGURATION_TEST_UNAVAILABLE') run.result_json = {'trigger_written': True} db.session.commit() return _payload(run) @@ -305,12 +309,12 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any] 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(), + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( + 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') - source = db.session.get(ShippingInventorySource, source_id) + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND') + source = db.session.get(FreightRpaSource, source_id) if source is not None: _expire_timed_out_runs(source) db.session.commit() @@ -320,12 +324,12 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]: 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() + run = FreightRpaOnhandConfigurationTestRun.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') + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND') if run.status in {'completed', 'completed_empty', 'failed'}: return _payload(run) - source = db.session.get(ShippingInventorySource, run.inventory_source_id) + source = db.session.get(FreightRpaSource, run.source_id) if source is None or not _matches_current_configuration(run, source): run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow() run.result_json = {**(run.result_json or {}), 'stale_configuration': True} @@ -335,7 +339,10 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: status = str(payload.get('status') or 'success').lower() if status == 'empty': # 空库存是查询业务结果,不代表登录、报表路径或 RPA 执行失败。 - if source.parsing_profile is None or source.parsing_profile.status != 'published': + # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 + config = source.onhand_report_config + profile = config.parsing_profile if config is not None else None + if profile is None or profile.status != 'published': run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出无库存数据,且尚未绑定已发布库存解析方案'; run.completed_at = datetime.utcnow() else: run.status = 'completed_empty'; run.stage = 'empty_data_pending_validation' @@ -343,8 +350,8 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: 'export_result': 'empty', 'structure_validation': 'not_observed', 'data_validation': 'pending_first_non_empty_export', 'message': str(payload.get('message') or '库存查询成功但当前无库存数据')[:500], - 'confirmed_profile_id': source.parsing_profile_id, - 'confirmed_profile_checksum': source.parsing_profile.checksum, + 'confirmed_profile_id': profile.id, + 'confirmed_profile_checksum': profile.checksum, } run.completed_at = datetime.utcnow() db.session.commit() @@ -370,12 +377,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: 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, serialize_analysis - from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix - from app.models import ShippingInventoryStructureAnalysis + from app.services.shipping_notice.onhand_structure_analysis import _analyse_path, serialize_analysis + from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix + from app.models import FreightRpaOnhandStructureAnalysis import hashlib - 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 + from app.services.shipping_notice.onhand_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush() suffix = resolve_inventory_upload_suffix(path.name) @@ -384,7 +391,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: # The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy. structure, suggested, summary, warnings = _analyse_path(path, 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( + analysis = FreightRpaOnhandStructureAnalysis( source_kind='configuration_test', source_file_name=path.name, storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=run.created_by, @@ -392,18 +399,22 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: ) 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}) + # s18 起当前绑定取自 onhand_report_config 配置行;配置行缺失即无当前方案可比。 + config = source.onhand_report_config + current_profile_id = config.parsing_profile_id if config is not None else None current_profile_candidate = next(( candidate for candidate in (analysis.match_result_json.get('candidates') or []) - if int(candidate.get('profile_id') or 0) == int(source.parsing_profile_id or 0) + if int(candidate.get('profile_id') or 0) == int(current_profile_id or 0) ), None) run.analysis_id = analysis.id; run.status = 'completed' if current_profile_candidate is not None: # 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。 + current_profile = config.parsing_profile if config is not None else None run.stage = 'current_profile_verified' run.result_json = { 'analysis': serialize_analysis(analysis), - 'confirmed_profile_id': source.parsing_profile_id, - 'confirmed_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None, + 'confirmed_profile_id': current_profile_id, + 'confirmed_profile_checksum': current_profile.checksum if current_profile is not None else None, 'current_profile_verified': True, 'profile_match_level': current_profile_candidate.get('level'), } @@ -421,12 +432,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]: """接收批量 Worker 回调并逐项回写;未知运行标识只忽略,不影响同批其他站点。""" batch_id = int(payload.get('validation_batch_id') or 0) - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') results = payload.get('results') or [] if not isinstance(results, list): - raise ValidationError('Batch results must be a list', code='SHIPPING.INVENTORY_VALIDATION_BATCH_INVALID') + raise ValidationError('Batch results must be a list', code='SHIPPING.ONHAND_VALIDATION_BATCH_INVALID') updated: list[dict[str, Any]] = [] ignored = 0 for item in results: @@ -434,7 +445,7 @@ def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]: ignored += 1 continue run_no = str(item.get('validation_run_no') or '').strip() - run = ShippingInventoryConfigurationTestRun.query.filter_by( + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( run_no=run_no, validation_batch_id=batch.id, ).first() if run is None: @@ -459,22 +470,22 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]: batch_id = int(payload.get('validation_batch_id') or 0) run_no = str(payload.get('validation_run_no') or '').strip() if not batch_id or not run_no: - raise ValidationError('Batch id and validation run number are required', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID') - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + raise ValidationError('Batch id and validation run number are required', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID') + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') - run = ShippingInventoryConfigurationTestRun.query.filter_by( + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( run_no=run_no, validation_batch_id=batch.id, ).first() if run is None: - raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND') if run.status in {'completed', 'completed_empty', 'failed'}: return _payload(run) # 仅接受 Worker 领取后的执行阶段,防止外部回调任意覆盖运行状态。 stage = str(payload.get('stage') or 'rpa_exporting').strip().lower() if stage not in {'rpa_exporting'}: - raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID') + raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID') run.status = 'processing' run.stage = stage run.result_json = {**(run.result_json or {}), 'worker_claimed_at': datetime.utcnow().isoformat()} @@ -485,28 +496,38 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]: 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() + run = FreightRpaOnhandConfigurationTestRun.query.filter_by(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) + raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_READY') + source = db.session.get(FreightRpaSource, source_id) + profile = db.session.get(FreightRpaParsingProfile, 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') + raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') if ( source.enabled or source.config_version != run.source_config_version or source.rpa_profile is None or source.rpa_profile.config_version != run.rpa_profile_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 + raise ConflictError('Inventory Source configuration changed', code='SHIPPING.ONHAND_CONFIGURATION_TEST_STALE') + from app.services.shipping_notice.onhand_structure_analysis import adopt_published_profile adopt_published_profile(run.analysis_id, profile_id) - source.parsing_profile_id = profile.id + # s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键; + # 与 shipping_onhand_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。 + config = source.onhand_report_config + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.parsing_profile_id = profile.id + config.updated_by = actor_id source.updated_by = actor_id source.config_version += 1 run.source_config_version = source.config_version run.rpa_profile_config_version = source.rpa_profile.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} + return {'test_run': _payload(run), 'parsing_profile_id': config.parsing_profile_id} diff --git a/backend/app/services/shipping_notice/inventory_external_mapping.py b/backend/app/services/shipping_notice/onhand_external_mapping.py similarity index 71% rename from backend/app/services/shipping_notice/inventory_external_mapping.py rename to backend/app/services/shipping_notice/onhand_external_mapping.py index 9e0ef723..2836c9b1 100644 --- a/backend/app/services/shipping_notice/inventory_external_mapping.py +++ b/backend/app/services/shipping_notice/onhand_external_mapping.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_external_mapping.py +services/shipping_notice/onhand_external_mapping.py 用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。 -依赖:ShippingInventoryExternalMapping、ShippingInventorySource。 +依赖:FreightRpaOnhandExternalMapping、FreightRpaSource。 逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。 """ @@ -10,7 +10,7 @@ from __future__ import annotations from typing import Any -from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None: @@ -19,12 +19,12 @@ def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: warehouse = str(freight_warehouse_id or '').strip().upper() if not code: return None - source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first() + source = FreightRpaSource.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) + query = FreightRpaOnhandExternalMapping.query.filter_by(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() + mapping = mapping or query.filter(FreightRpaOnhandExternalMapping.freight_warehouse_id.is_(None)).first() if mapping is None: return None return { diff --git a/backend/app/services/shipping_notice/inventory_field_catalog.py b/backend/app/services/shipping_notice/onhand_field_catalog.py similarity index 77% rename from backend/app/services/shipping_notice/inventory_field_catalog.py rename to backend/app/services/shipping_notice/onhand_field_catalog.py index 08312c6a..f81baecc 100644 --- a/backend/app/services/shipping_notice/inventory_field_catalog.py +++ b/backend/app/services/shipping_notice/onhand_field_catalog.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_field_catalog.py +services/shipping_notice/onhand_field_catalog.py 用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。 -依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。 +依赖:FreightRpaOnhandField、统一业务异常和 SQLAlchemy 事务。 逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。 """ @@ -14,14 +14,14 @@ from typing import Any from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db -from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile +from app.models import ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaParsingProfile ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'} ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'} -def _payload(item: ShippingInventoryField) -> dict[str, Any]: +def _payload(item: FreightRpaOnhandField) -> dict[str, Any]: """输出业务字段目录记录,不向管理端暴露内部字段编码。""" return { 'id': item.id, @@ -38,15 +38,15 @@ def _payload(item: ShippingInventoryField) -> dict[str, Any]: def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]: """按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。""" - query = ShippingInventoryField.query + query = FreightRpaOnhandField.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, + FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id, ).all()] -def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]: +def _normalized_payload(data: dict[str, Any], *, existing: FreightRpaOnhandField | None = None) -> dict[str, Any]: """校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。""" display_name = str(data.get('display_name') or '').strip() description = str(data.get('description') or '').strip() or None @@ -55,11 +55,11 @@ def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryFiel 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 + raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_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') + raise ValidationError('Inventory field data is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') if sort_order < 0 or sort_order > 9999: - raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') + raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') return { 'display_name': display_name, 'description': description, @@ -78,7 +78,7 @@ def _field_code(display_name: str) -> str: stem = stem[:52] code = stem sequence = 2 - while ShippingInventoryField.query.filter_by(field_code=code).first() is not None: + while FreightRpaOnhandField.query.filter_by(field_code=code).first() is not None: suffix = f'_{sequence}' code = f'{stem[:64 - len(suffix)]}{suffix}' sequence += 1 @@ -88,9 +88,9 @@ def _field_code(display_name: str) -> str: 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( + if FreightRpaOnhandField.query.filter_by(display_name=values['display_name']).first() is not None: + raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT') + item = FreightRpaOnhandField( field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id, **values, ) @@ -101,24 +101,24 @@ def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。""" - item = db.session.get(ShippingInventoryField, field_id) + item = db.session.get(FreightRpaOnhandField, field_id) if item is None: - raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND') if item.status != 'active': - raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE') + raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.ONHAND_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}, + code='SHIPPING.ONHAND_FIELD_IMMUTABLE', details={'references': references}, ) - duplicate = ShippingInventoryField.query.filter( - ShippingInventoryField.display_name == values['display_name'], - ShippingInventoryField.id != item.id, + duplicate = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.display_name == values['display_name'], + FreightRpaOnhandField.id != item.id, ).first() if duplicate is not None: - raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT') + raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT') for key, value in values.items(): setattr(item, key, value) item.updated_by = actor_id @@ -128,14 +128,14 @@ def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) - def delete_field(field_id: int) -> dict[str, Any]: """物理删除从未被配置引用的用户字段。""" - item = db.session.get(ShippingInventoryField, field_id) + item = db.session.get(FreightRpaOnhandField, field_id) if item is None: - raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_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}, + code='SHIPPING.ONHAND_FIELD_DELETE_BLOCKED', details={'references': references}, ) db.session.delete(item) db.session.commit() @@ -144,14 +144,14 @@ def delete_field(field_id: int) -> dict[str, Any]: def retire_field(field_id: int) -> dict[str, Any]: """退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。""" - item = db.session.get(ShippingInventoryField, field_id) + item = db.session.get(FreightRpaOnhandField, field_id) if item is None: - raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_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}, + code='SHIPPING.ONHAND_FIELD_RETIRE_BLOCKED', details={'references': references}, ) item.status = 'retired' db.session.commit() @@ -163,8 +163,8 @@ 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']), + for item in FreightRpaParsingProfile.query.filter( + FreightRpaParsingProfile.status.in_(['draft', 'published']), ).all() if reference in { str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys() diff --git a/backend/app/services/shipping_notice/inventory_file_identity.py b/backend/app/services/shipping_notice/onhand_file_identity.py similarity index 97% rename from backend/app/services/shipping_notice/inventory_file_identity.py rename to backend/app/services/shipping_notice/onhand_file_identity.py index 95317804..2ada90e3 100644 --- a/backend/app/services/shipping_notice/inventory_file_identity.py +++ b/backend/app/services/shipping_notice/onhand_file_identity.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_file_identity.py +services/shipping_notice/onhand_file_identity.py 用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。 依赖:openpyxl、xlrd、csv、app.core.errors.AppError。 @@ -301,7 +301,7 @@ def assert_inventory_excel_warehouse_identity( expected = str(expected_warehouse_id or "").strip().upper() if not expected: raise AppError( - code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + code="SHIPPING.ONHAND_IDENTITY_MISMATCH", message="预期库位为空,无法校验库存文件内容", http_status=409, details={"operation": operation}, @@ -310,7 +310,7 @@ def assert_inventory_excel_warehouse_identity( suffix = path.suffix.lower() if suffix not in {".xls", ".xlsx", ".csv"}: raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED", message="库存源身份校验仅支持 .xls / .xlsx / .csv", http_status=409, details={"operation": operation, "file_suffix": suffix}, @@ -319,14 +319,14 @@ def assert_inventory_excel_warehouse_identity( found = extract_warehouse_ids_from_inventory_excel(path) if not found: raise AppError( - code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING", + code="SHIPPING.ONHAND_FILE_WAREHOUSE_MISSING", message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库", http_status=409, details={"operation": operation, "expected_warehouse_id": expected}, ) if len(found) > 1: raise AppError( - code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED", + code="SHIPPING.ONHAND_FILE_WAREHOUSE_MIXED", message="库存文件包含多个 Warehouse ID,已拒绝入库", http_status=409, details={ @@ -338,7 +338,7 @@ def assert_inventory_excel_warehouse_identity( actual = next(iter(found)) if actual != expected: raise AppError( - code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + code="SHIPPING.ONHAND_IDENTITY_MISMATCH", message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库", http_status=409, details={ diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/onhand_file_store.py similarity index 85% rename from backend/app/services/shipping_notice/inventory_file_store.py rename to backend/app/services/shipping_notice/onhand_file_store.py index 45cc29ae..231a3dbd 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/onhand_file_store.py @@ -1,10 +1,11 @@ """ -services/shipping_notice/inventory_file_store.py +services/shipping_notice/onhand_file_store.py 用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影;构造下载展示名 (build_inventory_download_name:企微压缩包短名规则 + exported_at 数据截止时间点)。 -依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。 -逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT); +依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读/查询取回,禁止构造)、 + freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_snapshot、export._storage_root。 +逻辑:onhand_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT); fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution: 冻结候选读所属 OT 的 prepare 合并行(传入 Notice 时回源 order_task_id),单源读 active Link 文件; 禁止用 Notice.id 漏读 OT Link,导出数据源不得偏离行级匹配门禁命中的候选事实。 @@ -25,24 +26,25 @@ from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError from app.models import ( - ShippingInventoryFile, + FreightRpaOnhandReportFile, ShippingNotice, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingOrderSnapshot, ShippingTaskEvent, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ) from app.services.shipping_notice.tool_common import task_event_task_id +from app.services.freight_rpa.onhand.report_store import insert_onhand_report, update_onhand_report from app.services.shipping_notice.export import _storage_root -from app.services.shipping_notice.inventory_snapshot import ( +from app.services.shipping_notice.onhand_snapshot import ( parse_inventory_excel_with_meta, read_inventory_schema_preview, ) -from app.services.shipping_notice.inventory_source_gate import ( +from app.services.shipping_notice.onhand_source_gate import ( is_inventory_source_stable, task_inventory_identity, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) @@ -79,7 +81,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str: name = str(filename or "").strip().lower() if not name or "." not in name: raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED", message="库存上传缺少可识别的文件后缀", http_status=409, ) @@ -90,7 +92,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str: if name.endswith(".xls"): return ".xls" raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED", message="库存上传仅支持 .xls / .xlsx / .csv", http_status=409, ) @@ -145,11 +147,11 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None: pass -def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None: +def active_inventory_file_for_task(task: ShippingNotice) -> FreightRpaOnhandReportFile | None: """ 读取任务当前 active link 指向的库存快照。 - 核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入 + 核心逻辑:``ShippingTaskOnhandLink.task_id`` 挂在正式 OT 上;传入 ``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。 Args: @@ -163,12 +165,12 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil if task_id is None: return None link = ( - ShippingTaskInventoryLink.query.filter_by( + ShippingTaskOnhandLink.query.filter_by( task_id=int(task_id), is_active=True, invalidated_at=None, ) - .order_by(ShippingTaskInventoryLink.id.desc()) + .order_by(ShippingTaskOnhandLink.id.desc()) .first() ) return link.inventory_file if link else None @@ -208,7 +210,7 @@ _DOWNLOAD_NAME_SANITIZE_RE = re.compile(r'[^\w.\-]+') def build_inventory_download_name( - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, source_file_name: str | None, path: Path | None = None, @@ -235,7 +237,7 @@ def build_inventory_download_name( base = str(source_file_name or '').strip() if not base: suffix = Path(path or base).suffix or '.xlsx' - return f'{inv_file.inventory_file_no}{suffix.lower()}' + return f'{inv_file.onhand_file_no}{suffix.lower()}' if _DOWNLOAD_CANONICAL_RE.match(base): return base seq_match = _DOWNLOAD_SEQ_PREFIX_RE.match(base) @@ -274,10 +276,10 @@ def build_inventory_download_name( return "_".join(tokens) + suffix.lower() -def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: +def read_inventory_file_lines(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: """读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。""" cached_rows = [ - row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict) + row for row in (inv_file.onhand_lines_json or []) if isinstance(row, dict) ] if cached_rows: return cached_rows, {'source': 'inventory_file_cache'} @@ -285,7 +287,7 @@ def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dic rows, column_meta = parse_inventory_snapshot_file(inv_file) rows = [row for row in rows if isinstance(row, dict)] if rows: - inv_file.inventory_lines_json = rows + inv_file.onhand_lines_json = rows inv_file.line_count = len(rows) db.session.flush() return rows, column_meta @@ -311,7 +313,7 @@ def resolve_inventory_lines_for_execution( """ 解析库存匹配与导出的统一运行输入。 - 核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源 + 核心逻辑:已冻结候选源时优先 ``prepare_candidate_onhand_lines`` 合并各源 ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File; 否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。 @@ -326,19 +328,19 @@ def resolve_inventory_lines_for_execution( # Notice 主键 ≠ OT 且不带候选集指针;冻结候选事实统一回源所属 OT 读取, # 防止导出路径把多源任务退化成单源 Link,出现「行匹配过门禁但生成 Excel 失败」。 from app.models import ShippingOrderTask - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, + from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) - from app.services.shipping_notice.stp_line_inventory_match import ( - prepare_candidate_inventory_lines, + from app.services.shipping_notice.stp_line_onhand_match import ( + prepare_candidate_onhand_lines, ) owner_task = task order_task_id = getattr(task, 'order_task_id', None) if order_task_id: owner_task = db.session.get(ShippingOrderTask, int(order_task_id)) or task - if len(task_frozen_inventory_source_codes(owner_task)) >= 1: - prep = prepare_candidate_inventory_lines(owner_task) + if len(task_frozen_onhand_source_codes(owner_task)) >= 1: + prep = prepare_candidate_onhand_lines(owner_task) if prep.get('status') == 'ready': rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)] if rows: @@ -373,12 +375,12 @@ def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool: ) -def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]: +def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineOnhandMatch]: """读取 OT 当前有效的行级库存匹配事实。""" task_id = getattr(task, 'id', None) if task_id is None: return [] - return ShippingNoticeLineInventoryMatch.query.filter_by( + return ShippingNoticeLineOnhandMatch.query.filter_by( task_id=int(task_id), is_current=True, ).all() @@ -428,7 +430,7 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> ) -def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile: +def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> FreightRpaOnhandReportFile: """ 保存库存 Excel 并创建任务级库存快照。 @@ -438,7 +440,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi """ if not is_inventory_source_stable(task): raise AppError( - code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED", + code="SHIPPING.ONHAND_SOURCE_GATE_BLOCKED", message="库存源尚未稳定,拒绝保存库存上传文件", http_status=409, ) @@ -454,7 +456,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi 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 + from app.services.shipping_notice.onhand_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( @@ -475,7 +477,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi }) if not inventory_lines: raise AppError( - code='SHIPPING.INVENTORY_FILE_EMPTY', + code='SHIPPING.ONHAND_FILE_EMPTY', message='库存文件没有可用于匹配的有效库存数据', http_status=409, ) @@ -502,8 +504,10 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi pass raise - inv_file = ShippingInventoryFile( - inventory_file_no=inventory_file_no, + # [STEP] 阶段 B Task 5:快照行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit), + # 本模块拿回 file_id 后按主键取回 ORM 对象,身份校验失败回滚删除仍按 ORM 行操作。 + saved_file_id = insert_onhand_report( + onhand_file_no=inventory_file_no, user_id=task.user_id, source_file_name=str(upload.filename or "").strip() or path.name, storage_path=str(path), @@ -511,7 +515,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi schema_preview_json=preview, share_mode="task_only", line_count=len(inventory_lines), - inventory_lines_json=inventory_lines, + onhand_lines_json=inventory_lines, field_mapping_json=dict(structure_check['field_mapping']), mapping_source='parsing_profile', mapping_confirmed=True, @@ -526,8 +530,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi snapshot_status="ready", exported_at=datetime.utcnow(), ) - db.session.add(inv_file) - db.session.flush() + inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id) candidates = [task] linked_tasks = [ @@ -535,9 +538,9 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi for item in candidates if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item) ] - from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + from app.services.shipping_notice.onhand_snapshot_store import link_snapshot_to_task - created_links: list[ShippingTaskInventoryLink] = [] + created_links: list[ShippingTaskOnhandLink] = [] for item in linked_tasks: link = link_snapshot_to_task( item, @@ -561,13 +564,14 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi "failed to delete inventory upload after link failure %s", path ) raise AppError( - code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + code="SHIPPING.ONHAND_IDENTITY_MISMATCH", message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定", http_status=409, ) created_links.append(link) if len(linked_tasks) > 1: - inv_file.share_mode = "batch_same_identity" + # [STEP] 阶段 B Task 5:多票同身份共用时改写 share_mode 也经 report_store 更新(同一 ORM 对象,行为不变)。 + update_onhand_report(inv_file.id, share_mode="batch_same_identity") return inv_file @@ -576,13 +580,13 @@ def save_task_inventory_file_from_local_path( source_path: str | Path, *, source_file_name: str | None = None, -) -> ShippingInventoryFile: +) -> FreightRpaOnhandReportFile: """ 将本地已有库存文件纳入统一库存快照模型,并为当前任务建立 active link。 - 【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 ShippingInventoryFile 记录时调用。 + 【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 FreightRpaOnhandReportFile 记录时调用。 核心逻辑:复制本地文件到 inventory_file_no 对应标准目录,生成 schema preview, - 再创建 task_only 的 ShippingInventoryFile 与 active ShippingTaskInventoryLink。 + 再创建 task_only 的 FreightRpaOnhandReportFile 与 active ShippingTaskOnhandLink。 Args: task: 当前发货任务,用于绑定 user/batch 与 active link。 @@ -590,7 +594,7 @@ def save_task_inventory_file_from_local_path( source_file_name: 展示给用户/审计的原始文件名;为空时回退源文件名。 Returns: - ShippingInventoryFile: 已持久化的库存快照对象。 + FreightRpaOnhandReportFile: 已持久化的库存快照对象。 Raises: FileNotFoundError: 源文件不存在时抛出。 @@ -607,8 +611,10 @@ def save_task_inventory_file_from_local_path( preview = read_inventory_schema_preview(path) preview["upload_filename"] = str(source_file_name or source.name or path.name).strip() or path.name - inv_file = ShippingInventoryFile( - inventory_file_no=inventory_file_no, + # [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit), + # 拿回 file_id 后取回 ORM 对象并交由 replace_task_inventory_link 建立 active link(link 表留在发货域)。 + saved_file_id = insert_onhand_report( + onhand_file_no=inventory_file_no, user_id=task.user_id, source_file_name=str(source_file_name or source.name or path.name).strip() or path.name, storage_path=str(path), @@ -618,27 +624,26 @@ def save_task_inventory_file_from_local_path( line_count=0, source_query_json={'trigger_type': 'manual_upload'}, ) - db.session.add(inv_file) - db.session.flush() + inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id) replace_task_inventory_link(task, inv_file, role="owner") return inv_file def replace_task_inventory_link( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, role: str = "member", -) -> ShippingTaskInventoryLink: +) -> ShippingTaskOnhandLink: """替换任务 active 库存 link,保留历史 link 审计。""" if task.id is None: db.session.flush() - existing = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all() + existing = ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True).all() for link in existing: link.is_active = False - new_link = ShippingTaskInventoryLink( + new_link = ShippingTaskOnhandLink( task_id=task.id, - inventory_file_id=inv_file.id, + onhand_file_id=inv_file.id, link_role=role, access_mode="readonly", linked_by_user_id=inv_file.user_id, @@ -649,7 +654,7 @@ def replace_task_inventory_link( task_id=task_event_task_id(task), event_type="inventory_file_linked", detail_json={ - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "role": role, "share_mode": inv_file.share_mode, }, @@ -667,14 +672,14 @@ def read_linked_inventory_schema_preview(task: ShippingNotice) -> dict[str, Any] return dict(inv_file.schema_preview_json) path = Path(inv_file.storage_path) if not path.is_file(): - raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}") + raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}") preview = read_inventory_schema_preview(path) preview["upload_filename"] = inv_file.source_file_name or path.name inv_file.schema_preview_json = preview return preview -def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: +def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: """以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。 仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败, @@ -682,18 +687,18 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list """ path = Path(inv_file.storage_path) if not path.is_file(): - raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}") - from app.models import ShippingInventorySource - from app.services.shipping_notice.inventory_parsing_profile import require_source_profile + raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}") + from app.models import FreightRpaSource + from app.services.shipping_notice.onhand_parsing_profile import require_source_profile from app.core.errors import ValidationError - source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first() + source = FreightRpaSource.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', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) definition = dict(profile.definition_json or {}) return parse_inventory_excel_with_meta( @@ -706,7 +711,7 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list def apply_inventory_parse_result_to_linked_tasks( - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, inventory_lines: list[dict[str, Any]], *, field_mapping: dict[str, str] | None = None, @@ -714,7 +719,7 @@ def apply_inventory_parse_result_to_linked_tasks( mapping_confirmed: bool = False, ) -> list[ShippingNotice]: """把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。""" - inv_file.inventory_lines_json = inventory_lines + inv_file.onhand_lines_json = inventory_lines inv_file.line_count = len(inventory_lines) if field_mapping: inv_file.field_mapping_json = field_mapping @@ -732,7 +737,7 @@ def apply_inventory_parse_result_to_linked_tasks( return linked_tasks -def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -> list[str]: +def linked_task_nos_for_inventory_file(inv_file: FreightRpaOnhandReportFile | None) -> list[str]: """返回库存快照当前 active link 关联的任务编号列表。""" if not inv_file: return [] @@ -743,7 +748,7 @@ def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) - return sorted(set(task_nos)) -def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> bool: +def start_inventory_file_linked_tasks(inv_file: FreightRpaOnhandReportFile | None) -> bool: """ 按库存快照关联任务批量入队续跑。 @@ -775,7 +780,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task): set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message="本批库存快照已确认,等待匹配库存", diff --git a/backend/app/services/shipping_notice/inventory_mapping.py b/backend/app/services/shipping_notice/onhand_mapping.py similarity index 92% rename from backend/app/services/shipping_notice/inventory_mapping.py rename to backend/app/services/shipping_notice/onhand_mapping.py index f124f1e4..365df70a 100644 --- a/backend/app/services/shipping_notice/inventory_mapping.py +++ b/backend/app/services/shipping_notice/onhand_mapping.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_mapping.py +services/shipping_notice/onhand_mapping.py 用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。 -依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。 +依赖:FreightRpaOnhandField、match_rule_desc、标准 `json`/`typing` 能力。 逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。 """ @@ -11,7 +11,7 @@ from __future__ import annotations import re from typing import Any -from app.models import ShippingInventoryField +from app.models import FreightRpaOnhandField from app.services.shipping_notice.match_rule_desc import resolve_match_rule @@ -19,7 +19,7 @@ LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "ava LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty") -def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]: +def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]: """读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。""" try: ids = {int(key) for key in field_mapping} @@ -27,8 +27,8 @@ def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventory return {} if not ids or any(item <= 0 for item in ids): return {} - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active', + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active', ).all() return {str(row.id): row for row in rows} @@ -43,7 +43,7 @@ def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool: return False -def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]: +def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, FreightRpaOnhandField]]: """验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。""" catalog = _catalog_by_id(field_mapping) if _uses_catalog_ids(field_mapping): @@ -56,8 +56,8 @@ def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str] def usage_field_ids() -> dict[str, set[str]]: """按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。""" - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.status == 'active', + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.status == 'active', ).all() result: dict[str, set[str]] = {} for row in rows: @@ -99,7 +99,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None: 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 + from app.services.shipping_notice.onhand_snapshot import _column_map, _map_header col_map = _column_map() norm_headers = [str(h or "").strip() for h in headers] @@ -165,9 +165,9 @@ def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> di """按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。""" if not as_catalog: return _suggest_runtime_field_mapping(headers) - from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header + from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header - rows = ShippingInventoryField.query.filter_by(status='active').all() + rows = FreightRpaOnhandField.query.filter_by(status='active').all() header_by_name: dict[str, list[str]] = {} for header in headers: normalized = normalise_header(header) diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/onhand_mapping_workflow.py similarity index 90% rename from backend/app/services/shipping_notice/inventory_mapping_workflow.py rename to backend/app/services/shipping_notice/onhand_mapping_workflow.py index 29eb6c3f..fd7c6043 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/onhand_mapping_workflow.py @@ -1,10 +1,10 @@ """ -services/shipping_notice/inventory_mapping_workflow.py +services/shipping_notice/onhand_mapping_workflow.py 用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。 -依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。 +依赖:onhand_file_store、onhand_snapshot、query_service、state_machine、tool_common。 逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析; - 快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。 + 快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 onhand_lines_json。 """ from __future__ import annotations @@ -13,13 +13,13 @@ from typing import Any from app import db from app.models import ShippingNotice -from app.services.shipping_notice.inventory_file_store import ( +from app.services.shipping_notice.onhand_file_store import ( _can_relink_inventory, active_inventory_file_for_task, apply_inventory_parse_result_to_linked_tasks, start_inventory_file_linked_tasks, ) -from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview +from app.services.shipping_notice.onhand_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.order_field_purposes import task_line_purpose_values @@ -44,7 +44,7 @@ def inventory_loaded_response( 将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。 核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库) - 写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态, + 写回 ``onhand_lines_json``;``False``(快照复用)只收集关联任务并推进状态, 禁止覆盖共享 File 上已有行缓存。 Args: @@ -57,7 +57,7 @@ def inventory_loaded_response( field_mapping: published Profile 的字段映射快照。 mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。 commit: False 时仅 flush,供批量回调维持外层事务边界。 - persist_lines: False 时不写 File.inventory_lines_json(复用路径)。 + persist_lines: False 时不写 File.onhand_lines_json(复用路径)。 Returns: Tool 标准响应;成功后任务可直接进入库存匹配。 @@ -101,7 +101,7 @@ def inventory_loaded_response( ) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="completed", message=f"已载入库存 {len(inventory_lines)} 行", @@ -138,7 +138,7 @@ def inventory_loaded_response( "warnings": warnings or [], "source": source, "column_meta": column_meta, - "inventory_file_no": inv_file.inventory_file_no if inv_file else None, + "inventory_file_no": inv_file.onhand_file_no if inv_file else None, "linked_task_nos": [item.task_no for item in linked_tasks], "persist_lines": bool(persist_lines), }, diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/shipping_notice/onhand_parsing_profile.py similarity index 77% rename from backend/app/services/shipping_notice/inventory_parsing_profile.py rename to backend/app/services/shipping_notice/onhand_parsing_profile.py index bbe30e4b..a800e462 100644 --- a/backend/app/services/shipping_notice/inventory_parsing_profile.py +++ b/backend/app/services/shipping_notice/onhand_parsing_profile.py @@ -1,8 +1,8 @@ """ -backend/app/services/shipping_notice/inventory_parsing_profile.py +backend/app/services/shipping_notice/onhand_parsing_profile.py 用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。 -依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。 +依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig(s18 起站点绑定归配置行)、FreightRpaInboundReportConfig、ShippingOrderField、onhand_mapping。 逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。 """ @@ -18,41 +18,41 @@ from sqlalchemy import func from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( - ShippingInventoryField, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingInventoryStructureAnalysis, + FreightRpaOnhandField, + FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, + FreightRpaOnhandStructureAnalysis, ShippingOrderField, - ShippingReceiptReportConfig, + FreightRpaInboundReportConfig, ) -def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]: +def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]: """解析字段目录 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 + raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc if field_id <= 0: - raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') field_ids.append(field_id) - rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else [] + rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.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') + raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') return fields -def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]: +def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> 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', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) return match_ids | quantity_ids @@ -69,13 +69,13 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]: if unknown: raise ValidationError( f'Movement parsing profile references unknown field: {sorted(unknown)}', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes} if missing: raise ValidationError( f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) return mapped_codes @@ -89,15 +89,15 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any] 'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 """ if not isinstance(raw, dict): - raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_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') + raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_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') + raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') 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') + raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if purpose == 'inbound': _required_movement_field_ids(raw) @@ -112,7 +112,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any] _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') + raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') normalized_keys: list[dict[str, str]] = [] seen_order_fields: set[str] = set() seen_inventory_fields: set[str] = set() @@ -124,9 +124,9 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any] 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') + raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_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') + raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_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}) @@ -143,20 +143,20 @@ def _require_sample_evidence( definition: dict[str, Any], *, file_format: str, -) -> ShippingInventoryStructureAnalysis: +) -> FreightRpaOnhandStructureAnalysis: """校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。""" try: analysis_id = int(sample_analysis_id) except (TypeError, ValueError) as exc: raise ValidationError( 'Parsing profile requires sample analysis evidence', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED', ) from exc - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format: raise ValidationError( 'Parsing profile sample analysis evidence is unavailable', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED', ) structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else [] @@ -166,13 +166,13 @@ def _require_sample_evidence( if not isinstance(selected, dict): raise ValidationError( 'Parsing profile worksheet or header row is not present in sample evidence', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID', ) headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()} if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()): raise ValidationError( 'Parsing profile mapping is not present in sample evidence', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID', ) duplicates = { str(column.get('header') or '').strip() @@ -181,12 +181,12 @@ def _require_sample_evidence( if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()): raise ValidationError( 'Parsing profile mapping uses duplicate sample headers', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID', ) return analysis -def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: +def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]: """序列化解析 Profile 管理 DTO。""" sample_analysis = profile.sample_analysis return { @@ -212,49 +212,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: def list_profiles() -> list[dict[str, Any]]: """列出全部解析 Profile 版本。""" - return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by( - ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(), + return [payload(item) for item in FreightRpaParsingProfile.query.order_by( + FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.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 + profile = db.session.get(FreightRpaParsingProfile, 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') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_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') + raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_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') + raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_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') + raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_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) + next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1 + profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id) db.session.add(profile) purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower() if purpose not in {'onhand', 'inbound', 'outbound'}: - raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if profile_id and purpose != profile.purpose: raise ValidationError( 'Draft parsing profile purpose is immutable', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) profile.purpose = purpose profile.display_name = str(data.get('display_name') or code).strip() requested_file_format = str(data.get('file_format') or 'xlsx').lower() if requested_file_format not in {'xls', 'xlsx', 'csv'}: - raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if profile_id and requested_file_format != profile.file_format: raise ValidationError( 'Draft parsing profile file format is immutable', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) profile.file_format = requested_file_format definition = _validate_definition(data.get('definition'), purpose=purpose) 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') + raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') sample_analysis = _require_sample_evidence( data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format, ) @@ -262,7 +262,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | if not bool(data.get('confirm_sample_replacement')): raise ValidationError( 'Replacing inventory sample evidence requires confirmation', - code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED', + code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED', ) history = list(profile.sample_evidence_history_json or []) history.append({ @@ -280,11 +280,11 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: """发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'draft': - raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID') + raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID') _require_sample_evidence( profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format, ) @@ -304,7 +304,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: 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', + code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID', ) encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() profile.checksum = hashlib.sha256(encoded).hexdigest() @@ -317,17 +317,18 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: def retire(profile_id: int) -> dict[str, Any]: """退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'published': - raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID') - bound_sources = ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count() - # 收料报表配置(ShippingReceiptReportConfig)同样绑定解析 Profile:退役前必须一并核查, + raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID') + # s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。 + bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + # 收料报表配置(FreightRpaInboundReportConfig)同样绑定解析 Profile:退役前必须一并核查, # 否则入站文件解析链(inbound purpose)会静默失去规则。 - bound_receipt_configs = ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + bound_receipt_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count() if bound_sources or bound_receipt_configs: - raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED') + raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED') profile.status = 'retired' db.session.commit() return payload(profile) @@ -335,18 +336,20 @@ def retire(profile_id: int) -> dict[str, Any]: def delete_draft(profile_id: int) -> None: """删除从未发布的解析 Profile 草稿。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'draft': - raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED') + raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED') db.session.delete(profile) db.session.commit() -def require_source_profile(source: Any) -> ShippingInventoryParsingProfile: +def require_source_profile(source: Any) -> FreightRpaParsingProfile: """读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。""" - profile = getattr(source, 'parsing_profile', None) + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = getattr(source, 'onhand_report_config', None) + profile = config.parsing_profile if config is not None else None if profile is None or profile.status != 'published': - raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') return profile diff --git a/backend/app/services/shipping_notice/inventory_profile_matching.py b/backend/app/services/shipping_notice/onhand_profile_matching.py similarity index 82% rename from backend/app/services/shipping_notice/inventory_profile_matching.py rename to backend/app/services/shipping_notice/onhand_profile_matching.py index 5b25dd7f..3992705b 100644 --- a/backend/app/services/shipping_notice/inventory_profile_matching.py +++ b/backend/app/services/shipping_notice/onhand_profile_matching.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_profile_matching.py +services/shipping_notice/onhand_profile_matching.py 用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。 -依赖:ShippingInventoryParsingProfile、库存结构指纹服务。 +依赖:FreightRpaParsingProfile、库存结构指纹服务。 逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。 """ @@ -10,17 +10,17 @@ from __future__ import annotations from typing import Any -from app.models import ShippingInventoryParsingProfile -from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header +from app.models import FreightRpaParsingProfile +from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header -def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]: +def _profile_headers(profile: FreightRpaParsingProfile) -> 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]]: +def _difference(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> 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', [])] @@ -32,9 +32,9 @@ def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfi } -def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool: +def _core_mapping_matches(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> bool: """确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。""" - from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids + from app.services.shipping_notice.onhand_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', [])} @@ -53,7 +53,7 @@ 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() + profiles = FreightRpaParsingProfile.query.filter_by(status='published').all() candidates: list[dict[str, Any]] = [] for profile in profiles: level = None diff --git a/backend/app/services/shipping_notice/inventory_recovery_service.py b/backend/app/services/shipping_notice/onhand_recovery_service.py similarity index 50% rename from backend/app/services/shipping_notice/inventory_recovery_service.py rename to backend/app/services/shipping_notice/onhand_recovery_service.py index 0271b1f4..219e9ca3 100644 --- a/backend/app/services/shipping_notice/inventory_recovery_service.py +++ b/backend/app/services/shipping_notice/onhand_recovery_service.py @@ -1,9 +1,14 @@ """ -services/shipping_notice/inventory_recovery_service.py +services/shipping_notice/onhand_recovery_service.py -用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。 +用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉;阶段 B Task 7 + 修复轮新增 onhand 报表事实落地后的候选 settle(settle_preparation_source_ + from_onhand_report)与等待任务反查(waiting_preparation_source_task_ids)。 依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。 -逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。 +逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。SourceAttempt + 被 settle 后的 PreparationAttempt 聚合(含 RecoveryPlan 收口)收敛到 + _aggregate_preparation_after_source_settle——per-source RPA 回调与 onhand + 事实处理函数(handle_onhand_report)共用同一聚合出口,防两路语义漂移。 """ from __future__ import annotations @@ -13,30 +18,30 @@ from typing import Any from app import db from app.models import ( - ShippingInventoryFile, - ShippingInventoryPreparationAttempt, - ShippingInventoryPreparationSourceAttempt, + FreightRpaOnhandReportFile, + ShippingOnhandPreparationAttempt, + ShippingOnhandPreparationSourceAttempt, ShippingOrderTask, ShippingOrderCandidate, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ) -from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task -from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint -from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable -from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes -from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts +from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task +from app.services.shipping_notice.onhand_combination_fingerprint import build_inventory_combination_fingerprint +from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable +from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes +from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts def create_inventory_preparation_round( *, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None, action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None, gate_attempt_id: int | None = None, -) -> ShippingInventoryPreparationAttempt: +) -> ShippingOnhandPreparationAttempt: """创建一次任务级准备轮次;同一任务按 attempt_no 递增。""" - last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by( - ShippingInventoryPreparationAttempt.attempt_no.desc(), + last = ShippingOnhandPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by( + ShippingOnhandPreparationAttempt.attempt_no.desc(), ).first() - round_row = ShippingInventoryPreparationAttempt( + round_row = ShippingOnhandPreparationAttempt( task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id, recovery_plan_id=recovery_plan_id, attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued', @@ -53,7 +58,7 @@ def create_inventory_preparation_round( db.session.flush() codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()] if not codes: - codes = task_frozen_inventory_source_codes(task) + codes = task_frozen_onhand_source_codes(task) active_file = active_inventory_file_for_task(task) for source_code in codes: reusable, _reuse_reasons = check_inventory_snapshot_reusable( @@ -65,15 +70,15 @@ def create_inventory_preparation_round( parser_version=getattr(active_file, 'parser_version', None) if active_file else None, mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None, ) - reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable) - link = ShippingTaskInventoryLink.query.filter_by( + reusable = bool(action_code == 'retry_onhand_from_field_mapping' and reusable) + link = ShippingTaskOnhandLink.query.filter_by( task_id=int(task.id), matched_source_code=source_code, is_active=True, - ).order_by(ShippingTaskInventoryLink.id.desc()).first() - source = ShippingInventoryPreparationSourceAttempt( + ).order_by(ShippingTaskOnhandLink.id.desc()).first() + source = ShippingOnhandPreparationSourceAttempt( preparation_attempt_id=int(round_row.id), source_code=source_code, status='reusable' if reusable else 'queued', - inventory_file_id=int(active_file.id) if reusable and active_file else None, - task_inventory_link_id=int(link.id) if reusable and link else None, + onhand_file_id=int(active_file.id) if reusable and active_file else None, + task_onhand_link_id=int(link.id) if reusable and link else None, operation_id=operation_id, ) db.session.add(source) @@ -90,18 +95,18 @@ def create_inventory_preparation_round( sources=[ { 'source_code': str(item.source_code), - 'snapshot_id': item.inventory_file_id, + 'snapshot_id': item.onhand_file_id, 'snapshot_hash': ( - getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None) - if item.inventory_file_id else None + getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'file_sha256', None) + if item.onhand_file_id else None ), 'parser_version': ( - getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None) - if item.inventory_file_id else None + getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'parser_version', None) + if item.onhand_file_id else None ), 'mapping_version': ( - getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None) - if item.inventory_file_id else None + getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'mapping_version', None) + if item.onhand_file_id else None ), } for item in round_row.source_attempts @@ -114,8 +119,8 @@ def create_inventory_preparation_round( def sync_inventory_preparation_round( - *, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any, -) -> ShippingInventoryPreparationAttempt: + *, preparation_attempt: ShippingOnhandPreparationAttempt, result: Any, +) -> ShippingOnhandPreparationAttempt: """将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。""" def _read(name: str, default: Any) -> Any: return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default) @@ -151,29 +156,24 @@ def sync_inventory_preparation_round( return preparation_attempt -def sync_preparation_source_from_rpa_attempt( - *, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None, -) -> None: - """由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。 +def _aggregate_preparation_after_source_settle(preparation: ShippingOnhandPreparationAttempt) -> None: + """按 SourceAttempt 状态聚合 PreparationAttempt 终态并收口绑定的 RecoveryPlan(只 flush 不 commit)。 - SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次, - 因而不会污染当前 GateAttempt 对应的 PreparationAttempt。 + 用途:SourceAttempt 被 settle(ready/failed/waiting)后的统一聚合出口—— + per-source RPA 回调(sync_preparation_source_from_rpa_attempt)与 + onhand 报表事实处理函数(settle_preparation_source_from_onhand_report, + 阶段 B Task 7 修复轮)共用同一聚合语义,防止两条路径漂移。 + 核心逻辑:任一 failed → failed;仍有 queued/running/waiting → waiting_external; + 全部 ready/reusable/skipped → succeeded(记 completed_at);聚合到终态后 + 同步收口绑定的 RecoveryPlan(succeeded/failed + 时间戳 + 失败码), + 避免已完成的计划继续占用 active-plan 互斥位。 + Args: + preparation: SourceAttempt 已更新的准备轮次行。 + Returns: + None。只 flush——事务提交时机归属调用方。 """ - source = ShippingInventoryPreparationSourceAttempt.query.filter_by( - rpa_attempt_id=int(rpa_attempt_id), - ).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first() - if source is None: + if preparation is None: return - status = str(rpa_status or '').strip().lower() - if status in {'succeeded', 'consumed'}: - source.status = 'ready' - if inventory_file_id: - source.inventory_file_id = int(inventory_file_id) - elif status in {'failed', 'exhausted'}: - source.status = 'failed' - elif status in {'queued', 'running'}: - source.status = 'waiting' - preparation = source.preparation_attempt rows = list(getattr(preparation, 'source_attempts', []) or []) if any(row.status == 'failed' for row in rows): preparation.status = 'failed' @@ -201,4 +201,105 @@ def sync_preparation_source_from_rpa_attempt( if preparation.status == 'failed': plan.failure_code = 'inventory_preparation_failed' plan.failure_detail_json = {'message': '库存准备 RPA 回调失败'} + + +def settle_preparation_source_from_onhand_report( + *, source_code: str, onhand_file_id: int, +) -> list[ShippingOnhandPreparationAttempt]: + """onhand 报表事实落地后:把该来源等待中的 SourceAttempt settle 为 ready 并绑定文件。 + + 【AI 触发时机】:onhand 事实处理函数(shipping_notice.onhand_report_handler. + handle_onhand_report)在文件行 commit 后投递 ok=True 事实时调用——共享快照 + 模型下「该来源已有可用快照」对所有等待该来源的候选准备成立。 + + 核心逻辑:[STEP 1] 取该来源 status ∈ queued/running/waiting 且未绑定文件的 + SourceAttempt(幂等集:已 ready/已绑定的行不在集合内,重复投递零副作用、 + 绝不重复候选行);[STEP 2] 逐行 ready + 绑定 onhand_file_id; + [STEP 3] 对受影响的 PreparationAttempt 逐一聚合终态 + (_aggregate_preparation_after_source_settle,含 RecoveryPlan 收口)。 + 只 flush 不 commit——事务提交时机归属调用方(处理函数)。 + + Args: + source_code: 库存来源编码(与 SourceAttempt.source_code 精确匹配)。 + onhand_file_id: 已提交的 freight_rpa_onhand_report_files 主键。 + Returns: + 受影响(发生了 settle)的 PreparationAttempt 列表;无等待行时为空表。 + """ + waiting = ( + ShippingOnhandPreparationSourceAttempt.query + .filter( + ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(), + ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')), + ShippingOnhandPreparationSourceAttempt.onhand_file_id.is_(None), + ) + .all() + ) + affected: dict[int, ShippingOnhandPreparationAttempt] = {} + for row in waiting: + row.status = 'ready' + row.onhand_file_id = int(onhand_file_id) + preparation = row.preparation_attempt + if preparation is not None: + affected[int(preparation.id)] = preparation + for preparation in affected.values(): + _aggregate_preparation_after_source_settle(preparation) + if waiting: + db.session.flush() + return list(affected.values()) + + +def waiting_preparation_source_task_ids(*, source_code: str) -> list[int]: + """列出「仍在等待该来源库存」的准备轮次任务 ID(onhand 事实处理函数门禁重投影用)。 + + 用途:onhand 失败/空事实(无文件身份)时,处理函数只对等待该来源的任务重投影 + 履约门禁(回调失败路径的门禁更新归处理函数),不发明/改写任何候选行。 + 核心逻辑:按 source_code 取 status ∈ queued/running/waiting 的 SourceAttempt, + 经其准备轮次收集去重 task_id;只读查询。 + Args: + source_code: 库存来源编码。 + Returns: + 去重后的 ShippingOrderTask.id 列表(无等待行时为空表)。 + """ + rows = ( + ShippingOnhandPreparationSourceAttempt.query + .filter( + ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(), + ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')), + ) + .all() + ) + task_ids: list[int] = [] + for row in rows: + preparation = row.preparation_attempt + if preparation is not None and preparation.task_id and int(preparation.task_id) not in task_ids: + task_ids.append(int(preparation.task_id)) + return task_ids + + +def sync_preparation_source_from_rpa_attempt( + *, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None, +) -> None: + """由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。 + + SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次, + 因而不会污染当前 GateAttempt 对应的 PreparationAttempt。聚合语义自阶段 B + Task 7 修复轮起收敛到 _aggregate_preparation_after_source_settle(与 + settle_preparation_source_from_onhand_report 共用同一出口)。 + """ + source = ShippingOnhandPreparationSourceAttempt.query.filter_by( + rpa_attempt_id=int(rpa_attempt_id), + ).order_by(ShippingOnhandPreparationSourceAttempt.id.desc()).first() + if source is None: + return + status = str(rpa_status or '').strip().lower() + if status in {'succeeded', 'consumed'}: + source.status = 'ready' + if inventory_file_id: + source.onhand_file_id = int(inventory_file_id) + elif status in {'failed', 'exhausted'}: + source.status = 'failed' + elif status in {'queued', 'running'}: + source.status = 'waiting' + preparation = source.preparation_attempt + _aggregate_preparation_after_source_settle(preparation) db.session.flush() diff --git a/backend/app/services/shipping_notice/onhand_report_handler.py b/backend/app/services/shipping_notice/onhand_report_handler.py new file mode 100644 index 00000000..7d1ad0f7 --- /dev/null +++ b/backend/app/services/shipping_notice/onhand_report_handler.py @@ -0,0 +1,156 @@ +""" +services/shipping_notice/onhand_report_handler.py + +用途:onhand(在手库存)报表事实的发货侧业务处理函数(阶段 B Task 7)—— + 在手文件归档终态 commit 后由 dispatch_report_fact 投递的 ReportFact + 只在此更新发货自己的门禁与候选相关状态,绝不写调拨或 RPA 侧事实。 +依赖:app.db、app.models(FreightRpaOnhandReportFile 只读行获取 / ShippingTaskOnhandLink / + ShippingOrderTask / ShippingProcessExecution)、app.core.errors + (ValidationError / NotFoundError)、freight_rpa.reports.facts(ReportFact / + require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、 + onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、 + process_gate_bridge(门禁同步)。 +逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks) + 注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调 + (rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch) + 在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮 + 接线;HTTP 收件入口 rpa_report_inventory_batch 只入队 Job、不 commit 文件, + 故不投递)。处理函数只改发货自己的行:[候选] settle 等待该来源的 + SourceAttempt 并绑定该文件(共享快照模型);[门禁] 对受影响的准备轮次任务与 + 挂接该文件的任务重投影履约门禁;[提交] 处理函数自行 commit(文件行已由归档方 + 提交,绝不回滚)。行插入唯一入口在 freight_rpa/onhand/report_store(本模块 + 【禁止】构造 FreightRpaOnhandReportFile 行,边界由 test_report_model_boundary 锁定); + TransferSourceJob 归调拨域(本模块不写)。 +""" + +from __future__ import annotations + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import FreightRpaOnhandReportFile, ShippingTaskOnhandLink +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind + + +def _sync_gates_for_task_ids(task_ids: list[int]) -> None: + """对给定任务逐一重投影履约门禁(活动、非 superseded 执行链;幂等可重放)。 + + 核心逻辑:按主键取任务与活动执行链——执行链缺失/已 superseded 时跳过 + (重冻结/复活链路上 Task 指针可能短暂指向旧执行链:迟到事实只保留原始 + 审计,不得回写已废弃执行的 Gate);命中即 sync_fulfillment_gates_from_task + (域事实投影为 Gate 结果,重复投递重投影同值,不产生重复行)。 + 只写不 commit——事务提交时机归属调用方(handle_onhand_report)。 + """ + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + seen: set[int] = set() + for task_id in task_ids: + if task_id in seen: + continue + seen.add(task_id) + task = db.session.get(ShippingOrderTask, int(task_id)) + if task is None or not getattr(task, 'active_process_execution_id', None): + continue + execution = db.session.get( + ShippingProcessExecution, int(task.active_process_execution_id), + ) + if execution is not None and str(execution.status or '').strip().lower() != 'superseded': + sync_fulfillment_gates_from_task(execution=execution, actor_type='system') + + +def handle_onhand_report(fact: ReportFact) -> None: + """report_kind 必须是 onhand。用 fact.file_id 更新发货门禁与候选。不写 TransferSourceJob。 + 不插入 freight_rpa_onhand_report_files。 + + (Task 7 契约 docstring 逐字保留如上;修复轮补充说明见下。) + + 核心逻辑: + [STEP 1] kind 门禁(fail-closed,防误注册/误分发); + [STEP 2] success 事实(ok 且 file_id 有值):按主键取回已提交的 onhand 报表行 + (只读——行由 freight_rpa/onhand/report_store 收敛写入,本模块只消费;缺失即 + fail-closed 抛 NotFoundError); + [STEP 3 候选] settle 等待该来源的候选准备行并绑定该文件 + (onhand_recovery_service.settle_preparation_source_from_onhand_report——共享 + 快照模型:该来源已有可用快照即对所有等待该来源的候选准备成立;幂等—— + 已 ready/已绑定的行不在等待集,重复投递零副作用、不重复候选行); + [STEP 4 门禁] 对受影响的准备轮次任务 + 挂接该文件(active link)的任务重投影 + 履约门禁(sync_fulfillment_gates_from_task,幂等可重放); + [STEP 5] db.session.commit()——处理函数提交自己的候选/门禁写(文件行已由 + 归档方提交,绝不回滚)。 + 失败/空事实(ok=False 或 file_id=None):无文件身份——不发明候选行、不 settle + 任何 SourceAttempt;仅对仍在等待该来源库存的任务重投影门禁(回调失败路径的 + 门禁更新归本处理函数),随后同样 commit。 + 【不写 TransferSourceJob】(归 in_transit_transfer 域);【不构造 + freight_rpa_onhand_report_files 行】(归 freight_rpa 域唯一写入口)。 + 异常原样外抛(不捕获):文件行已提交不回滚,Worker 重试整笔回调补齐。 + + Args: + fact: 终态已提交后由归档入口构造的报表事实(report_kind='onhand'/ + source_code/file_id/sha256/ok/error_code/error_message)。 + Returns: + None(候选/门禁写库,不返回业务值)。 + Raises: + ValidationError: report_kind 非 onhand(误注册/误分发,fail-closed)。 + NotFoundError: fact.file_id 对应的在手报表行不存在(事实先于文件提交 + 属硬性不一致,fail-closed 而非静默跳过)。 + """ + # [STEP 1] kind 门禁:本函数只消费 onhand 事实(dispatch 已按 kind 路由, + # 防御性复核,防止误注册成其他 kind 的处理函数后静默错写发货行)。 + kind = require_report_kind(fact.report_kind) + if kind != 'onhand': + raise ValidationError( + f"handle_onhand_report only accepts onhand facts, got: {kind!r}", + code='SHIPPING.RECEIPT_CALLBACK_INVALID', + details={'report_kind': fact.report_kind}, + ) + + from app.services.shipping_notice.onhand_recovery_service import ( + settle_preparation_source_from_onhand_report, + waiting_preparation_source_task_ids, + ) + + source_code = str(fact.source_code or '').strip() + affected_task_ids: list[int] = [] + + if not fact.ok or fact.file_id is None: + # [STEP 2·失败/空分支] 无文件身份:不发明候选行、不 settle 任何 SourceAttempt; + # 仅对仍在等待该来源库存的任务重投影门禁(失败路径门禁更新归本处理函数)。 + affected_task_ids.extend(waiting_preparation_source_task_ids(source_code=source_code)) + else: + # [STEP 2·success 分支] 只读取回已提交的在手报表行(构造禁走 report_store; + # 读取按主键)。 + inv_file = db.session.get(FreightRpaOnhandReportFile, int(fact.file_id)) + if inv_file is None: + raise NotFoundError( + f"Onhand report file not found: {fact.file_id}", + details={'file_id': fact.file_id}, + ) + file_source = str(inv_file.source_code or source_code).strip() + + # [STEP 3·候选] settle 等待该来源的候选准备行并绑定该文件(幂等)。 + settled = ( + settle_preparation_source_from_onhand_report( + source_code=file_source, onhand_file_id=int(inv_file.id), + ) + if file_source + else [] + ) + for preparation in settled: + if preparation.task_id: + affected_task_ids.append(int(preparation.task_id)) + + # [STEP 4·门禁] 挂接该文件(active link)的任务一并重投影门禁。 + links = ( + ShippingTaskOnhandLink.query + .filter_by(onhand_file_id=inv_file.id, is_active=True) + .all() + ) + for link in links: + if link.task_id: + affected_task_ids.append(int(link.task_id)) + + _sync_gates_for_task_ids(affected_task_ids) + + # [STEP 5] 处理函数提交自己的候选/门禁写(sync_fulfillment_gates_from_task + # 不 commit——不提交则请求结束回滚会丢掉这些写;文件行已提交,不受影响)。 + db.session.commit() diff --git a/backend/app/services/shipping_notice/inventory_routing_engine.py b/backend/app/services/shipping_notice/onhand_routing_engine.py similarity index 94% rename from backend/app/services/shipping_notice/inventory_routing_engine.py rename to backend/app/services/shipping_notice/onhand_routing_engine.py index 657512a9..aaf0074b 100644 --- a/backend/app/services/shipping_notice/inventory_routing_engine.py +++ b/backend/app/services/shipping_notice/onhand_routing_engine.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_routing_engine.py +services/shipping_notice/onhand_routing_engine.py 用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。 -依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。 +依赖:库存路由模型、冻结订单 Snapshot、routing_operators、onhand_source_repository。 逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源, 命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层); 随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。 @@ -16,8 +16,8 @@ from dataclasses import dataclass from datetime import datetime from typing import Any -from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot -from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources +from app.models import FreightRpaOnhandRoutingRule, ShippingOrderSnapshot +from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources from app.services.shipping_notice.routing_operators import matches_operator @@ -76,7 +76,7 @@ class InventoryRoutingResult: ) -def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[dict[str, Any], ...]: +def _matched_rule_summaries(rules: list[FreightRpaOnhandRoutingRule]) -> tuple[dict[str, Any], ...]: """将命中规则折叠为可审计、可序列化的摘要元组。""" return tuple( { @@ -177,7 +177,7 @@ def _condition_value_from_maps( def _rule_matches( - rule: ShippingInventoryRoutingRule, + rule: FreightRpaOnhandRoutingRule, *, value_reader, ) -> bool: @@ -191,7 +191,7 @@ def _rule_matches( return all(results) if rule.match_mode == 'all' else any(results) -def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, priority: int) -> InventoryRoutingResult: +def _evaluate_matched_rules(top_rules: list[FreightRpaOnhandRoutingRule], *, priority: int) -> InventoryRoutingResult: """ 将同优先级命中规则折叠为候选集合与建单资格。 @@ -250,13 +250,13 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr ) -def _published_rules(*, scope: str, now: datetime) -> list[ShippingInventoryRoutingRule]: +def _published_rules(*, scope: str, now: datetime) -> list[FreightRpaOnhandRoutingRule]: """加载当前时刻有效的已发布规则,按优先级降序。""" - query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope) + query = FreightRpaOnhandRoutingRule.query.filter_by(status='published', scope=scope) return [ rule for rule in query.order_by( - ShippingInventoryRoutingRule.priority.desc(), - ShippingInventoryRoutingRule.id.asc(), + FreightRpaOnhandRoutingRule.priority.desc(), + FreightRpaOnhandRoutingRule.id.asc(), ).all() if (rule.effective_from is None or rule.effective_from <= now) and (rule.effective_to is None or rule.effective_to >= now) diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/onhand_rpa_workflow.py similarity index 86% rename from backend/app/services/shipping_notice/inventory_rpa_workflow.py rename to backend/app/services/shipping_notice/onhand_rpa_workflow.py index 84543921..75c9ced2 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/onhand_rpa_workflow.py @@ -1,18 +1,29 @@ """ -services/shipping_notice/inventory_rpa_workflow.py +services/shipping_notice/onhand_rpa_workflow.py 用途:发货通知库存 RPA 业务编排(触发导出、等待/超时、回调落盘、快照与门禁推进)。 依赖:customer_identity_gate、reservation_gate、freight_rpa.onhand(trigger_io 目录/attempts 计数/ - workflow_protocol 协议记账)、inventory_snapshot、inventory_mapping_workflow、query_service、 + workflow_protocol 协议记账)、onhand_snapshot、onhand_mapping_workflow、query_service、 动态订单字段、tool_common、state_machine、tool_response。 -逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新; +逻辑:onhand_workflow.ensure_onhand 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新; 库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取; 复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。 Task 9 拆分:attempt 行记账/run_no 幂等键/轮次与排程校验/批量进度记账/超时窗口数学/ 回调契约归一化等纯协议态下沉 freight_rpa.onhand.workflow_protocol(零 shipping_notice - import);快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机 + import); 快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机 留守本文件(事务边界与 commit 时机与拆分前逐点等价)。下方旧私有名以模块别名 re-export, 既有同包调用与测试 import(含 monkeypatch 接缝)不换名。 + 【阶段 B Task 7 修复】单回调(rpa_report_inventory)与批量 worker + (process_rpa_report_inventory_batch)在文件行 commit 后逐文件投递 onhand 报表事实 + (dispatch_report_fact(ReportFact(report_kind='onhand', ...))——先 commit 再投递; + 处理函数异常原样外抛、不折进 warnings;HTTP 收件入口 rpa_report_inventory_batch 只入队 + Job、不 commit 文件故不投递;空结果审计快照不投递——不作可用库存复用)。候选 settle + 与门禁同步由 handle_onhand_report 承担(见 onhand_report_handler.py)。修复轮 2/3:批量内 + 单文件处理函数失败先回滚未提交会话(半途写不得被后续 commit 持久化)并继续投递其余 + 已提交文件,排程 finalize 与 drop 文件清理入队照常执行,之后以 + OnhandReportDispatchAfterCommitError 携带未成功文件清单原样重抛;Job 处理器把清单写回 + payload(retry_dispatch_files)并 requeue,重试经「只重投失败文件」通道 + (_dispatch_retry_onhand_report_files)补齐,全部成功前绝不返回 ok。 """ from __future__ import annotations @@ -26,16 +37,16 @@ from typing import Any from app import db from app.core.errors import AppError, ServiceUnavailableError -from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask +from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING -from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file -from app.services.shipping_notice.inventory_snapshot_store import ( +from app.services.shipping_notice.onhand_snapshot import ingest_inventory_file +from app.services.shipping_notice.onhand_snapshot_store import ( find_latest_ready_snapshot, get_or_create_rpa_inventory_snapshot, link_snapshot_to_task, link_snapshot_to_task_for_preparation, ) -from app.services.shipping_notice.inventory_upload import ( +from app.services.shipping_notice.onhand_upload import ( delete_staged_task_inventory_file, promote_staged_task_inventory_file, rebuild_task_inventory_attachment_from_snapshot, @@ -49,12 +60,12 @@ from app.services.freight_rpa.onhand.callback_cleanup import ( quarantine_callback_drop_file, recover_pending_rpa_callback_cleanup_jobs, ) -from app.services.shipping_notice.inventory_source_gate import ( +from app.services.shipping_notice.onhand_source_gate import ( assert_inventory_source_gate, inventory_identities_match, is_inventory_source_stable, ) -from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source +from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, customer_gate_tool_response, @@ -186,7 +197,7 @@ def _try_reuse_inventory_snapshot( if mode == "retry_rpa": return None - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response snapshot = find_latest_ready_snapshot( str(rpa_source.get("source_code") or ""), @@ -208,7 +219,7 @@ def _try_reuse_inventory_snapshot( task, "inventory_snapshot_reused", { - "inventory_file_no": snapshot.inventory_file_no, + "inventory_file_no": snapshot.onhand_file_no, "source_code": snapshot.source_code, "warehouse_id": snapshot.warehouse_id, "snapshot_age_seconds": link.snapshot_age_seconds, @@ -216,7 +227,7 @@ def _try_reuse_inventory_snapshot( ) db.session.flush() - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines try: lines, column_meta = read_inventory_file_lines(snapshot) except (OSError, ValueError, AppError): @@ -298,12 +309,12 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int | Returns: tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。 """ - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task from app.services.shipping_notice.process_gate_projection import task_blocking_reason if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task): return None, None, None - last_trigger = latest_task_event(task, "inventory_rpa_triggered") + last_trigger = latest_task_event(task, "onhand_rpa_triggered") if not last_trigger or not isinstance(last_trigger.created_at, datetime): return None, None, None # 超时窗口数学为协议态(workflow_protocol.compute_rpa_wait_window); @@ -344,14 +355,14 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor return None log_task_event( task, - "inventory_rpa_wait_rechecked", + "onhand_rpa_wait_rechecked", {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, ) # [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落 # rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。 log_task_event( task, - "inventory_rpa_failed", + "onhand_rpa_failed", { "error": "timeout", "elapsed_seconds": elapsed, @@ -360,7 +371,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor ) log_task_event( task, - "inventory_rpa_exhausted", + "onhand_rpa_exhausted", {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, ) db.session.flush() @@ -378,7 +389,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]: """从任务正式库存身份推导快照预期二元组。""" - from app.services.shipping_notice.inventory_source_gate import task_inventory_identity + from app.services.shipping_notice.onhand_source_gate import task_inventory_identity identity = task_inventory_identity(task) return ( @@ -409,7 +420,7 @@ def _rollback_orphan_inventory_snapshot( return from sqlalchemy import inspect as sa_inspect - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path for raw in paths: delete_inventory_storage_path(raw) @@ -446,12 +457,12 @@ def _inventory_file_sha256(path: Path) -> str: def _validate_reused_snapshot_callback_file( - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, callback_path: Path, ) -> str | None: """ 校验复用快照时回调落盘文件与托管 storage_path 内容一致。 - 核心逻辑:不一致时拒绝复用,避免 inventory_lines_json 与 storage_path 文件分叉。 + 核心逻辑:不一致时拒绝复用,避免 onhand_lines_json 与 storage_path 文件分叉。 """ storage_path = Path(str(inv_file.storage_path or "")) if not storage_path.is_file(): @@ -463,11 +474,11 @@ def _validate_reused_snapshot_callback_file( return None -def _snapshot_ingest_path(inv_file: ShippingInventoryFile) -> Path: +def _snapshot_ingest_path(inv_file: FreightRpaOnhandReportFile) -> Path: """返回应解析的库存快照托管路径(复用与新建均读 storage_path)。""" path = Path(str(inv_file.storage_path or "")) if not path.is_file() or str(inv_file.storage_path or "").startswith("failed://"): - raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.inventory_file_no}") + raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.onhand_file_no}") return path @@ -575,7 +586,7 @@ def _flush_pending_callback_moves( def _try_rebuild_task_inventory_attachment( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, post_commit_warnings: list[str], ) -> bool: """ @@ -655,12 +666,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) # per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。 source_run_no = str(payload.get('source_run_no') or '').strip() if source_run_no: - from app.models import ShippingTaskInventoryRpaAttempt + from app.models import FreightRpaOnhandTaskAttempt current_attempt = ( - db.session.query(ShippingTaskInventoryRpaAttempt) + db.session.query(FreightRpaOnhandTaskAttempt) .filter_by(task_no=task.task_no, source_run_no=source_run_no) - .order_by(ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.id.desc()) .first() ) if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running', 'succeeded'}: @@ -672,12 +683,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) # source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt # 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。 if source_run_no: - from app.models import ShippingTaskInventoryRpaAttempt + from app.models import FreightRpaOnhandTaskAttempt current_attempt = ( - db.session.query(ShippingTaskInventoryRpaAttempt) + db.session.query(FreightRpaOnhandTaskAttempt) .filter_by(task_no=task.task_no, source_run_no=source_run_no) - .order_by(ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.id.desc()) .first() ) if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}: @@ -811,9 +822,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ 核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。 """ callback_source = str(payload.get("source_code") or "").strip().upper() - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - task_sources = set(task_frozen_inventory_source_codes(task)) + task_sources = set(task_frozen_onhand_source_codes(task)) if not callback_source: return tool_response( status="failed", @@ -829,12 +840,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ data=serialize_task_for_tool(task), ) - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(callback_source) is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed' callback_wh = str(payload.get("warehouse_id") or "").strip().upper() - from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id task_wh = resolve_inventory_source_warehouse_id(task, source=source) or '' if is_fixed and (not callback_wh or callback_wh != task_wh): @@ -962,7 +973,7 @@ 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_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source return get_database_inventory_source(source_code) @@ -976,7 +987,7 @@ def _batch_snapshot_verify_warehouse_id( if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match': return None if task: - from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or '' return warehouse_id or None @@ -1021,14 +1032,14 @@ def ensure_inventory_via_rpa( allow_auto_retry: bool = True, source_codes: list[str] | None = None, ) -> dict[str, Any]: - """触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。 + """触发或轮询 RPA 库存导出;成功落盘时委托 onhand_workflow.inventory_loaded_response。 Args: allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。 - poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。 + poll_onhand_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。 source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。 """ - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response manual_retry_round = mode == "retry_rpa" disposition_reason = task_execution_block_reason(task) @@ -1075,7 +1086,7 @@ def ensure_inventory_via_rpa( except AppError: apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) # OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。 - task.stage = "inventory_source_resolving" + task.stage = "onhand_source_resolving" _set_workflow_error(task, "库存源尚未确定,无法启动 RPA") db.session.commit() return tool_response( @@ -1108,7 +1119,7 @@ def ensure_inventory_via_rpa( _set_workflow_error(task, None) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='running', message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。', @@ -1136,7 +1147,7 @@ def ensure_inventory_via_rpa( poll_read_only = not allow_auto_retry set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='needs_human', message='库存 RPA 未能为全部库存源生成结果。', @@ -1165,11 +1176,11 @@ def ensure_inventory_via_rpa( # [STEP 1] 先检查当前是否已有进行中的 RPA 导出。 # 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。 timeout_seconds = rpa_inventory_timeout_seconds() - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task from app.services.shipping_notice.process_gate_projection import task_blocking_reason if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task): - last_trigger = latest_task_event(task, "inventory_rpa_triggered") + last_trigger = latest_task_event(task, "onhand_rpa_triggered") if last_trigger and isinstance(last_trigger.created_at, datetime): elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds()) if elapsed < timeout_seconds: @@ -1190,12 +1201,12 @@ def ensure_inventory_via_rpa( }, }, ) - last_failed = latest_task_event(task, "inventory_rpa_failed") + last_failed = latest_task_event(task, "onhand_rpa_failed") if not last_failed or (last_failed.created_at < last_trigger.created_at): _set_workflow_error(task, "RPA 库存导出等待超时") log_task_event( task, - "inventory_rpa_failed", + "onhand_rpa_failed", { "error": "timeout", "elapsed_seconds": elapsed, @@ -1249,7 +1260,7 @@ def ensure_inventory_via_rpa( ) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message=progress_message, @@ -1261,7 +1272,7 @@ def ensure_inventory_via_rpa( ) log_task_event( task, - "inventory_rpa_triggered", + "onhand_rpa_triggered", { "trigger": trigger, "run_no": _extract_run_no_from_trigger(trigger), @@ -1299,7 +1310,7 @@ def ensure_inventory_via_rpa( _set_workflow_error(task, human_message[:500]) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=human_message, @@ -1308,7 +1319,7 @@ def ensure_inventory_via_rpa( total=max_attempts, detail=detail, ) - log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"}) + log_task_event(task, "onhand_rpa_retry_requested", {"reason": "trigger_failed"}) db.session.commit() return tool_response( status="needs_human", @@ -1409,7 +1420,7 @@ def _handle_rpa_inventory_skipped( _set_workflow_error(task, None) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message="货代系统当前无可用库存", @@ -1418,7 +1429,7 @@ def _handle_rpa_inventory_skipped( ) log_task_event( task, - "inventory_rpa_skipped", + "onhand_rpa_skipped", { "skip_reason": skip_reason, "message": detail or message, @@ -1449,14 +1460,14 @@ def _handle_rpa_inventory_failed( """处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。""" apply_task_transition(task, TaskTransition.INV_UNAVAIL) _set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500]) - log_task_event(task, "inventory_rpa_failed", { + log_task_event(task, "onhand_rpa_failed", { "error": _workflow_error(task), "error_code": str(payload.get("error_code") or "rpa_export_failed"), "rpa_runtime": runtime, }) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='needs_human', message=_workflow_error(task), @@ -1520,7 +1531,7 @@ def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) -> def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: """RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。""" - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler cleanup_retry_warnings = flush_callback_cleanup_queue() @@ -1574,7 +1585,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: # callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。 log_task_event( task, - 'shipping_inventory_callback_ignored', + 'freight_rpa_onhand_callback_ignored', { 'run_no': run_no_raw, 'source_code': source_code_from_run, @@ -1714,7 +1725,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) staging_path: Path | None = None - inv_file: ShippingInventoryFile | None = None + inv_file: FreightRpaOnhandReportFile | None = None created_new = False orphan_paths: list[str | Path] = [] try: @@ -1780,7 +1791,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if link is None: raise _RpaCallbackItemAbort("inventory_identity_mismatch") - from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure structure_check = validate_production_inventory_structure( source_code=str(rpa_source['source_code']), path=ingest_path, @@ -1808,7 +1819,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: } set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message="RPA 库存文件已返回,正在读取库存快照", @@ -1824,7 +1835,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: "upload_filename": ingest_path.name, "upload_path": str(ingest_path), "origin_file_path": str(path), - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "reused_existing_snapshot": not created_new, "structure_validation": column_meta.get('structure_validation'), }, @@ -1835,7 +1846,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: lines, column_meta=column_meta, source="rpa_callback", - event_type="inventory_rpa_ready", + event_type="onhand_rpa_ready", field_mapping=dict(structure_check['field_mapping']), mapping_source='parsing_profile', commit=False, @@ -1885,7 +1896,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: path, run_no=run_no, task_no=task.task_no, - inventory_file_no=inv_file.inventory_file_no, + inventory_file_no=inv_file.onhand_file_no, ) promote_ok = False try: @@ -1906,13 +1917,13 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: processed, run_no=run_no, task_no=task.task_no, - inventory_file_no=inv_file.inventory_file_no, + inventory_file_no=inv_file.onhand_file_no, ) if move_warning: post_commit_warnings.append(f"move_callback_file_failed:{move_warning}") try: - from app.services.shipping_notice.inventory_file_store import start_inventory_file_linked_tasks + from app.services.shipping_notice.onhand_file_store import start_inventory_file_linked_tasks start_inventory_file_linked_tasks(inv_file) except Exception as exc: @@ -1926,10 +1937,25 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if post_commit_warnings: _persist_post_commit_task_event( task, - "inventory_rpa_post_commit_warning", - {"warnings": post_commit_warnings, "inventory_file_no": inv_file.inventory_file_no}, + "onhand_rpa_post_commit_warning", + {"warnings": post_commit_warnings, "inventory_file_no": inv_file.onhand_file_no}, ) + # [STEP 阶段 B Task 7 修复] 文件行已随上方 db.session.commit() 提交——同请求投递 + # onhand 报表事实(先 commit 再投递)。处理函数异常必须原样外抛:绝不折进 + # post_commit_warnings、不吞——已提交文件行保留,Worker 重试整笔回调即可补齐 + # 候选 settle 与门禁收口(处理函数幂等:重复投递不重复候选行)。 + from app.services.freight_rpa.reports.dispatch import dispatch_report_fact + from app.services.freight_rpa.reports.facts import ReportFact + + dispatch_report_fact(ReportFact( + report_kind='onhand', + source_code=str(inv_file.source_code or ''), + file_id=int(inv_file.id), + sha256=str(inv_file.file_sha256 or '') or None, + ok=True, + )) + if response is None: return tool_response(status="failed", task=task, message="RPA 回调处理未完成") if post_commit_warnings: @@ -1963,7 +1989,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: existing_job = ( Job.query.filter( Job.domain == 'shipping_notice', - Job.job_type == 'shipping_inventory_callback_process', + Job.job_type == 'freight_rpa_onhand_callback_process', Job.business_ref == f'inventory-callback:{callback_id}', Job.status.in_(('queued', 'running')), ) @@ -1996,7 +2022,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: from app.jobs.types import JobType job_id = enqueue( - JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS, + JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS, receipt_payload, domain='shipping_notice', business_ref=f'inventory-callback:{callback_id}', @@ -2119,6 +2145,89 @@ def _received_batch_callback_file_path( return None +class OnhandReportDispatchAfterCommitError(RuntimeError): + """批量 commit 后 onhand 事实投递失败(Task 7 修复轮 3)。 + + 用途:process_rpa_report_inventory_batch 在排程收口与 drop 文件清理入队完成后, + 把首轮投递的首个异常连同「未成功文件清单」一并外抛——Job 处器捕获后把清单写回 + payload(retry_dispatch_files)并 fail_job(retryable=True),重试经「只重投失败 + 文件」通道(_dispatch_retry_onhand_report_files)补齐,不再整批重放(整批重放 + 会被 callback_id 已消费的 replay 检查跳过、且已收口的排程 run 校验会拦下)。 + 继承 RuntimeError:与既有 RuntimeError 契约(测试 match / 调用方捕获)兼容。 + """ + + def __init__(self, message: str, *, failed_files: list[dict[str, Any]]) -> None: + super().__init__(message) + self.failed_files = list(failed_files) + + +def _dispatch_retry_onhand_report_files(retry_files: list[Any]) -> dict[str, Any]: + """Job 重试通道:只对首轮投递失败的已提交文件重投 onhand 事实(不重放整批)。 + + 【AI 触发时机】:仅由 process_rpa_report_inventory_batch 在 payload 携带 + retry_dispatch_files(Job 处理器自 OnhandReportDispatchAfterCommitError 清单写回) + 时调用;普通 Worker 回调载荷不含该键,永不进入本通道。 + 核心逻辑:逐文件 dispatch_report_fact;单文件处理函数失败先回滚未提交会话 + (半途写不得被后续 commit 持久化、PendingRollback 不得拖垮后续投递)并收集 + 首个异常与未成功清单;任一失败即携带清单重抛(重试绝不在处理函数未完成时 + 返回 ok);全部成功才返回 ok(result_status='retried'——Job 处理器据此 + finish_job,且仅在此即全部处理函数已完成的情形下才标记成功)。 + Args: + retry_files: 首轮未成功文件清单({source_code, file_id, sha256} 字典列表)。 + Returns: + tool_response:status='ok'、data.result_status='retried'(非 failed/ + partial_failed,Job 处理器走 finish_job 成功收口)。 + Raises: + OnhandReportDispatchAfterCommitError: 仍有文件投递失败(携带未成功清单, + 供 Job 处理器更新 payload 继续重试,直至 attempts 耗尽落终态 failed)。 + """ + from app.services.freight_rpa.reports.dispatch import dispatch_report_fact + from app.services.freight_rpa.reports.facts import ReportFact + + dispatch_error: Exception | None = None + remaining: list[dict[str, Any]] = [] + for item in retry_files: + if not isinstance(item, dict): + continue + try: + file_id = int(item.get('file_id')) + except (TypeError, ValueError): + continue + marker = { + 'source_code': str(item.get('source_code') or ''), + 'file_id': file_id, + 'sha256': item.get('sha256'), + } + try: + dispatch_report_fact(ReportFact( + report_kind='onhand', + source_code=marker['source_code'], + file_id=marker['file_id'], + sha256=marker['sha256'] if isinstance(marker['sha256'], str) else None, + ok=True, + )) + except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余文件必须继续投递,未成功清单随专用异常重抛 + db.session.rollback() + if dispatch_error is None: + dispatch_error = exc + remaining.append(marker) + logging.getLogger(__name__).warning( + 'RPA onhand report fact retry dispatch failed: file_id=%s error=%s', + marker['file_id'], exc, exc_info=exc, + ) + if dispatch_error is not None: + raise OnhandReportDispatchAfterCommitError( + f'RPA onhand report fact retry dispatch failed: {dispatch_error}', + failed_files=remaining, + ) + return tool_response( + status='ok', + message=f'库存 RPA 回调重试完成:已补齐投递 {len(retry_files)} 个失败文件。', + data={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)}, + extra={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)}, + ) + + def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: """ RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。 @@ -2128,10 +2237,19 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any 含 schedule_run_id 时委托 finalize 终态化排程 run。 响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。 """ - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response cleanup_retry_warnings = flush_callback_cleanup_queue() + # [STEP 阶段 B Task 7 修复轮 3] Job 重试「只重投失败文件」通道:首轮投递失败后, + # Job 处理器把未成功文件清单写回 payload(retry_dispatch_files);重试不再整批 + # 重放(task-linked 项的 Attempt 已消费 callback_id 会被 replay 检查跳过、已收口 + # 的排程 run 校验也会拦下整批),只对清单内已提交文件重投事实(处理函数幂等)。 + # 普通回调载荷不含该键,永不进入本通道。 + retry_files = payload.get('retry_dispatch_files') if isinstance(payload, dict) else None + if retry_files: + return _dispatch_retry_onhand_report_files(retry_files) + if payload.get('schema_version') != SCHEMA: return tool_response(status='failed', message='callback_schema_invalid', data={ 'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid', @@ -2166,6 +2284,9 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any skipped: list[dict[str, Any]] = [] batch_new_storage_paths: list[str] = [] pending_callback_moves: list[dict[str, Any]] = [] + # [STEP 阶段 B Task 7 修复] 整批事务内落地的 onhand 报表文件清单——随 created + # 同步追加/回退(单项保存点回滚时该文件行一并消失),整批 commit 后逐文件投递事实。 + landed_onhand_files: list[dict[str, Any]] = [] try: for item in results: @@ -2187,8 +2308,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any if not item_callback_id and source_run_no_item: item_callback_id = f"{callback_id}:{source_run_no_item}:C1" if item_callback_id: - from app.models import ShippingTaskInventoryRpaAttempt - replay_attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(callback_id=item_callback_id).one_or_none() + from app.models import FreightRpaOnhandTaskAttempt + replay_attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(callback_id=item_callback_id).one_or_none() if replay_attempt is not None: skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True}) continue @@ -2382,7 +2503,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any # 调度空结果保留为审计快照,但绝不链接给任务或作为 ready 库存复用。 source = _resolve_batch_callback_source(None, merged_item) if source and not task_no: - from app.services.shipping_notice.inventory_snapshot_store import create_empty_rpa_inventory_snapshot + from app.services.shipping_notice.onhand_snapshot_store import create_empty_rpa_inventory_snapshot snapshot = create_empty_rpa_inventory_snapshot( source=source, rpa_run_no=run_no or None, schedule_run_id=schedule_run_id, @@ -2391,7 +2512,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any ) skipped.append({ 'source_code': source_code, 'warehouse_id': warehouse_id, - 'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.inventory_file_no, + 'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.onhand_file_no, }) continue @@ -2427,8 +2548,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any "error": "file_missing", }) if task_no and source_run_no_item: - from app.models import ShippingTaskInventoryRpaAttempt - _att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() + from app.models import FreightRpaOnhandTaskAttempt + _att = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() if _att: _att.callback_id = item_callback_id or callback_id _att.callback_received_at = datetime.utcnow(); _att.file_generated = False; _att.file_exists_at_callback = False @@ -2476,7 +2597,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any item_savepoint = db.session.begin_nested() item_orphan_path: str | None = None created_new = False - inv_file: ShippingInventoryFile | None = None + inv_file: FreightRpaOnhandReportFile | None = None created_entry: dict[str, Any] | None = None try: try: @@ -2505,7 +2626,7 @@ def process_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 + from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure ingest_path = _snapshot_ingest_path(inv_file) structure_check = validate_production_inventory_structure( @@ -2516,7 +2637,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any inv_file.mapping_source = 'parsing_profile' inv_file.mapping_confirmed = True created_entry = { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "source_code": inv_file.source_code or source_code, "warehouse_id": inv_file.warehouse_id or warehouse_id, "reused_existing_snapshot": not created_new, @@ -2529,6 +2650,13 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any }, } created.append(created_entry) + # [STEP 阶段 B Task 7 修复] 记录落地文件(含复用行——同样随整批事务提交), + # 供整批 commit 后投递 onhand 报表事实;except 分支随 created 一并回退。 + landed_onhand_files.append({ + 'source_code': str(inv_file.source_code or source_code or ''), + 'file_id': int(inv_file.id), + 'sha256': str(inv_file.file_sha256 or '') or None, + }) if item_orphan_path: batch_new_storage_paths.append(item_orphan_path) @@ -2562,7 +2690,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any lines, column_meta=column_meta, source="rpa_batch_callback", - event_type="inventory_rpa_ready", + event_type="onhand_rpa_ready", field_mapping=dict(structure_check['field_mapping']), mapping_source='parsing_profile', commit=False, @@ -2583,7 +2711,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any run_no=source_run_no_item, callback_payload={ **dict(merged_item), - 'inventory_file_no': inv_file.inventory_file_no, + 'inventory_file_no': inv_file.onhand_file_no, }, ) if final_code != 'succeeded': @@ -2605,20 +2733,24 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any "run_no": run_no or None, "task_no": task_no or None, "schedule_run_id": schedule_run_id, - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, }) item_savepoint.commit() except _RpaCallbackItemAbort as abort: item_savepoint.rollback() if item_orphan_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(item_orphan_path) if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path: batch_new_storage_paths.pop() if created_entry and created and created[-1] is created_entry: created.pop() + # [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录 + # (保存点回滚后该文件行已消失,不得再投递其事实)。 + if landed_onhand_files: + landed_onhand_files.pop() failed.append({ "source_code": source_code, "warehouse_id": warehouse_id, @@ -2629,13 +2761,17 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any except Exception as exc: item_savepoint.rollback() if item_orphan_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(item_orphan_path) if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path: batch_new_storage_paths.pop() if created_entry and created and created[-1] is created_entry: created.pop() + # [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录 + # (保存点回滚后该文件行已消失,不得再投递其事实)。 + if landed_onhand_files: + landed_onhand_files.pop() failed.append({ "source_code": source_code, "warehouse_id": warehouse_id, @@ -2661,7 +2797,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any db.session.commit() except Exception as exc: db.session.rollback() - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path for storage_path in batch_new_storage_paths: delete_inventory_storage_path(storage_path) @@ -2674,9 +2810,47 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any }, ) + # [STEP 阶段 B Task 7 修复轮 2/3] 整批文件行已随上方 db.session.commit() 提交——同一 + # worker 调用内逐文件投递 onhand 报表事实(先 commit 再投递)。必须放在外层 + # except 之后:处理函数异常若落入该 except 会误删已提交文件的存储对象。 + # 单文件处理函数失败只收集首个异常并继续投递其余已提交文件(不得因一文件失败 + # 跳过其余文件的候选/门禁收口);【修复轮 3】失败点先回滚未提交会话——丢弃该次 + # 处理函数半途 flush 的候选/门禁写(否则会被下一个处理函数的 commit / finalize + # 的 commit 误持久化,且数据库错误后的 PendingRollback 会拖垮后续投递与收口), + # 已 commit 的文件行不受影响(rollback 只丢弃未提交变更)。首个异常与未成功 + # 文件清单在排程收口、drop 文件清理入队之后携带在专用异常上原样重抛(见下)—— + # 调用方见到失败、文件行保留,Job 按 retryable=True 契约经「只重投失败文件」 + # 通道补齐(处理函数幂等:重复投递不重复候选行)。空结果审计快照 + # (create_empty_rpa_inventory_snapshot,no_inventory_data 分支)不投递——其明令 + # 不作为可用库存复用,投递 ok=True 事实会错误 settle 等待中的候选准备。 + from app.services.freight_rpa.reports.dispatch import dispatch_report_fact + from app.services.freight_rpa.reports.facts import ReportFact + + dispatch_error: Exception | None = None + failed_dispatch_files: list[dict[str, Any]] = [] + for landed in landed_onhand_files: + try: + dispatch_report_fact(ReportFact( + report_kind='onhand', + source_code=str(landed['source_code'] or ''), + file_id=int(landed['file_id']), + sha256=landed['sha256'], + ok=True, + )) + except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余已提交文件必须继续投递,首个异常携带未成功清单在收口/清理之后重抛 + # [修复轮 3] 回滚未提交会话:半途写不得被后续 commit 持久化;PendingRollback 解除。 + db.session.rollback() + if dispatch_error is None: + dispatch_error = exc + failed_dispatch_files.append(dict(landed)) + logging.getLogger(__name__).warning( + 'RPA onhand report fact dispatch failed after batch commit: file_id=%s error=%s', + landed['file_id'], exc, exc_info=exc, + ) + finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"} if schedule_run_id is not None: - from app.services.schedule.freight_onhand_rpa_finalize import finalize_shipping_inventory_schedule_run + from app.services.schedule.freight_rpa_onhand_finalize import finalize_shipping_inventory_schedule_run finalize_result = finalize_shipping_inventory_schedule_run( schedule_run_id, @@ -2695,6 +2869,18 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any ), ) + # [STEP 阶段 B Task 7 修复轮 3] drop 文件清理已先行入队/移动(不得因重抛被跳过 + # ——清理只在 _flush_pending_callback_moves 内写消费标记/入队,先于此处执行): + # 首个投递异常携带未成功文件清单在专用异常上原样重抛——调用方(Job/Worker) + # 见到失败、已提交文件行保留;Job 处理器把清单写回 payload(retry_dispatch_files) + # 后 fail_job(retryable=True),重试经「只重投失败文件」通道补齐(见函数头部), + # 全部投递成功前绝不返回 ok(重试不得在处理函数未完成时被记成功)。 + if dispatch_error is not None: + raise OnhandReportDispatchAfterCommitError( + f'RPA onhand report fact dispatch failed after batch commit: {dispatch_error}', + failed_files=failed_dispatch_files, + ) + response_data = { "run_no": run_no, "created": created, @@ -2743,7 +2929,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any def _validate_repair_inventory_snapshot( task: ShippingNotice, - inv_file: ShippingInventoryFile | None, + inv_file: FreightRpaOnhandReportFile | None, *, requested_file_no: str | None = None, ) -> str | None: @@ -2751,10 +2937,10 @@ def _validate_repair_inventory_snapshot( 校验修复接口允许使用的库存快照。 核心逻辑:默认仅 active link;显式 file_no 必须与 active 一致,且 ready/未过期/身份匹配。 """ - from app.models import ShippingTaskInventoryLink - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task - from app.services.shipping_notice.inventory_snapshot_store import is_snapshot_fresh - from app.services.shipping_notice.inventory_source_gate import ( + from app.models import ShippingTaskOnhandLink + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_snapshot_store import is_snapshot_fresh + from app.services.shipping_notice.onhand_source_gate import ( inventory_identities_match, is_inventory_source_stable, ) @@ -2766,12 +2952,12 @@ def _validate_repair_inventory_snapshot( return "no_active_snapshot" if inv_file.id != active.id: return "snapshot_not_active_for_task" - if requested_file_no and active.inventory_file_no != requested_file_no: + if requested_file_no and active.onhand_file_no != requested_file_no: return "snapshot_not_active_for_task" if task.id is not None: - link = ShippingTaskInventoryLink.query.filter_by( + link = ShippingTaskOnhandLink.query.filter_by( task_id=task.id, - inventory_file_id=inv_file.id, + onhand_file_id=inv_file.id, is_active=True, ).first() if link is None: @@ -2782,7 +2968,7 @@ def _validate_repair_inventory_snapshot( return "snapshot_expired" if not is_inventory_source_stable(task): return "inventory_source_unstable" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(inv_file.source_code) if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed': @@ -2806,7 +2992,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: Returns: tool_response:含 attachment_path 与 inventory_file_no。 """ - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task task = resolve_task_from_payload(payload) if not task: @@ -2821,7 +3007,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: message="任务无可用库存快照,无法重建附件", data=serialize_task_for_tool(task), ) - if inv_file_no and inv_file.inventory_file_no != inv_file_no: + if inv_file_no and inv_file.onhand_file_no != inv_file_no: return tool_response( status="failed", task=task, @@ -2856,7 +3042,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: task, "inventory_attachment_repaired", { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "attachment_path": str(attachment_path), "source": str(payload.get("source") or "manual_repair"), }, @@ -2878,7 +3064,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: message="任务库存附件已从快照重建", data={ **serialize_task_for_tool(task), - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "attachment_path": str(attachment_path), }, ) diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/onhand_snapshot.py similarity index 96% rename from backend/app/services/shipping_notice/inventory_snapshot.py rename to backend/app/services/shipping_notice/onhand_snapshot.py index af621fdd..2b696a75 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/onhand_snapshot.py @@ -1,9 +1,9 @@ """ -services/shipping_notice/inventory_snapshot.py +services/shipping_notice/onhand_snapshot.py 用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。 依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。 -逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。 +逻辑:由 onhand_workflow、onhand_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。 """ from __future__ import annotations @@ -187,12 +187,12 @@ def _normalize_inventory_row( # 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 + from app.models import FreightRpaOnhandField 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() + for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all() } parsed = { field_id: _cell(row, index) @@ -334,7 +334,7 @@ def _load_excel_rows( """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 + from app.services.shipping_notice.onhand_file_identity import load_inventory_csv_rows rows = load_inventory_csv_rows(path, max_rows=max_rows) try: @@ -422,7 +422,7 @@ def describe_inventory_columns( ) -> dict[str, Any]: """根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。""" if field_mapping: - from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping + from app.services.shipping_notice.onhand_mapping import build_column_meta_from_mapping return build_column_meta_from_mapping( headers, @@ -587,7 +587,7 @@ def parse_inventory_rows( ) -> list[dict[str, Any]]: """按表头与数据行解析库存表格(Excel 或文档提取文本共用)。""" if field_mapping: - from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping + from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping columns = resolve_columns_from_field_mapping(headers, field_mapping) else: @@ -627,7 +627,7 @@ def parse_inventory_text( header = rows[0] if field_mapping: - from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping + from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping has_header = True column_meta = describe_inventory_columns( @@ -659,7 +659,7 @@ def read_inventory_schema_preview( max_sample_rows: int = 5, ) -> dict[str, Any]: """仅读取表头与样本行(供 LLM 推断列映射,不加载全量数据)。""" - from app.services.shipping_notice.inventory_mapping import suggest_field_mapping + from app.services.shipping_notice.onhand_mapping import suggest_field_mapping scan_rows, total_rows = _load_excel_rows(path, max_rows=40) if not scan_rows: @@ -724,7 +724,7 @@ def parse_inventory_excel_with_meta( headers = [str(c or "").strip() for c in rows[header_idx]] data_rows = [list(r) for r in rows[header_idx + 1 :] if r] if not field_mapping: - from app.services.shipping_notice.inventory_mapping import suggest_field_mapping + from app.services.shipping_notice.onhand_mapping import suggest_field_mapping suggested = suggest_field_mapping(headers) if suggested.get("part_number") and suggested.get("available_qty"): diff --git a/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py b/backend/app/services/shipping_notice/onhand_snapshot_reuse_policy.py similarity index 95% rename from backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py rename to backend/app/services/shipping_notice/onhand_snapshot_reuse_policy.py index c6b4c354..1dd729c2 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py +++ b/backend/app/services/shipping_notice/onhand_snapshot_reuse_policy.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_snapshot_reuse_policy.py +services/shipping_notice/onhand_snapshot_reuse_policy.py 用途:统一判断库存快照是否可被当前任务复用。 -依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。 +依赖:FreightRpaOnhandReportFile、ShippingNotice、候选冻结事实。 逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。 """ diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/onhand_snapshot_store.py similarity index 79% rename from backend/app/services/shipping_notice/inventory_snapshot_store.py rename to backend/app/services/shipping_notice/onhand_snapshot_store.py index 9d12e71f..9c3037f7 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/onhand_snapshot_store.py @@ -1,9 +1,12 @@ """ -services/shipping_notice/inventory_snapshot_store.py +services/shipping_notice/onhand_snapshot_store.py 用途:库存快照查询、TTL 复用、RPA 入库与任务关联审计。 -依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_file_store、Flask config。 -逻辑:ensure_inventory 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录。 +依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读取回行,禁止构造)、 + freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_file_store、Flask config。 +逻辑:ensure_onhand 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录; + 阶段 B Task 5 起新建/空快照行一律经 report_store.insert_onhand_report 插入, + 本模块只在拿回 file_id 后按主键取回 ORM 对象并维护任务 link(关联表留在发货域)。 """ from __future__ import annotations @@ -19,36 +22,37 @@ from sqlalchemy.orm import Session from app import db from app.core.errors import AppError -from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink +from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingTaskEvent, ShippingTaskOnhandLink from app.services.shipping_notice.tool_common import task_event_task_id -from app.services.shipping_notice.inventory_file_store import ( +from app.services.freight_rpa.onhand.report_store import insert_onhand_report +from app.services.shipping_notice.onhand_file_store import ( _can_relink_inventory, generate_inventory_file_no, inventory_file_upload_path, inventory_storage_suffix_for_path, replace_task_inventory_link, ) -from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview +from app.services.shipping_notice.onhand_snapshot import read_inventory_schema_preview _SNAPSHOT_STATUS_READY = "ready" _SNAPSHOT_STATUS_EMPTY = "empty" _SNAPSHOT_STATUS_FAILED = "failed" _SNAPSHOT_STATUS_EXPIRED = "expired" -# 请求内只读缓存(key: (source_code, warehouse_id) → ShippingInventoryFile | None)。 +# 请求内只读缓存(key: (source_code, warehouse_id) → FreightRpaOnhandReportFile | None)。 # 同一请求内 _build_stp_facts / _build_stage_context / 行级匹配会重复查询同一 # (source, warehouse) 的最新 ready 快照(实测 task detail 一次请求重复 3 次)。 # 任何快照行写入(新建/过期/更新)都会由 after_flush 事件失效,保证写后读可见。 -_READ_CACHE_KEY = "shipping_inventory_snapshot_read_cache" +_READ_CACHE_KEY = "shipping_onhand_snapshot_read_cache" @_sa_event.listens_for(Session, "after_flush") def _clear_snapshot_read_cache_on_write(session, flush_context): # noqa: ANN001 """快照写入路径统一失效点:覆盖全部创建/过期/更新调用方,无需逐处接线。""" touched = ( - any(isinstance(obj, ShippingInventoryFile) for obj in session.new) - or any(isinstance(obj, ShippingInventoryFile) for obj in session.dirty) - or any(isinstance(obj, ShippingInventoryFile) for obj in session.deleted) + any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.new) + or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.dirty) + or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.deleted) ) if touched: session.info.pop(_READ_CACHE_KEY, None) @@ -80,10 +84,10 @@ def snapshot_expires_at(exported_at: datetime | None = None) -> datetime: return base + timedelta(hours=inventory_snapshot_ttl_hours()) -def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = None) -> bool: +def is_snapshot_fresh(inv_file: FreightRpaOnhandReportFile, *, now: datetime | None = None) -> bool: """ 判断库存快照是否仍处于 ready 且未过期。 - 【AI 触发时机】:ensure_inventory 决定是否复用已有快照前调用。 + 【AI 触发时机】:ensure_onhand 决定是否复用已有快照前调用。 """ if not inv_file or str(inv_file.snapshot_status or "").strip().lower() != _SNAPSHOT_STATUS_READY: return False @@ -99,7 +103,7 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = def find_latest_ready_snapshot( source_code: str | None, warehouse_id: str | None = None, -) -> ShippingInventoryFile | None: +) -> FreightRpaOnhandReportFile | None: """ 查找指定 Source 的最新 ready 且未过期库存快照。 核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。 @@ -119,14 +123,14 @@ def find_latest_ready_snapshot( if cache_key in read_cache: return read_cache[cache_key] - query = ShippingInventoryFile.query.filter_by( + query = FreightRpaOnhandReportFile.query.filter_by( source_code=code, snapshot_status=_SNAPSHOT_STATUS_READY, ) if warehouse: query = query.filter_by(warehouse_id=warehouse) - rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all() + rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc()).limit(5).all() result = None for row in rows: if is_snapshot_fresh(row): @@ -141,7 +145,7 @@ def find_ready_rpa_inventory_snapshot( rpa_run_no: str, source_code: str, warehouse_id: str, -) -> ShippingInventoryFile | None: +) -> FreightRpaOnhandReportFile | None: """ 按 RPA 轮次 + Source/Warehouse 身份查找已入库 ready 快照。 核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。 @@ -152,13 +156,13 @@ def find_ready_rpa_inventory_snapshot( if not run_no or not code or not warehouse: return None return ( - ShippingInventoryFile.query.filter_by( + FreightRpaOnhandReportFile.query.filter_by( rpa_run_no=run_no, source_code=code, warehouse_id=warehouse, snapshot_status=_SNAPSHOT_STATUS_READY, ) - .order_by(ShippingInventoryFile.id.desc()) + .order_by(FreightRpaOnhandReportFile.id.desc()) .first() ) @@ -177,13 +181,13 @@ def get_or_create_rpa_inventory_snapshot( batch_id: int | None = None, share_mode: str | None = None, verify_warehouse_id: str | None = None, -) -> tuple[ShippingInventoryFile, bool]: +) -> tuple[FreightRpaOnhandReportFile, bool]: """ 幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。 核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。 Returns: - tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。 + tuple[FreightRpaOnhandReportFile, bool]: (快照, 是否新建)。 """ from sqlalchemy.exc import IntegrityError @@ -224,7 +228,7 @@ def get_or_create_rpa_inventory_snapshot( except IntegrityError: savepoint.rollback() if orphan_storage_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(orphan_storage_path) if run_no and code and warehouse: @@ -239,7 +243,7 @@ def get_or_create_rpa_inventory_snapshot( except Exception: savepoint.rollback() if orphan_storage_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(orphan_storage_path) raise @@ -250,18 +254,18 @@ def list_available_snapshots( source_code: str | None = None, warehouse_id: str | None = None, limit: int = 20, -) -> list[ShippingInventoryFile]: +) -> list[FreightRpaOnhandReportFile]: """列出未过期 ready 快照,供工作台查询。""" - query = ShippingInventoryFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY) + query = FreightRpaOnhandReportFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY) if source_code: query = query.filter_by(source_code=str(source_code).strip().upper()) if warehouse_id: query = query.filter_by(warehouse_id=str(warehouse_id).strip().upper()) - rows = query.order_by(ShippingInventoryFile.exported_at.desc()).limit(max(limit, 1)).all() + rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc()).limit(max(limit, 1)).all() return [row for row in rows if is_snapshot_fresh(row)] -def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None: +def expire_snapshot(inv_file: FreightRpaOnhandReportFile, reason: str) -> None: """将快照标记为 expired。""" inv_file.snapshot_status = _SNAPSHOT_STATUS_EXPIRED inv_file.updated_at = datetime.utcnow() @@ -274,7 +278,7 @@ def _normalize_header_key(value: Any) -> str: def _extract_warehouse_id_from_inventory_excel(path: Path) -> str: """从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。""" - from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel + from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel values = extract_warehouse_ids_from_inventory_excel(path) if not values: @@ -298,7 +302,7 @@ def create_inventory_snapshot_from_rpa( batch_id: int | None = None, share_mode: str | None = None, verify_warehouse_id: str | None = None, -) -> ShippingInventoryFile: +) -> FreightRpaOnhandReportFile: """ 从 RPA 导出文件创建库存快照记录。 【AI 触发时机】:RPA 单条或 batch 回调成功/失败时调用;定时任务只入库不绑定发货任务。 @@ -310,7 +314,7 @@ def create_inventory_snapshot_from_rpa( success: False 时写入 failed 快照,不复制文件到标准目录。 Returns: - ShippingInventoryFile: 已持久化的快照对象。 + FreightRpaOnhandReportFile: 已持久化的快照对象。 """ exported_at = datetime.utcnow() inventory_file_no = generate_inventory_file_no() @@ -328,7 +332,7 @@ def create_inventory_snapshot_from_rpa( local = Path(local_path) # 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。 try: - from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel + from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local) if len(excel_warehouse_ids) == 1: @@ -354,10 +358,13 @@ 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_source_repository import inventory_sources_runtime_version + from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version - inv_file = ShippingInventoryFile( - inventory_file_no=inventory_file_no, + # [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit), + # 本模块只在拿到 file_id 后取回 ORM 对象;先 flush 再落盘的语义由 report_store 保持, + # 唯一约束冲突时同样不会留下已复制的孤儿文件。 + file_id = insert_onhand_report( + onhand_file_no=inventory_file_no, user_id=user_id, source_file_name=str(source_file_name or (path.name if path else "")).strip() or None, storage_path=storage_path or f"failed://{inventory_file_no}", @@ -399,9 +406,8 @@ def create_inventory_snapshot_from_rpa( "trigger_type": trigger_type, }, ) - db.session.add(inv_file) - db.session.flush() - # [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。 + inv_file = db.session.get(FreightRpaOnhandReportFile, file_id) + # [STEP] flush 已在 report_store 内完成,此处先落盘再返回:唯一约束冲突(上面 insert 抛出)时不会留下已复制的孤儿文件。 if success and storage_path and not str(storage_path).startswith("failed://"): path = Path(storage_path) path.parent.mkdir(parents=True, exist_ok=True) @@ -420,25 +426,26 @@ def create_inventory_snapshot_from_rpa( def create_empty_rpa_inventory_snapshot( *, source: dict[str, Any], rpa_run_no: str | None, schedule_run_id: int | None, trigger_type: str, message: str | None = None, -) -> ShippingInventoryFile: +) -> FreightRpaOnhandReportFile: """记录 RPA 已成功执行但没有库存行的空快照;空快照永不参与库存匹配。""" exported_at = datetime.utcnow() - from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version + from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version source_code = str(source.get('source_code') or '').strip().upper() warehouse_id = str(source.get('warehouse_id') or '').strip().upper() or None run_no = str(rpa_run_no or '').strip() or None if run_no and source_code: - existing = ShippingInventoryFile.query.filter_by( + existing = FreightRpaOnhandReportFile.query.filter_by( rpa_run_no=run_no, source_code=source_code, warehouse_id=warehouse_id, snapshot_status=_SNAPSHOT_STATUS_EMPTY, - ).order_by(ShippingInventoryFile.id.desc()).first() + ).order_by(FreightRpaOnhandReportFile.id.desc()).first() if existing is not None: return existing - inv_file = ShippingInventoryFile( - inventory_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}', + # [STEP] 阶段 B Task 5:空快照行同样经 report_store 插入(列集与原构造逐项一致;只 flush 不 commit)。 + file_id = insert_onhand_report( + onhand_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}', schema_preview_json={'export_result': 'empty', 'message': str(message or '库存查询成功但当前无库存数据')[:500]}, - share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id, + share_mode='warehouse_pool', line_count=0, onhand_lines_json=[], warehouse_id=warehouse_id, warehouse_code=warehouse_id, source_code=source_code or None, source_type=str(source.get('connector_type') or '').strip() or None, # 空快照没有可验证的行级身份;使用数据库枚举中的 unknown,避免审计入库失败。 @@ -447,41 +454,39 @@ def create_empty_rpa_inventory_snapshot( rpa_run_no=run_no, schedule_run_id=schedule_run_id, source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'}, ) - db.session.add(inv_file) - db.session.flush() - return inv_file + return db.session.get(FreightRpaOnhandReportFile, file_id) def link_snapshot_to_task( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, reason: str, role: str = "member", audit_payload: dict[str, Any] | None = None, -) -> ShippingTaskInventoryLink | None: +) -> ShippingTaskOnhandLink | None: """ 将 ready 库存快照关联到发货任务并写入审计字段。 - 【AI 触发时机】:ensure_inventory 复用快照或 RPA 回调带 task_no 时调用。 + 【AI 触发时机】:ensure_onhand 复用快照或 RPA 回调带 task_no 时调用。 Returns: - ShippingTaskInventoryLink | None: 终态任务不允许 relink 时返回 None。 + ShippingTaskOnhandLink | None: 终态任务不允许 relink 时返回 None。 """ if not _can_relink_inventory(task): return None if not is_snapshot_fresh(inv_file): return None - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(inv_file.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 + from app.services.shipping_notice.onhand_warehouse_resolution import resolve_dynamic_warehouse - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines try: lines, _column_meta = read_inventory_file_lines(inv_file) @@ -508,7 +513,7 @@ def link_snapshot_to_task( if inv_file.exported_at: age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0) - from app.services.shipping_notice.inventory_source_gate import inventory_identities_match + from app.services.shipping_notice.onhand_source_gate import inventory_identities_match identity_ok = inventory_identities_match( task, @@ -532,7 +537,7 @@ def link_snapshot_to_task( "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, + "inventory_file_no": inv_file.onhand_file_no, "trigger_type": (inv_file.source_query_json or {}).get("trigger_type"), } db.session.add( @@ -540,7 +545,7 @@ def link_snapshot_to_task( task_id=task_event_task_id(task), event_type="inventory_snapshot_linked", detail_json={ - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "link_reason": reason, "snapshot_age_seconds": age_seconds, "warehouse_id": resolved_warehouse_id, @@ -553,11 +558,11 @@ def link_snapshot_to_task( def link_snapshot_to_task_for_preparation( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, reason: str, audit_payload: dict[str, Any] | None = None, -) -> ShippingTaskInventoryLink | None: +) -> ShippingTaskOnhandLink | None: """将 RPA 已准备快照关联任务;动态仓身份待匹配时保留文件事实。 动态仓的 Warehouse 只能由下一阶段用订单键匹配库存行得出。若该匹配尚无结论, @@ -573,7 +578,7 @@ def link_snapshot_to_task_for_preparation( if link is not None: return link - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(inv_file.source_code) if ( @@ -584,7 +589,7 @@ def link_snapshot_to_task_for_preparation( ): return None - from app.services.shipping_notice.inventory_file_store import replace_task_inventory_link + from app.services.shipping_notice.onhand_file_store import replace_task_inventory_link link = replace_task_inventory_link(task, inv_file) link.link_reason = f'{reason}_pending_matching' @@ -593,7 +598,7 @@ def link_snapshot_to_task_for_preparation( link.audit_payload_json = { **(audit_payload or {}), 'source_code': inv_file.source_code, - 'inventory_file_no': inv_file.inventory_file_no, + 'inventory_file_no': inv_file.onhand_file_no, 'identity_status': inv_file.identity_status, } return link @@ -604,8 +609,8 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | if task.id is None: return None link = ( - ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True) - .order_by(ShippingTaskInventoryLink.id.desc()) + ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True) + .order_by(ShippingTaskOnhandLink.id.desc()) .first() ) if not link or not link.inventory_file: @@ -613,7 +618,7 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | inv_file = link.inventory_file trigger_type = (inv_file.source_query_json or {}).get("trigger_type") if isinstance(inv_file.source_query_json, dict) else None return { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "source_code": inv_file.source_code, "warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id, "warehouse_code": inv_file.warehouse_code, diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/onhand_source_gate.py similarity index 87% rename from backend/app/services/shipping_notice/inventory_source_gate.py rename to backend/app/services/shipping_notice/onhand_source_gate.py index 8ae4d075..a18ac272 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/onhand_source_gate.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_source_gate.py +services/shipping_notice/onhand_source_gate.py 用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。 -依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。 +依赖:onhand_source_rules、onhand_source_repository、models.ShippingOrderTask、core.errors。 逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备); apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet; 解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。 @@ -14,30 +14,31 @@ from typing import Any from app.core.errors import AppError from app.models import ShippingOrderTask -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, adjudicate_inventory_source, compute_routing_fingerprint, extract_routing_context, resolve_ambiguous_source_from_ready_snapshots, ) -from app.services.shipping_notice.inventory_candidate_freeze_service import ( +from app.services.shipping_notice.onhand_candidate_freeze_service import ( freeze_candidates_for_task, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) +# 发货通知业务错误码,族名为 SHIPPING.ONHAND_*。货代 RPA 模块错误使用 FREIGHT_RPA_*。 INVENTORY_SOURCE_ERROR_CODES = { - "unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED", - "ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS", - "invalid": "SHIPPING.INVENTORY_SOURCE_INVALID", - "conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED", - "changed": "SHIPPING.INVENTORY_SOURCE_CHANGED", - "identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH", - "gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED", + "unresolved": "SHIPPING.ONHAND_SOURCE_UNRESOLVED", + "ambiguous": "SHIPPING.ONHAND_SOURCE_AMBIGUOUS", + "invalid": "SHIPPING.ONHAND_SOURCE_INVALID", + "conflicted": "SHIPPING.ONHAND_SOURCE_CONFLICTED", + "changed": "SHIPPING.ONHAND_SOURCE_CHANGED", + "identity_mismatch": "SHIPPING.ONHAND_IDENTITY_MISMATCH", + "gate_blocked": "SHIPPING.ONHAND_SOURCE_GATE_BLOCKED", } @@ -49,10 +50,10 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool: STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。 不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。 """ - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - codes = task_frozen_inventory_source_codes(task) + codes = task_frozen_onhand_source_codes(task) lines = get_active_candidate_lines(task) if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines): return False @@ -67,7 +68,7 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool: def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool: """比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。""" - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set current = get_active_candidate_set(task) previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip() @@ -206,7 +207,7 @@ def transition_task_to_inventory_source_review( apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) # OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流, # 不能在通知准备前写入 OT。 - task.stage = "inventory_source_resolving" + task.stage = "onhand_source_resolving" task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源" payload = dict(getattr(task, 'step_payload_json', None) or {}) payload["inventory_source_resolution"] = { @@ -227,7 +228,7 @@ def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySo """ 对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。 - 【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。 + 【AI 触发时机】:confirm_parse / auto_progress / ensure_onhand 等入口发现门禁未通过时调用。 核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源自动裁决。 """ adjudication = adjudicate_and_apply_inventory_source(task) @@ -281,11 +282,11 @@ def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]: 传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。 """ - from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes task = resolve_inventory_fact_task(task) - source_codes = task_frozen_inventory_source_codes(task) + source_codes = task_frozen_onhand_source_codes(task) source_code = source_codes[0] if len(source_codes) == 1 else None source = get_database_inventory_source(source_code) if source_code else None return { @@ -309,20 +310,20 @@ def resolve_inventory_source_warehouse_id( if mode == 'fixed': return str(source.get('fixed_warehouse_id') or '').strip().upper() or None - from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task + from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task task = resolve_inventory_fact_task(task) task_id = getattr(task, 'id', None) source_code = str(source.get('source_code') or '').strip().upper() if not task_id or not source_code: return None - from app.models import ShippingTaskInventoryLink + from app.models import ShippingTaskOnhandLink - link = ShippingTaskInventoryLink.query.filter_by( + link = ShippingTaskOnhandLink.query.filter_by( task_id=int(task_id), matched_source_code=source_code, is_active=True, - ).order_by(ShippingTaskInventoryLink.id.desc()).first() + ).order_by(ShippingTaskOnhandLink.id.desc()).first() if link is None: return None return ( @@ -354,9 +355,9 @@ def inventory_identities_match( if expected_code != task_code: return False else: - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - frozen = set(task_frozen_inventory_source_codes(task)) + frozen = set(task_frozen_onhand_source_codes(task)) if expected_code not in frozen: return False diff --git a/backend/app/services/shipping_notice/inventory_source_identity.py b/backend/app/services/shipping_notice/onhand_source_identity.py similarity index 98% rename from backend/app/services/shipping_notice/inventory_source_identity.py rename to backend/app/services/shipping_notice/onhand_source_identity.py index df52a012..500e3360 100644 --- a/backend/app/services/shipping_notice/inventory_source_identity.py +++ b/backend/app/services/shipping_notice/onhand_source_identity.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_source_identity.py +services/shipping_notice/onhand_source_identity.py 用途:校验库存源与 Warehouse 的两段式身份。 依赖:无业务模块反向依赖。 diff --git a/backend/app/services/shipping_notice/inventory_source_repository.py b/backend/app/services/shipping_notice/onhand_source_repository.py similarity index 74% rename from backend/app/services/shipping_notice/inventory_source_repository.py rename to backend/app/services/shipping_notice/onhand_source_repository.py index b7ac5ae2..3063bbcc 100644 --- a/backend/app/services/shipping_notice/inventory_source_repository.py +++ b/backend/app/services/shipping_notice/onhand_source_repository.py @@ -1,18 +1,21 @@ """ -services/shipping_notice/inventory_source_repository.py +services/shipping_notice/onhand_source_repository.py 用途:提供库存源主数据的最小一致性校验和受控读取入口。 -依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。 +依赖:models.FreightRpaSource/FreightRpaProfile/FreightRpaOnhandReportConfig、core.errors.ValidationError。 逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。 + s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 配置行, + 本模块非敏感快照与运行时版本指纹均改读配置行;配置行缺失即「站点未就绪」, + 沿用返回 None 的既有跳过/失败语义,不新造错误码。 """ from __future__ import annotations from app.core.errors import ValidationError -from app.models import ShippingInventorySource, ShippingRpaProfile +from app.models import FreightRpaSource, FreightRpaProfile -def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None: +def validate_source_profile(source: FreightRpaSource, profile: FreightRpaProfile) -> None: """ 校验库存源引用的 RPA Profile 与其 Driver 类型一致。 @@ -26,11 +29,11 @@ def validate_source_profile(source: ShippingInventorySource, profile: ShippingRp 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') + raise ValidationError('Unsupported inventory connector type', code='SHIPPING.ONHAND_CONNECTOR_INVALID') if source_type != profile_type: raise ValidationError( 'Inventory Source connector_type must match its RPA Profile', - code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH', + code='SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH', ) @@ -48,7 +51,7 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True code = str(source_code or '').strip().upper() if not code: return None - source = ShippingInventorySource.query.filter_by(source_code=code).first() + source = FreightRpaSource.query.filter_by(source_code=code).first() if source is None or (enabled_only and not source.enabled): return None profile = source.rpa_profile @@ -57,9 +60,14 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True login_config = dict(profile.login_config_json or {'auth_mode': 'password'}) if login_config.get('auth_mode') != 'password': return None + # s18 起报表路径/查询条件/解析方案绑定归 onhand_report_config 配置行; + # 配置行缺失即「站点未就绪」,沿用返回 None 的既有跳过/失败语义,不新造错误码。 + config = source.onhand_report_config + if config is None: + 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 {} + source_navigation = dict(config.report_path_json or {}) if source.connector_type == 'dbs' else {} return { 'source_code': source.source_code, 'display_name': source.display_name, @@ -70,17 +78,17 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True '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, + 'parsing_profile_id': config.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 []), + 'report_path_json': dict(config.report_path_json or {}), + 'query_parameters_json': list(config.query_parameters_json or []), 'rpa_profile_code': profile.profile_code, # 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页, # 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。 'upload_config_json': profile.upload_config_json, # 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。 'navigation': source_navigation, - 'parameters': list(source.query_parameters_json or []), + 'parameters': list(config.query_parameters_json or []), 'query': {}, 'login_url': profile.login_url, 'login_config': login_config, @@ -92,7 +100,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T 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() + source = FreightRpaSource.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 @@ -106,7 +114,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]: """列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。""" - query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code) + query = FreightRpaSource.query.order_by(FreightRpaSource.source_code) if enabled_only: query = query.filter_by(enabled=True) result = [] @@ -123,8 +131,10 @@ def inventory_sources_runtime_version() -> str: import json rows = [] - for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all(): + for source in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all(): profile = source.rpa_profile + # s18 起报表路径/查询条件归 onhand_report_config 配置行;配置行缺失按空配置参与指纹。 + config = source.onhand_report_config rows.append({ 'source_code': source.source_code, 'source_version': source.config_version, @@ -136,8 +146,8 @@ def inventory_sources_runtime_version() -> str: '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 [], + 'report_path_json': (config.report_path_json or {}) if config is not None else {}, + 'query_parameters_json': (config.query_parameters_json or []) if config is not None else [], 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, }, 'profile_config': { diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/onhand_source_rules.py similarity index 92% rename from backend/app/services/shipping_notice/inventory_source_rules.py rename to backend/app/services/shipping_notice/onhand_source_rules.py index 44e34072..fccde009 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/onhand_source_rules.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_source_rules.py +services/shipping_notice/onhand_source_rules.py 用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。 -依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。 +依赖:onhand_routing_engine、onhand_source_repository、order_field_purposes。 逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行; 行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源; Warehouse 由 Source/匹配决定。 @@ -18,9 +18,9 @@ from typing import Any from app import db from app.models import ShippingNotice, ShippingOrderSnapshot -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 ( +from app.services.shipping_notice.onhand_routing_engine import evaluate_inventory_source_rules +from app.services.shipping_notice.onhand_source_identity import resolve_inventory_source_identity +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, list_database_inventory_sources, @@ -181,8 +181,8 @@ def resolve_ambiguous_source_from_ready_snapshots( if len(order_keys) != len(order_lines): return adjudication - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines - from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot matched: list[tuple[dict[str, Any], Any]] = [] checked: list[dict[str, Any]] = [] @@ -206,7 +206,7 @@ def resolve_ambiguous_source_from_ready_snapshots( is_match = order_keys.issubset(inventory_keys) checked.append({ 'source_code': source_code, - 'inventory_file_no': snapshot.inventory_file_no, + 'inventory_file_no': snapshot.onhand_file_no, 'matched': is_match, }) if is_match: @@ -236,7 +236,7 @@ def resolve_ambiguous_source_from_ready_snapshots( candidates=adjudication.candidates, destination_candidates=adjudication.destination_candidates, evidence=evidence, - reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}', + reason=f'unique_ready_snapshot:{snapshot.onhand_file_no}', ) @@ -288,9 +288,9 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None: """按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。""" - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - for code in task_frozen_inventory_source_codes(task): + for code in task_frozen_onhand_source_codes(task): item = get_database_inventory_source(code) if item is not None: return item @@ -299,7 +299,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None: def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None: """持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。""" - from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication del source selected = resolution or adjudicate_inventory_source(task) @@ -308,6 +308,6 @@ def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None: """兼容旧入口,写入规则裁决候选;不触发人工库存源确认。""" - from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication apply_inventory_source_adjudication(task, resolution) diff --git a/backend/app/services/shipping_notice/inventory_structure_analysis.py b/backend/app/services/shipping_notice/onhand_structure_analysis.py similarity index 87% rename from backend/app/services/shipping_notice/inventory_structure_analysis.py rename to backend/app/services/shipping_notice/onhand_structure_analysis.py index 46b1f6fd..858df483 100644 --- a/backend/app/services/shipping_notice/inventory_structure_analysis.py +++ b/backend/app/services/shipping_notice/onhand_structure_analysis.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_structure_analysis.py +services/shipping_notice/onhand_structure_analysis.py 用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。 -依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。 +依赖:openpyxl、onhand_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。 逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。 """ @@ -24,11 +24,11 @@ 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 ( +from app.models import FreightRpaOnhandField, FreightRpaParsingProfile, FreightRpaOnhandStructureAnalysis +from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix +from app.services.shipping_notice.onhand_mapping import suggest_field_mapping +from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index +from app.services.shipping_notice.onhand_structure_fingerprint import ( compatibility_fingerprint, exact_fingerprint, normalise_header, @@ -44,8 +44,8 @@ _SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', ' def _has_required_suggestions(mapping: dict[str, str]) -> bool: """确认自动建议至少覆盖一个匹配字段和一个库存数量字段。""" - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([ + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.status == 'active', FreightRpaOnhandField.id.in_([ int(field_id) for field_id in mapping if str(field_id).isdigit() ]), ).all() if mapping else [] @@ -118,7 +118,7 @@ def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[di """生成来源栏位的业务预览,包括样例、空值率和建议字段。""" suggestions = suggest_field_mapping(headers, as_catalog=True) catalog = { - str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all() + str(item.id): item for item in FreightRpaOnhandField.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) @@ -206,7 +206,7 @@ def _build_workbook_structure( if headers: candidates.append(candidate) if not candidates: - raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') # Prefer a populated detail sheet over a same-score cover/summary sheet. selected = max(candidates, key=lambda item: ( item['score'], item['sample_row_count'], sum(1 for header in item['headers'] if header), @@ -259,9 +259,9 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str 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 + raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc if not rows: - raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory file is empty', code='SHIPPING.ONHAND_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] @@ -294,10 +294,10 @@ def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, st return _xls_structure(path) if suffix == '.csv': return _csv_structure(path) - raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory file format is unsupported', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') -def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]: +def serialize_analysis(item: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]: """输出管理端需要的分析结果,不暴露服务器存储路径。""" return { 'id': item.id, @@ -319,13 +319,13 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An 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') + raise ValidationError('Inventory sample file is required', code='SHIPPING.ONHAND_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') + raise ValidationError('Inventory sample file is too large', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_TOO_LARGE') if not raw: - raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory sample file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') analysis_dir = _analysis_root() / uuid.uuid4().hex analysis_dir.mkdir(parents=True, exist_ok=False) path = analysis_dir / f'sample{suffix}' @@ -337,13 +337,13 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> 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 + raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.ONHAND_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( + item = FreightRpaOnhandStructureAnalysis( source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary, @@ -355,7 +355,7 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> ) db.session.add(item) db.session.flush() - from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles item.match_result_json = recommend_profiles({ 'structure': structure, @@ -373,22 +373,22 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> def get_analysis(analysis_id: int) -> dict[str, Any]: """读取既有结构分析,供管理员选择工作表、表头和来源栏位。""" - item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + item = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if item is None: - raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND') return serialize_analysis(item) def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: dict[str, Any] | None = None) -> dict[str, Any]: """比较草稿当前样本和候选样本,明确列出需要管理员确认的结构变化。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'draft': - raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE') + raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE') if analysis is None or analysis.analysis_status != 'ready': - raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED') + raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED') previous = profile.sample_analysis old_headers = list((previous.structure_json or {}).get('selected_headers') or []) if previous else [] new_headers = list((analysis.structure_json or {}).get('selected_headers') or []) @@ -419,14 +419,14 @@ def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: 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) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if analysis is None: - raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') - existing_profile = db.session.get(ShippingInventoryParsingProfile, data.get('profile_id')) if data.get('profile_id') else None + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND') + existing_profile = db.session.get(FreightRpaParsingProfile, data.get('profile_id')) if data.get('profile_id') else None if existing_profile is not None and existing_profile.file_format != analysis.file_format: raise ValidationError( 'Draft parsing profile file format is immutable', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) 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 @@ -436,21 +436,21 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in 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') + raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.ONHAND_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') + raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.ONHAND_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 + raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID') + from app.services.shipping_notice import onhand_parsing_profile - saved = inventory_parsing_profile.save_draft({ + saved = onhand_parsing_profile.save_draft({ 'profile_code': data.get('profile_code'), 'display_name': data.get('display_name'), # 用途随请求透传(缺省沿用既有草稿/默认 onhand):inbound 草稿端点为定死领域字段。 @@ -465,7 +465,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in 'match_keys': data.get('match_keys'), }, }, actor_id=actor_id, profile_id=data.get('profile_id')) - profile = db.session.get(ShippingInventoryParsingProfile, saved['id']) + profile = db.session.get(FreightRpaParsingProfile, 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', [])], @@ -478,17 +478,17 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in ) profile.fingerprint_version = selected_definition['fingerprint_version'] db.session.commit() - return inventory_parsing_profile.payload(profile) + return onhand_parsing_profile.payload(profile) def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]: """确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。""" - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, 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) + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND') + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None or profile.status != 'published': - raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_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( @@ -496,7 +496,7 @@ def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any] 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') + raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID') analysis.match_result_json = { **match, 'adopted_profile_id': profile.id, diff --git a/backend/app/services/shipping_notice/inventory_structure_drift.py b/backend/app/services/shipping_notice/onhand_structure_drift.py similarity index 77% rename from backend/app/services/shipping_notice/inventory_structure_drift.py rename to backend/app/services/shipping_notice/onhand_structure_drift.py index b292b828..142fb2cc 100644 --- a/backend/app/services/shipping_notice/inventory_structure_drift.py +++ b/backend/app/services/shipping_notice/onhand_structure_drift.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_structure_drift.py +services/shipping_notice/onhand_structure_drift.py 用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。 依赖:库存源/解析方案模型、库存结构分析和方案复用服务。 @@ -12,7 +12,7 @@ from pathlib import Path from typing import Any from app.core.errors import ConflictError -from app.models import ShippingInventorySource +from app.models import FreightRpaSource def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]: @@ -28,20 +28,22 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) -> 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 + source = FreightRpaSource.query.filter_by(source_code=str(source_code or '').strip().upper()).first() + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = source.onhand_report_config if source is not None else None + profile = config.parsing_profile if config 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') + raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.ONHAND_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 + from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix + from app.services.shipping_notice.onhand_structure_analysis import _analyse_path + from app.services.shipping_notice.onhand_structure_fingerprint import exact_fingerprint, structure_definition + from app.services.shipping_notice.onhand_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') + raise ConflictError('Inventory file format changed', code='SHIPPING.ONHAND_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') @@ -53,14 +55,14 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) -> if selected is None: raise ConflictError( 'Configured inventory worksheet or header row is unavailable', - code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED', + code='SHIPPING.ONHAND_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 + from app.services.shipping_notice.onhand_mapping import suggest_field_mapping suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True) definition = structure_definition( @@ -79,7 +81,7 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) -> if candidate is None: raise ConflictError( 'Inventory file structure is incompatible with the bound parsing profile', - code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED', + code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED', details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings}, ) return { diff --git a/backend/app/services/shipping_notice/inventory_structure_fingerprint.py b/backend/app/services/shipping_notice/onhand_structure_fingerprint.py similarity index 91% rename from backend/app/services/shipping_notice/inventory_structure_fingerprint.py rename to backend/app/services/shipping_notice/onhand_structure_fingerprint.py index 13eaf036..5bda791d 100644 --- a/backend/app/services/shipping_notice/inventory_structure_fingerprint.py +++ b/backend/app/services/shipping_notice/onhand_structure_fingerprint.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_structure_fingerprint.py +services/shipping_notice/onhand_structure_fingerprint.py 用途:为库存文件结构和解析定义生成稳定、可审计的指纹。 -依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。 +依赖:标准 hashlib/json/unicodedata;输入来自 onhand_structure_analysis 与 onhand_parsing_profile。 逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。 """ @@ -47,7 +47,7 @@ def exact_fingerprint(definition: dict[str, Any]) -> str: 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 + from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids runtime_mapping, catalog = runtime_field_mapping(field_mapping) usages = usage_field_ids() diff --git a/backend/app/services/shipping_notice/inventory_temporary_session.py b/backend/app/services/shipping_notice/onhand_temporary_session.py similarity index 81% rename from backend/app/services/shipping_notice/inventory_temporary_session.py rename to backend/app/services/shipping_notice/onhand_temporary_session.py index 314904b2..8b9a6007 100644 --- a/backend/app/services/shipping_notice/inventory_temporary_session.py +++ b/backend/app/services/shipping_notice/onhand_temporary_session.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_temporary_session.py +services/shipping_notice/onhand_temporary_session.py 用途:处理对话上传库存候选文件的身份初检与临时会话状态。 依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。 @@ -24,33 +24,33 @@ from app.models import ( Agent, ChatSession, FileAsset, - ShippingInventoryStructureAnalysis, - ShippingTemporaryInventorySession, - ShippingInventoryField, - ShippingInventoryParsingProfile, + FreightRpaOnhandStructureAnalysis, + ShippingTemporaryOnhandSession, + FreightRpaOnhandField, + FreightRpaParsingProfile, ) 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 ( +from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix +from app.services.shipping_notice.onhand_structure_analysis import ( MAX_UPLOAD_BYTES, _analyse_path, _analysis_root, _safe_filename, serialize_analysis, ) -from app.services.shipping_notice.inventory_structure_fingerprint import ( +from app.services.shipping_notice.onhand_structure_fingerprint import ( compatibility_fingerprint, exact_fingerprint, structure_definition, ) -from app.services.shipping_notice.inventory_mapping import ( +from app.services.shipping_notice.onhand_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 +from app.services.shipping_notice.onhand_snapshot import parse_inventory_excel_with_meta _CONTEXT_PATHS = ['agent_code', 'platform.session_id'] _TTL_HOURS = 24 @@ -59,7 +59,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession: 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') + raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID') session_id = str(values.get('platform.session_id') or '').strip() session = ( db.session.query(ChatSession) @@ -68,7 +68,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession: .one_or_none() ) if session is None: - raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID') + raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID') return session @@ -77,9 +77,9 @@ def _session_no() -> str: return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}' -def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]: +def _serialize(item: ShippingTemporaryOnhandSession) -> dict[str, Any]: """输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。""" - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None return { 'session_no': item.session_no, 'status': item.status, @@ -101,19 +101,19 @@ def _available_inventory_fields() -> list[dict[str, Any]]: '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, + } for item in FreightRpaOnhandField.query.filter_by(status='active').order_by( + FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id, ).all()] -def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None: +def _mapping_suggestion(item: ShippingTemporaryOnhandSession) -> 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: +def _confirmed_usage(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None: """输出已确认的临时使用摘要,不返回库存行或文件内部路径。""" result = item.result_json if isinstance(item.result_json, dict) else {} value = result.get('confirmed_usage') @@ -128,7 +128,7 @@ def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] } -def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]: +def _serialize_dify_analysis_preview(analysis: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]: """返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。""" preview = copy.deepcopy(serialize_analysis(analysis)) structure = preview.get('structure') @@ -146,12 +146,12 @@ def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysi return preview -def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis: +def _persist_analysis(*, asset: FileAsset, owner_id: int) -> FreightRpaOnhandStructureAnalysis: """对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。""" 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', + code='SHIPPING.TEMP_ONHAND_FILE_TOO_LARGE', ) suffix = resolve_inventory_upload_suffix(asset.original_filename) raw = read_asset_bytes(asset) @@ -168,7 +168,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt shutil.rmtree(analysis_dir, ignore_errors=True) raise ValidationError( 'Temporary inventory file cannot be analysed', - code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID', + code='SHIPPING.TEMP_ONHAND_ANALYSIS_INVALID', ) from exc # 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。 suggested, _catalog = runtime_field_mapping(suggested_catalog) @@ -177,7 +177,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []), ) - analysis = ShippingInventoryStructureAnalysis( + analysis = FreightRpaOnhandStructureAnalysis( 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, @@ -189,7 +189,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt ) db.session.add(analysis) db.session.flush() - from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles analysis.match_result_json = recommend_profiles({ 'structure': structure, @@ -200,7 +200,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt return analysis -def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]: +def _classify(analysis: FreightRpaOnhandStructureAnalysis) -> 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 [] @@ -230,27 +230,27 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any 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') + raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_ONHAND_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') + raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_ONHAND_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') + raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_ONHAND_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 + raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_ONHAND_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_([ + active = ShippingTemporaryOnhandSession.query.filter( + ShippingTemporaryOnhandSession.user_id == session.user_id, + ShippingTemporaryOnhandSession.conversation_id == session.session_id, + ShippingTemporaryOnhandSession.asset_id == asset.id, + ShippingTemporaryOnhandSession.status.in_([ 'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion', 'awaiting_mapping_confirmation', ]), - ShippingTemporaryInventorySession.expires_at > datetime.utcnow(), - ).order_by(ShippingTemporaryInventorySession.id.desc()).first() + ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(), + ).order_by(ShippingTemporaryOnhandSession.id.desc()).first() if active: return _serialize(active) @@ -262,7 +262,7 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any 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( + item = ShippingTemporaryOnhandSession( 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, @@ -291,11 +291,11 @@ def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]: """ session = _runtime_session(payload.get('agent_runtime_context')) session_no = str(payload.get('temporary_session_no') or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by( + item = ShippingTemporaryOnhandSession.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') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND') if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}: item.status = 'expired' db.session.commit() @@ -317,31 +317,31 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di """ session = _runtime_session(payload.get('agent_runtime_context')) session_no = str(payload.get('temporary_session_no') or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by( + item = ShippingTemporaryOnhandSession.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') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_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') + raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_ONHAND_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') + raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_ONHAND_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 + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, 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') + raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_ONHAND_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}, + code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID', details={'errors': errors}, ) item.result_json = { **(item.result_json if isinstance(item.result_json, dict) else {}), @@ -353,19 +353,19 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di def _select_confirmed_mapping( - item: ShippingTemporaryInventorySession, + item: ShippingTemporaryOnhandSession, *, 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 + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, 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') + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_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 + raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_ONHAND_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')) @@ -373,17 +373,17 @@ def _select_confirmed_mapping( and str(candidate.get('level') or '') == 'exact' and str(candidate.get('profile_id') or '').isdigit() } - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, 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') + raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_ONHAND_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') + raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') return dict(mapping), 'dify_candidate', None - raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]: @@ -419,7 +419,7 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: 【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。 核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁; - 只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。 + 只写临时会话审计,不创建 FreightRpaOnhandReportFile、不修改库存站点、不回填任务库存行、不执行匹配。 Args: payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。 @@ -429,19 +429,19 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: """ session = _runtime_session(payload.get('agent_runtime_context')) session_no = str(payload.get('temporary_session_no') or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by( + item = ShippingTemporaryOnhandSession.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') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_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') + raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_ONHAND_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 + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, 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') + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} try: lines, column_meta = parse_inventory_excel_with_meta( @@ -449,10 +449,10 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: 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 + raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_ONHAND_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}) + raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID', details={'quality': quality}) item.task_id = None item.result_json = { **(item.result_json if isinstance(item.result_json, dict) else {}), @@ -470,12 +470,12 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]: """返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。""" - rows = ShippingTemporaryInventorySession.query.filter_by( + rows = ShippingTemporaryOnhandSession.query.filter_by( status='confirmed_for_temporary_use', - ).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all() + ).order_by(ShippingTemporaryOnhandSession.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 + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None confirmed = _confirmed_usage(item) result.append({ 'session_no': item.session_no, @@ -513,24 +513,24 @@ def create_parsing_profile_draft_from_temporary_session( 新建的库存文件解析方案草稿。 """ normalized_no = str(session_no or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none() + item = ShippingTemporaryOnhandSession.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') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND') if item.status != 'confirmed_for_temporary_use': - raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_ONHAND_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') + raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_ONHAND_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) + existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id) if existing_draft is not None: - from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload + from app.services.shipping_notice.onhand_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 + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, 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') + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID') structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} payload = { 'profile_code': data.get('profile_code'), @@ -540,9 +540,9 @@ def create_parsing_profile_draft_from_temporary_session( 'field_mapping': confirmed['field_mapping'], 'match_keys': data.get('match_keys'), } - from app.services.shipping_notice import inventory_structure_analysis + from app.services.shipping_notice import onhand_structure_analysis - draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id) + draft = onhand_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'], diff --git a/backend/app/services/shipping_notice/onhand_trigger_batch.py b/backend/app/services/shipping_notice/onhand_trigger_batch.py index 857c500f..0a33be48 100644 --- a/backend/app/services/shipping_notice/onhand_trigger_batch.py +++ b/backend/app/services/shipping_notice/onhand_trigger_batch.py @@ -4,10 +4,13 @@ services/shipping_notice/onhand_trigger_batch.py 用途:onhand(在手库存)RPA 的批量/按需导出编排——组装逐源凭据与身份键、写批量 trigger、 单票按需触发的 fail-closed 入口。 依赖:Flask current_app 配置、freight_rpa.onhand.trigger_io(目录解析/原子写/SCHEMA/ACTION 常量)、 - shipping_notice.inventory_source_repository(按源补 Profile 密文,函数内延迟 import)。 -逻辑:由 schedule.freight_onhand_rpa_job(定时批量)、inventory_configuration_test(配置测试)、 - inventory_rpa_workflow / per_source_rpa_service(按需触发)调用, + shipping_notice.onhand_source_repository(按源补 Profile 密文,函数内延迟 import)。 +逻辑:由 schedule.freight_rpa_onhand_job(定时批量)、onhand_configuration_test(配置测试)、 + onhand_rpa_workflow / per_source_rpa_service(按需触发)调用, 与 freight_rpa.onhand.trigger_io 的纯文件 IO 分层:本文件管业务编排,目录与 JSON 原子写下沉包内。 + s18 起 report_path_json / query_parameters_json / parsing_profile_id 改由仓库快照取自 + source.onhand_report_config 配置行(navigation/parameters 由此派生);配置行缺失时 + 仓库返回 None,沿用「站点未就绪」的跳过/回退语义,不新造错误码。 """ from __future__ import annotations @@ -53,11 +56,14 @@ def write_inventory_export_batch_trigger( 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 + from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'} trigger_source = get_rpa_trigger_inventory_source( str(source["source_code"]), enabled_only=not configuration_test, ) or source + # s18 起合并进来的 report_path_json / query_parameters_json / parsing_profile_id + # 均取自 source.onhand_report_config 配置行(仓库快照),配置缺失时上面已回退到 + # 调用方传入的非敏感快照,沿用「站点未就绪」既有语义。 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) @@ -106,11 +112,11 @@ def write_inventory_export_batch_trigger( return str(path) -def inventory_rpa_batch_enabled() -> bool: +def onhand_rpa_batch_enabled() -> bool: """是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。""" - raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED") + raw = current_app.config.get("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED") if raw is None: - raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true") + raw = os.getenv("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED", "true") return str(raw).strip().lower() in {"1", "true", "yes", "on"} @@ -133,7 +139,7 @@ def build_on_demand_inventory_trigger_source( Returns: 可直接传入 write_inventory_export_batch_trigger 的单源条目。 """ - from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source + from app.services.shipping_notice.onhand_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 @@ -178,7 +184,7 @@ def write_inventory_export_trigger_for_task( 不再生成 legacy inventory_export trigger。 """ body = dict(payload or {}) - if inventory_rpa_batch_enabled(): + if onhand_rpa_batch_enabled(): run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}") source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body) return write_inventory_export_batch_trigger( @@ -193,5 +199,5 @@ def write_inventory_export_trigger_for_task( ) raise ValidationError( 'shipping inventory RPA v2 batch trigger is required', - code='SHIPPING.INVENTORY_RPA_V2_REQUIRED', + code='SHIPPING.ONHAND_RPA_V2_REQUIRED', ) diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/onhand_upload.py similarity index 95% rename from backend/app/services/shipping_notice/inventory_upload.py rename to backend/app/services/shipping_notice/onhand_upload.py index 5de59882..b9d2f74a 100644 --- a/backend/app/services/shipping_notice/inventory_upload.py +++ b/backend/app/services/shipping_notice/onhand_upload.py @@ -1,9 +1,9 @@ """ -services/shipping_notice/inventory_upload.py +services/shipping_notice/onhand_upload.py 用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。 -依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。 -逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息; +依赖:onhand_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。 +逻辑:由 onhand_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息; 正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。 """ @@ -19,9 +19,9 @@ from typing import Any from flask import current_app from werkzeug.datastructures import FileStorage -from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask +from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask 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.onhand_file_store import inventory_storage_suffix_for_path _TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv") _TASK_INVENTORY_MARKER = ".current_inventory" _TASK_INVENTORY_VERSION_PREFIX = "inventory_" @@ -164,7 +164,7 @@ def install_task_inventory_attachment_from_file( def rebuild_task_inventory_attachment_from_snapshot( task: ShippingOrderTask | ShippingNotice | str, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, ) -> Path: """ 从已提交库存快照 storage_path 幂等重建任务正式附件。 @@ -183,7 +183,7 @@ def rebuild_task_inventory_attachment_from_snapshot( storage_path = Path(str(inv_file.storage_path or "")) if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"): raise FileNotFoundError( - f"库存快照托管文件不存在: {inv_file.inventory_file_no}", + f"库存快照托管文件不存在: {inv_file.onhand_file_no}", ) return install_task_inventory_attachment_from_file( task_no, diff --git a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py b/backend/app/services/shipping_notice/onhand_warehouse_resolution.py similarity index 78% rename from backend/app/services/shipping_notice/inventory_warehouse_resolution.py rename to backend/app/services/shipping_notice/onhand_warehouse_resolution.py index f5e16c2b..9250a723 100644 --- a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py +++ b/backend/app/services/shipping_notice/onhand_warehouse_resolution.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_warehouse_resolution.py +services/shipping_notice/onhand_warehouse_resolution.py 用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。 -依赖:ShippingInventoryField/Source、动态订单字段投影。 +依赖:FreightRpaOnhandField/Source、动态订单字段投影。 逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。 """ @@ -11,7 +11,7 @@ from __future__ import annotations from dataclasses import dataclass from typing import Any -from app.models import ShippingInventoryField, ShippingInventorySource +from app.models import FreightRpaOnhandField, FreightRpaSource from app.services.shipping_notice.export import order_field_id_values @@ -31,8 +31,11 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution: """按站点已发布解析方案为全部订单行寻找唯一 Warehouse。""" - source = ShippingInventorySource.query.filter_by(source_code=source_code).first() - definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} + source = FreightRpaSource.query.filter_by(source_code=source_code).first() + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = source.onhand_report_config if source is not None else None + profile = config.parsing_profile if config is not None else None + definition = profile.definition_json if profile is not None 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)] @@ -40,9 +43,9 @@ def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any] 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', + warehouse_fields = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(mapped_ids), FreightRpaOnhandField.status == 'active', + FreightRpaOnhandField.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') diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/onhand_workflow.py similarity index 89% rename from backend/app/services/shipping_notice/inventory_workflow.py rename to backend/app/services/shipping_notice/onhand_workflow.py index fe422e11..e66187d7 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/onhand_workflow.py @@ -1,11 +1,11 @@ """ -services/shipping_notice/inventory_workflow.py +services/shipping_notice/onhand_workflow.py -用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。 -依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、 - inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。 +用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 onhand_rpa_workflow。 +依赖:customer_identity_gate、reservation_gate、onhand_file_store、onhand_mapping_workflow、 + onhand_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。 逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除; - payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓); + payload.source_codes 可收窄 ensure_inventory(持久化阶段码 ensure_onhand)/ RPA 作用源(行级重抓); STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File; 动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。 """ @@ -21,8 +21,8 @@ from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( POSITION_INVENTORY_SOURCE_REVIEW, ) -from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response -from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload +from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response +from app.services.shipping_notice.onhand_file_store import save_task_inventory_upload from app.services.shipping_notice.query_service import ( get_task_by_ref, resolve_task_from_payload, @@ -31,7 +31,7 @@ from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues from app.services.shipping_notice.task_field_gate import field_conflict_gate_response from app.services.shipping_notice.i18n import resolve_lang, t -from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -67,20 +67,20 @@ def _link_ready_candidate_prep_or_block( 核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded 快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定 - (pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成 + (pending_matching),仓/匹配问题留给 onhand_matching,禁止把「有文件」投影成 inventory_file_missing。仅当真的无法绑定文件时才 needs_human。 Args: task: 已冻结候选源的订单任务。 - prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。 + prep: ``prepare_candidate_onhand_lines`` 的 ready 结果。 lang: 文案语言。 Returns: None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。 """ - from app.models import ShippingInventoryFile - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task - from app.services.shipping_notice.inventory_snapshot_store import ( + from app.models import FreightRpaOnhandReportFile + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_snapshot_store import ( link_snapshot_to_task_for_preparation, ) @@ -107,7 +107,7 @@ def _link_ready_candidate_prep_or_block( break inv_file = ( - ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first() + FreightRpaOnhandReportFile.query.filter_by(onhand_file_no=file_no).first() if file_no else None ) @@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block( apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='needs_human', message=t('workflow.inventory.unavailable', lang=lang), @@ -221,10 +221,10 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, reservation_gate = _reservation_gate_response(task, lang=lang) if reservation_gate is not None: return reservation_gate - if operation == "ensure_inventory": + if operation == "ensure_onhand": # [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或 # 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。 - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, get_active_candidate_sources, @@ -251,7 +251,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, message="库存源候选集尚未冻结完成,暂不能准备库存。", data={ **serialize_task_for_tool(task), - "error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED", + "error_code": "SHIPPING.ONHAND_SOURCE_ROUTING_REQUIRED", "position": POSITION_INVENTORY_SOURCE_REVIEW, }, position=POSITION_INVENTORY_SOURCE_REVIEW, @@ -281,7 +281,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh")) lang = resolve_lang({"lang": None}) - gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang) + gate_resp = _inventory_source_gate_response(task, operation="upload_onhand_file", lang=lang) if gate_resp is not None: return gate_resp from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success @@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: try: set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message=t("workflow.inventory.uploading", lang=lang), @@ -322,13 +322,13 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: db.session.flush() inv_file = save_task_inventory_upload(task, upload) inventory_lines = [ - item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict) + item for item in (inv_file.onhand_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': + if exc.code == 'SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED': message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。' return tool_response( status="failed", @@ -362,7 +362,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: task, "inventory_snapshot_created", { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "share_mode": inv_file.share_mode, }, ) @@ -397,7 +397,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: task_no, trigger=trigger, expected_version=None, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, - resume_gate_code='inventory_preparation', + resume_gate_code='onhand_preparation', operator_id=operator_id, inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto', line_scope_key=( @@ -415,7 +415,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) # [STEP 0] 与 parse/upload 共用客户、Reservation、库存源门禁,避免旁路入口绕过订单侧闸门。 - gate_resp = _inventory_source_gate_response(task, operation="ensure_inventory", lang=lang) + gate_resp = _inventory_source_gate_response(task, operation="ensure_onhand", lang=lang) if gate_resp is not None: return gate_resp @@ -441,27 +441,27 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 2] 正常流程优先复用已完成的库存快照;缺少快照时自动进入库存 RPA。 if mode == "retry_rpa": - from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa return ensure_inventory_via_rpa( task, mode=mode, source_codes=scoped_source_codes, ) 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 - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines + from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines # [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。 - frozen_codes = task_frozen_inventory_source_codes(task) + frozen_codes = task_frozen_onhand_source_codes(task) if len(frozen_codes) >= 1: - prep = prepare_candidate_inventory_lines(task) + prep = prepare_candidate_onhand_lines(task) if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing': apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), @@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: task.error_message = None set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message="已触发库存获取,等待各库存源回调。", @@ -521,7 +521,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) if probe.all_prepared: # 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。 - prep = prepare_candidate_inventory_lines(task) + prep = prepare_candidate_onhand_lines(task) else: # 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。 log_task_event(task, "inventory_probe_failed", { @@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message="库存 RPA 未能为全部库存源生成结果。", @@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), @@ -599,7 +599,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 库存源已确定但没有可复用快照时,自动推进必须启动一次 RPA, # 否则任务会错误停在人审且没有可执行的恢复动作。 - from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa return ensure_inventory_via_rpa( task, @@ -610,7 +610,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。 # 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。 - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if has_ready_inventory_file_for_task(task): apply_task_transition(task, TaskTransition.INVENTORY_READY) @@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index 7754ad4c..b6118190 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -4,9 +4,9 @@ services/shipping_notice/order_build_eligibility_service.py 用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及 Candidate Qualification 统一自动建单检查。 依赖:candidate_qualification_service(含 confidence_policy)、candidate_validation、field_rules、 - inventory_routing_engine、inventory_source_repository、 + onhand_routing_engine、onhand_source_repository、 ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、 - ShippingInventorySource、process_gate_contract(原因唯一归属)。 + FreightRpaSource、process_gate_contract(原因唯一归属)。 逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费); 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; 停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选, @@ -20,7 +20,7 @@ from __future__ import annotations from typing import Any -from app.models import ShippingInventorySource +from app.models import FreightRpaSource from app.services.shipping_notice.candidate_qualification_contract import ( CANDIDATE_QUALIFICATION_GATE_KEYS, CANDIDATE_QUALIFICATION_GATE_REASON_CODES, @@ -30,11 +30,11 @@ from app.services.shipping_notice.candidate_qualification_service import ( ) from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.error_explainability_contract import build_explainability_reason -from app.services.shipping_notice.inventory_routing_engine import ( +from app.services.shipping_notice.onhand_routing_engine import ( InventoryRoutingResult, evaluate_inventory_source_rules_for_field_values, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, list_database_inventory_sources, ) @@ -175,7 +175,7 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]: reasons: dict[str, str] = {} for code in _normalize_manual_codes(codes): # [STEP 1] 源不存在 - source = ShippingInventorySource.query.filter_by(source_code=code).first() + source = FreightRpaSource.query.filter_by(source_code=code).first() if source is None: unavailable.append(code) reasons[code] = 'source_not_found' @@ -197,8 +197,9 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]: unavailable.append(code) reasons[code] = 'source_runtime_unavailable' continue - # [STEP 5] 解析 Profile 未发布 - parsing = source.parsing_profile + # [STEP 5] 解析 Profile 未发布(s18 起绑定归 onhand_report_config 配置行;配置行缺失即未绑定) + config = source.onhand_report_config + parsing = config.parsing_profile if config is not None else None if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published': unavailable.append(code) reasons[code] = 'parsing_profile_unavailable' @@ -539,7 +540,7 @@ def assess_order_build_eligibility( 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'severity': 'blocking', - 'owning_gate_code': 'inventory_source_routing', + 'owning_gate_code': 'onhand_source_routing', 'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [], 'unavailable_source_codes': routing.get('unavailable_source_codes') or [], 'unavailable_reasons': routing.get('unavailable_reasons') or {}, @@ -578,7 +579,7 @@ def assess_order_build_eligibility( # 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。 build_blocking_issues = [ item for item in issues - if str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + if str(item.get('owning_gate_code') or '') != 'onhand_source_routing' ] can_build = ( bool(customer_resolved) diff --git a/backend/app/services/shipping_notice/order_candidate_builder.py b/backend/app/services/shipping_notice/order_candidate_builder.py index 2f314362..e51bcbc3 100644 --- a/backend/app/services/shipping_notice/order_candidate_builder.py +++ b/backend/app/services/shipping_notice/order_candidate_builder.py @@ -12,7 +12,7 @@ import re from decimal import Decimal, InvalidOperation from typing import Any -from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text +from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text from app.services.shipping_notice.notice_line_table import ( find_notice_header_row_index, parse_notice_row, diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 9b57481f..d73c2852 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -16,7 +16,7 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py 豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束; 新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照 Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的 - 正式 inventory_source_routing Gate 负责; + 正式 onhand_source_routing Gate 负责; 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox), @@ -1440,7 +1440,7 @@ def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bo upload_status = getattr(latest_upload_attempt(task), 'status', None) # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_for_task, has_ready_inventory_file_for_task, ) diff --git a/backend/app/services/shipping_notice/order_review_draft_service.py b/backend/app/services/shipping_notice/order_review_draft_service.py index 8ad0f96f..43eb9bb5 100644 --- a/backend/app/services/shipping_notice/order_review_draft_service.py +++ b/backend/app/services/shipping_notice/order_review_draft_service.py @@ -656,7 +656,7 @@ def _validation( # 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。 can_build = bool(eligibility.get('can_build')) and not any( str(item.get('severity') or '') == 'blocking' - and str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + and str(item.get('owning_gate_code') or '') != 'onhand_source_routing' for item in issues ) # [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。 @@ -1574,7 +1574,7 @@ def _sync_review_gates_safe( details=sync_details, ) - inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing') + inventory_issues = _blocking_issues_for_gate(result, 'onhand_source_routing') if not inventory_issues: # 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task; # 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。 diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index d8a18cdc..48849145 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -4,7 +4,7 @@ services/shipping_notice/order_review_fulfillment_decision_service.py 用途:行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次投影。 依赖:ShippingOrderReviewLineDecision、order_review_confirmation_service、 order_review_draft_service、order_review_workbench_projection、 - line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、 + line_onhand_match_projection(OT 行匹配事实)、fulfillment_audit、 order_review_resume_service。 逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions; 订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」= @@ -20,17 +20,17 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( - ShippingInventoryField, - ShippingInventoryFile, - ShippingInventorySource, + FreightRpaOnhandField, + FreightRpaOnhandReportFile, + FreightRpaSource, ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderReviewWaveLine, ShippingNotice, ShippingOrderTask, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandTaskAttempt, ) -from app.services.shipping_notice.line_inventory_match_persistence import ( +from app.services.shipping_notice.line_onhand_match_persistence import ( resolve_review_case_for_task, ) from app.services.shipping_notice.workflow_ledger_service import ( @@ -44,13 +44,13 @@ def _get_soft_loader(): return soft_load_review_case_for_audit -DECISION_WAIT = 'wait_inventory' +DECISION_WAIT = 'wait_onhand' DECISION_FULFILL = 'fulfill_complete_line_now' DECISION_CLOSE = 'close_unfulfillable' DECISION_REOPEN = 'reopen' DECISION_USE_NEW_FILE = 'use_new_inventory_file' DECISION_CHANGE_SOURCE = 'change_inventory_source' -DECISION_RELEASE_SHORTAGE = 'release_inventory_shortage' +DECISION_RELEASE_SHORTAGE = 'release_onhand_shortage' ALLOWED_DECISIONS = frozenset({ DECISION_WAIT, @@ -171,7 +171,7 @@ def _release_template_inventory_fields( 'field_id': field_id, 'display_name': field_labels.get(field_id) or f'库存字段(编号 {field_id})', 'value': value, - 'value_source': 'inventory_snapshot' if value is not None else 'manual_required', + 'value_source': 'onhand_snapshot' if value is not None else 'manual_required', 'requires_manual': value is None, }) return fields @@ -278,7 +278,7 @@ def _is_shortage_match_fact(fact: Any) -> bool: def _has_terminal_inventory_rpa_failure( task: ShippingNotice, *, - attempts: list[ShippingTaskInventoryRpaAttempt] | None = None, + attempts: list[FreightRpaOnhandTaskAttempt] | None = None, ) -> bool: """仅在已投递的库存 RPA 全部终态失败且无活动 Attempt 时允许无快照人工放行。""" task_no = str(getattr(task, 'task_no', '') or '').strip() @@ -286,20 +286,20 @@ def _has_terminal_inventory_rpa_failure( return False source_codes: set[str] = set() try: - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)} + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + source_codes = {str(item or '').strip().upper() for item in task_frozen_onhand_source_codes(task)} except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。 source_codes = set() rows = attempts if attempts is not None else ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter_by(task_no=task_no) - .order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc(), ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc(), FreightRpaOnhandTaskAttempt.id.desc()) .all() ) relevant = [row for row in rows if not source_codes or str(getattr(row, 'source_code', '') or '').strip().upper() in source_codes] if not relevant or any(str(getattr(row, 'status', '') or '').lower() in {'queued', 'running'} for row in relevant): return False - latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {} + latest_by_source: dict[str, FreightRpaOnhandTaskAttempt] = {} for row in relevant: code = str(getattr(row, 'source_code', '') or '').strip().upper() if code and code not in latest_by_source: @@ -325,7 +325,7 @@ def _shortage_release_required_fields( Returns: (fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读, - 其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'}, + 其余 requires_manual);evidence_scope ∈ {'onhand_snapshot', 'part_fallback'}, 'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。 """ if line_index is None: @@ -333,20 +333,20 @@ def _shortage_release_required_fields( 'Current line inventory evidence is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None + snapshot = db.session.get(FreightRpaOnhandReportFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None if inventory_snapshot_id is not None and snapshot is None: raise ConflictError( 'Current inventory snapshot is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes resolved_source_code = _resolve_shortage_release_inventory_source( fact_source_code=inventory_source_code, snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None, candidate_source_codes={ str(code or '').strip().upper() - for code in task_frozen_inventory_source_codes(task) + for code in task_frozen_onhand_source_codes(task) if str(code or '').strip() }, ) @@ -355,7 +355,7 @@ def _shortage_release_required_fields( 'Current line inventory evidence is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - source = ShippingInventorySource.query.filter_by( + source = FreightRpaSource.query.filter_by( source_code=resolved_source_code, enabled=True, ).first() template = getattr(source, 'excel_template', None) if source is not None else None @@ -379,9 +379,9 @@ def _shortage_release_required_fields( and item.get('source_kind') == 'inventory_field' and str(item.get('source_key') or '').strip().isdigit() } - labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {} + labels = {str(row.id): str(row.display_name or '').strip() for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()} if field_ids else {} # 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。 - return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot' + return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'onhand_snapshot' definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else [] expected = [ @@ -393,7 +393,7 @@ def _shortage_release_required_fields( 'Inventory matching keys are unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines try: inventory_lines, _column_meta = read_inventory_file_lines(snapshot) except (OSError, ValueError, AppError) as exc: @@ -405,7 +405,7 @@ def _shortage_release_required_fields( dict(row) for row in inventory_lines if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected) ] - evidence_scope = 'inventory_snapshot' + evidence_scope = 'onhand_snapshot' if not candidates: # [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行, # 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键; @@ -413,7 +413,7 @@ def _shortage_release_required_fields( part_field_ids = { int(field_id) for field_id, _value in expected if str(field_id).strip().isdigit() - and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number' + and str(getattr(db.session.get(FreightRpaOnhandField, int(field_id)), 'field_code', '') or '') == 'part_number' } if part_field_ids: candidates = [ @@ -433,7 +433,7 @@ def _shortage_release_required_fields( } labels = { str(row.id): str(row.display_name or '').strip() - for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all() + for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all() } if field_ids else {} return _release_template_inventory_fields( mappings=mappings, @@ -481,7 +481,7 @@ def _sync_confirmed_task_fulfillment_gates( # 出现"Excel 已生成但任务仍显示库存不足/缺货"的矛盾。仅当任务确有匹配行事实时重算, # 空事实任务不得被误标为缺货。 if getattr(task, 'id', None) is not None: - from app.models import ShippingNoticeLineInventoryMatch as _MatchRow + from app.models import ShippingNoticeLineOnhandMatch as _MatchRow has_match_rows = ( _MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None @@ -592,11 +592,11 @@ def _assess_line_fulfill_complete( return False, 'SHIPPING.REVIEW_LINE_RESERVATION_REQUIRED', req, avail block_reason = str(proj.get('block_reason') or '').lower() if 'shortage' in block_reason or 'insufficient' in block_reason: - return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail + return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail if avail is None: - return False, 'SHIPPING.REVIEW_LINE_INVENTORY_UNKNOWN', req, None + return False, 'SHIPPING.REVIEW_LINE_ONHAND_UNKNOWN', req, None if avail < req: - return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail + return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail return True, None, req, avail @@ -621,7 +621,7 @@ def _assert_line_can_fulfill_complete( if not ok or req is None or avail is None: raise ConflictError( 'Line cannot fulfill complete quantity with current inventory', - code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'), + code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND'), details={'draft_line_id': draft_line_id}, ) return req, avail @@ -791,13 +791,13 @@ def project_review_case_line_decisions( Args: case: 复核 Case。 schema_fields: 可选;优先使用 serialize_review_case 已解析的字段列表。 - inventory_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。 + onhand_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。 source_labels: code→显示名映射。 Returns: lines(含 inventory_source / 分域 actions)与聚合计数。 """ - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( line_auto_fulfill_enabled, project_line_inventory_view, ) @@ -816,13 +816,13 @@ def project_review_case_line_decisions( task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id)) rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task)) # [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。 - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, + from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) fallback_inventory_source: dict[str, Any] | None = None if task is not None: - frozen_codes = task_frozen_inventory_source_codes(task) + frozen_codes = task_frozen_onhand_source_codes(task) if len(frozen_codes) == 1: fallback_inventory_source = { 'code': frozen_codes[0], @@ -846,7 +846,7 @@ def project_review_case_line_decisions( 'source': 'inventory_source_clue', } # [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。 - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( load_current_match_facts_by_line_index, ) match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id')) @@ -1058,7 +1058,7 @@ def build_inventory_issue_fallback( Case 级库存兜底:仅无有效行投影且库存系统失败时返回。 核心逻辑:有行投影→None;系统等待/RPA 运行中→None;失败时最多下发 - retry_inventory_preparation。 + retry_onhand_preparation。 Returns: fallback 字典或 None。 @@ -1088,8 +1088,8 @@ def build_inventory_issue_fallback( 'inventory_file_missing', 'inventory_source_unavailable', 'inventory_preparation_failed', - 'inventory_rpa_timeout', - 'inventory_rpa_export_failed', + 'onhand_rpa_timeout', + 'onhand_rpa_export_failed', 'inventory_file_empty', } if auto_status not in {'failed', 'error'} and reason not in failed_reasons: @@ -1101,7 +1101,7 @@ def build_inventory_issue_fallback( 'reason_label_key': kind, 'affected_line_count': 0, 'file_count': 0, - 'allowed_actions': ['retry_inventory_preparation'], + 'allowed_actions': ['retry_onhand_preparation'], } @@ -1122,7 +1122,7 @@ def _apply_shortage_line_release( 版本化落库、同步正式 OT 门禁并写审计。 核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。 - 证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中 + 证据字段按行事实快照解析(预约键命中 → onhand_snapshot;预约键 0 行命中 按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并 同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过, @@ -1161,10 +1161,10 @@ def _apply_shortage_line_release( raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND') key, draft_line = pair - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch fact = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True) .first() if getattr(task, 'id', None) is not None else None @@ -1173,10 +1173,10 @@ def _apply_shortage_line_release( release_template_fields, resolved_scope = _shortage_release_required_fields( task=task, line_index=release_line_index, - inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None, - inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None, + inventory_snapshot_id=getattr(fact, 'onhand_snapshot_id', None) if fact is not None else None, + inventory_source_code=getattr(fact, 'source_code', None) if fact is not None else None, ) - release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot') + release_evidence_scope = str(evidence_scope or resolved_scope or 'onhand_snapshot') release_required_fields = _manual_required_release_fields(release_template_fields) release_values = _validate_inventory_shortage_release_fields( required_fields=release_required_fields, @@ -1241,7 +1241,7 @@ def _apply_shortage_line_release( 'draft_line_id': key, 'release_field_values': release_values, 'release_required_fields': release_required_fields, - # 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。 + # 审计口径:放行证据来自预约匹配快照(onhand_snapshot)还是料号兜底重筛(part_fallback)。 'release_evidence_scope': release_evidence_scope, **({'auto_release': True} if auto_release else {}), }, @@ -1300,7 +1300,7 @@ def decide_review_line_fulfillment( 核心逻辑:停用旧活动决定;task_created/fulfilled 不可逆; reopen 仅 closed_unfulfillable 且管理员;fulfill 强制最新库存充足; - release_inventory_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。 + release_onhand_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。 Args: user_id: 操作人。 @@ -1310,7 +1310,7 @@ def decide_review_line_fulfillment( reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。 release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照 release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源), - release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。 + release_evidence_scope 记录证据范围(onhand_snapshot / part_fallback)。 expected_draft_version: 可选草稿乐观锁。 actor_is_admin: 是否管理员(重开授权)。 @@ -1392,12 +1392,12 @@ def decide_review_line_fulfillment( schema_fields=schema_fields, ) if code == DECISION_RELEASE_SHORTAGE: - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch task_id = getattr(case, 'confirmed_task_id', None) task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None fact = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True) .first() if task is not None else None @@ -1570,7 +1570,7 @@ def auto_release_part_fallback_shortages( Returns: 自动放行的 line_index 列表(按行号升序)。 """ - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( load_current_match_facts_by_task, ) diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index c4a330df..df594d5e 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -60,7 +60,7 @@ from app.models import ( ShippingProcessGate, ShippingProcessGateAttempt, ) -from app.services.shipping_notice.line_inventory_match_projection import ( +from app.services.shipping_notice.line_onhand_match_projection import ( inventory_rpa_is_running as _inventory_rpa_is_running, ) diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index a0506d34..5a7da034 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -70,16 +70,16 @@ _PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({ # Worker 等待类库存准备:即使存在 Gate 行,也不得投影为人工待办。 _SYSTEM_WAIT_INVENTORY_GATES: frozenset[str] = frozenset({ - 'inventory_preparation', + 'onhand_preparation', }) # 库存/履约域(正式 OT 后允许在 owner_type=human 时成为当前阻断)。 _POST_OT_INVENTORY_FULFILLMENT_GATES: frozenset[str] = frozenset({ - 'inventory_source_routing', + 'onhand_source_routing', 'reservation_validation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'line_fulfillment', 'shortage_review', 'fulfillment_decision', @@ -486,7 +486,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str from app.services.shipping_notice.upload_attempt_service import latest_export_artifact export_file_path = getattr(latest_export_artifact(task), 'file_path', None) if isinstance(task, ShippingOrderTask): - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_for_task, has_ready_inventory_file_for_task, ) @@ -494,8 +494,8 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str has_match = bool(current_inventory_matches_for_task(task)) has_inventory = has_ready_inventory_file_for_task(task) else: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task match_status = aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) has_match = bool(match_status) has_inventory = has_ready_inventory_file_for_task(task) @@ -690,7 +690,7 @@ def project_stage_for_task( from app.services.shipping_notice.processing_projection_invariants import ( map_notice_to_processing_status_stage, ) - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task from app.services.shipping_notice.upload_attempt_service import ( has_verified_upload_success, @@ -704,12 +704,12 @@ def project_stage_for_task( owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task verified_upload_success = has_verified_upload_success(task) if isinstance(owner, ShippingOrderTask): - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(getattr(owner, 'id', None)).values()) has_task_match = bool(match_facts) else: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task has_task_match = bool(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None))) progress_state = ( 'uploaded' if verified_upload_success @@ -758,13 +758,13 @@ def project_stage_for_task( # Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。 if ot_stage == 'order_creating': if progress_state in {'inventory_ready'}: - return _with_label('inventory_fetching', source='notice_inventory') + return _with_label('onhand_fetching', source='notice_inventory') if progress_state in {'matched', 'export_ready'}: _status, mapped = map_notice_to_processing_status_stage(task) - code = str(mapped or 'inventory_matching').strip() or 'inventory_matching' + code = str(mapped or 'onhand_matching').strip() or 'onhand_matching' return _with_label(code, source='notice_map') if progress_state in {None, '', 'not_started'}: - return _with_label('inventory_fetching', source='post_ot_inventory') + return _with_label('onhand_fetching', source='post_ot_inventory') return _with_label(ot_stage, source='order_task') # [STEP 2] Notice 尚无履约领域事实:统一 order_creating。 diff --git a/backend/app/services/shipping_notice/order_task_stage_machine.py b/backend/app/services/shipping_notice/order_task_stage_machine.py index ebbbb93e..02ab7245 100644 --- a/backend/app/services/shipping_notice/order_task_stage_machine.py +++ b/backend/app/services/shipping_notice/order_task_stage_machine.py @@ -65,11 +65,11 @@ _PROGRESS_EVENT_TO_PROCESSING_STAGE: dict[str, str] = { # 正式 Process Gate 的库存履约阶段 → 统一 15 阶投影阶段。 # Gate 码不是 15 阶成员,必须在写路径转换后再回写 OT,避免已建单任务残留建单前 stage。 _PROCESS_GATE_TO_PROCESSING_STAGE: dict[str, str] = { - 'inventory_source_routing': 'inventory_source_resolving', - 'inventory_preparation': 'inventory_fetching', - 'inventory_field_mapping': 'inventory_fetching', - 'inventory_matching': 'inventory_matching', - 'inventory_sufficiency': 'inventory_matching', + 'onhand_source_routing': 'onhand_source_resolving', + 'onhand_preparation': 'onhand_fetching', + 'onhand_field_mapping': 'onhand_fetching', + 'onhand_matching': 'onhand_matching', + 'onhand_sufficiency': 'onhand_matching', 'excel_readiness': 'excel_generating', 'artifact_generation': 'excel_generating', 'freight_upload_rpa': 'freight_uploading', @@ -220,7 +220,7 @@ def resolve_pre_confirm_stage( 根据 Candidate 资格评估结果解析确认建单前的 OT (stage, status)。 核心逻辑:客户未确认 → customer_resolving;查重未清 → duplicate_checking; - 库存源阻断 → inventory_source_resolving;否则 waiting_review。 + 库存源阻断 → onhand_source_resolving;否则 waiting_review。 prefer_waiting_review 仅在无阻断时抬升到 waiting_review,不得覆盖前置业务阻断。 Args: @@ -258,7 +258,7 @@ def resolve_pre_confirm_stage( return 'duplicate_checking', 'waiting_review' if any('inventory' in code for code in blocking): - return 'inventory_source_resolving', 'waiting_review' + return 'onhand_source_resolving', 'waiting_review' # [BE-02] prefer_waiting_review 不得跳过客户/查重/库存源阻断;无阻断时才落到复核。 return 'waiting_review', 'waiting_review' @@ -373,7 +373,7 @@ def sync_order_task_stage_for_notice( stage = gate_stage status = 'blocked' if stage not in SHIPPING_PROCESSING_STAGES: - stage = 'inventory_matching' + stage = 'onhand_matching' return sync_order_task_processing_state( ot, stage=stage, diff --git a/backend/app/services/shipping_notice/per_source_rpa_service.py b/backend/app/services/shipping_notice/per_source_rpa_service.py index c13f77ef..fda20a23 100644 --- a/backend/app/services/shipping_notice/per_source_rpa_service.py +++ b/backend/app/services/shipping_notice/per_source_rpa_service.py @@ -2,10 +2,10 @@ services/shipping_notice/per_source_rpa_service.py 用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。 -依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、 +依赖:models.FreightRpaOnhandTaskAttempt、onhand_candidate_freeze_service(取候选源)、 rpa.write_inventory_export_batch_trigger(批次 trigger 文件写入,单文件多源)与 rpa.build_on_demand_inventory_trigger_source(逐源条目构造)、 - inventory_snapshot_store(快照复用判断)。 + onhand_snapshot_store(快照复用判断)。 逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层, 新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。 三元组 (task_no, source_code, run_no) 幂等定位;迟到回调标记 superseded 不回写业务。 @@ -27,14 +27,14 @@ from sqlalchemy.orm import Session from app import db from app.models import ( - ShippingInventoryFile, + FreightRpaOnhandReportFile, ShippingNotice, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandTaskAttempt, ) -from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, +from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) -from app.services.shipping_notice.inventory_snapshot_store import ( +from app.services.shipping_notice.onhand_snapshot_store import ( find_latest_ready_snapshot, is_snapshot_fresh, ) @@ -45,7 +45,7 @@ from app.services.shipping_notice.onhand_trigger_batch import ( from app.services.freight_rpa.onhand.trigger_io import SCHEMA -def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None: +def _archive_unclaimed_trigger(attempt: FreightRpaOnhandTaskAttempt) -> str | None: """将仍在 trigger 根目录的未领取文件移入 failed;Worker 已领取/移走时安全忽略。""" if str(getattr(attempt, 'status', '') or '') != 'queued': return None @@ -70,7 +70,7 @@ def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str def _attempt_ref_has_ready_snapshot( - attempt: ShippingTaskInventoryRpaAttempt, + attempt: FreightRpaOnhandTaskAttempt, *, session: Session | None = None, ) -> bool: @@ -80,12 +80,12 @@ def _attempt_ref_has_ready_snapshot( 被误判为 prepared 而绕过有效库存门禁。 """ sess = session or db.session - file_no = str(getattr(attempt, 'inventory_file_no', '') or '').strip() + file_no = str(getattr(attempt, 'onhand_file_no', '') or '').strip() if not file_no: return False inv_file = ( - sess.query(ShippingInventoryFile) - .filter(ShippingInventoryFile.inventory_file_no == file_no) + sess.query(FreightRpaOnhandReportFile) + .filter(FreightRpaOnhandReportFile.onhand_file_no == file_no) .one_or_none() ) return is_snapshot_fresh(inv_file) @@ -94,7 +94,7 @@ def _attempt_ref_has_ready_snapshot( def _validate_callback_attempt_identity( *, task: ShippingNotice, - attempt: ShippingTaskInventoryRpaAttempt, + attempt: FreightRpaOnhandTaskAttempt, callback_payload: dict[str, Any], ) -> bool: """校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。""" @@ -147,7 +147,7 @@ class PerSourcePrepareResult: source_attempts: dict[str, dict[str, Any]] # source_code → {attempt_no, status, run_no, error} -def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str: +def _per_source_run_no(attempt: FreightRpaOnhandTaskAttempt) -> str: """ 构造 per-source 唯一 run_no:PSR-(dumb ID)。 @@ -166,20 +166,20 @@ def _latest_attempt( source_code: str, *, session: Session | None = None, -) -> ShippingTaskInventoryRpaAttempt | None: +) -> FreightRpaOnhandTaskAttempt | None: """查询 (task, source) 维度最新的 Attempt(按 attempt_no desc, id desc)。""" sess = session or db.session return ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, ) ) .order_by( - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), + FreightRpaOnhandTaskAttempt.attempt_no.desc(), + FreightRpaOnhandTaskAttempt.id.desc(), ) .first() ) @@ -194,12 +194,12 @@ def _consumed_run_nos( """查询 (task, source) 维度已 consumed/superseded 的 run_no 集合,用于回调幂等/迟到判断。""" sess = session or db.session rows = ( - sess.query(ShippingTaskInventoryRpaAttempt.run_no) + sess.query(FreightRpaOnhandTaskAttempt.run_no) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, - ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.status.in_(('consumed', 'superseded')), ) ) .all() @@ -219,25 +219,25 @@ def _next_attempt_no( """ sess = session or db.session last_success = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, - ShippingTaskInventoryRpaAttempt.status.in_(('succeeded', 'consumed')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.status.in_(('succeeded', 'consumed')), ) ) - .order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc()) + .order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc()) .first() ) base_no = last_success.attempt_no if last_success else 0 subsequent_count = ( - sess.query(func.count(ShippingTaskInventoryRpaAttempt.id)) + sess.query(func.count(FreightRpaOnhandTaskAttempt.id)) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, - ShippingTaskInventoryRpaAttempt.attempt_no > base_no, + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.attempt_no > base_no, ) ) .scalar() @@ -264,7 +264,7 @@ def _snapshot_ready_for_source( snap = find_latest_ready_snapshot(source_code, warehouse_id) except Exception: snap = None - from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable + from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable source_config_version = None if isinstance(rpa_source, dict): source_config_version = rpa_source.get('source_config_version') or rpa_source.get('config_version') @@ -314,7 +314,7 @@ def ensure_all_required_sources_prepared( ) -> PerSourcePrepareResult: """ 遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。 - 【AI 触发时机】:inventory_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。 + 【AI 触发时机】:onhand_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。 核心逻辑: [STEP 1] 从 T3 冻结表/兼容 step_payload 读取候选 source_codes(保序)。 @@ -325,10 +325,10 @@ def ensure_all_required_sources_prepared( - succeeded/consumed → 已 prepared - 从未 attempt → 首次触发新 attempt(queued 新 run) - failed/exhausted → 仅用户显式 retry_rpa 才触发下一 Attempt - c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件 + c. 写 FreightRpaOnhandTaskAttempt 记录 + trigger 文件 Args: - allow_auto_retry: 只读轮询开关。poll_inventory_preparation 等查询路径必须传 False: + allow_auto_retry: 只读轮询开关。poll_onhand_preparation 等查询路径必须传 False: 轮询只消费 Attempt 事实(快照复用/pending/failed 上报),禁止自动新建 Attempt。 无论此开关取值,失败后的重试都只能由用户显式动作(mode='retry_rpa')发起, 避免 RPA Worker 离线时形成“失败→重试→再失败”的无人值守空转环。 @@ -349,7 +349,7 @@ def ensure_all_required_sources_prepared( # SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。 pass source_codes = [ - str(code).strip().upper() for code in (source_codes or task_frozen_inventory_source_codes(task)) + str(code).strip().upper() for code in (source_codes or task_frozen_onhand_source_codes(task)) if str(code).strip() ] if not source_codes: @@ -359,14 +359,14 @@ def ensure_all_required_sources_prepared( failed_source_codes=[], source_attempts={}, ) - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source prepared: list[str] = [] pending: list[str] = [] failed: list[str] = [] # 本轮待触发源的单源条目与对应 Attempt;循环后合并写入单个批次 trigger。 pending_payloads: list[dict[str, Any]] = [] - pending_attempts: list[ShippingTaskInventoryRpaAttempt] = [] + pending_attempts: list[FreightRpaOnhandTaskAttempt] = [] for source_code in source_codes: rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code} @@ -386,8 +386,8 @@ def ensure_all_required_sources_prepared( # 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt, # 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。 if mode == 'retry_rpa' or current_status in {'failed', 'exhausted'}: - from app.models.shipping_task_inventory_rpa_attempts import ( - ShippingTaskInventoryRpaAttempt as _Attempt2, + from app.models.freight_rpa_onhand_task_attempts import ( + FreightRpaOnhandTaskAttempt as _Attempt2, ) q = ( sess.query(_Attempt2) @@ -433,7 +433,7 @@ def ensure_all_required_sources_prepared( next_att_no = _next_attempt_no(task_no, source_code, session=sess) # [STEP 2c] 新建 Attempt + 写 trigger 文件 - new_att = ShippingTaskInventoryRpaAttempt( + new_att = FreightRpaOnhandTaskAttempt( task_no=task_no, source_code=source_code, attempt_no=next_att_no, @@ -450,7 +450,7 @@ def ensure_all_required_sources_prepared( sess.flush([new_att]) try: - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source from app.models import ShippingProcessExecution, ShippingProcessGate legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source) @@ -565,7 +565,7 @@ def per_source_callback_handler( run_no: str, callback_payload: dict[str, Any], session: Session | None = None, -) -> tuple[str, ShippingTaskInventoryRpaAttempt | None]: +) -> tuple[str, FreightRpaOnhandTaskAttempt | None]: """ 处理 per-source 库存 RPA 回调(三元组幂等 + 迟到保护 + Task 全局状态保护)。 【AI 触发时机】:RPA Dropzone 回调入口、手动 ingest API、Worker 补录回调统一调用本函数。 @@ -586,7 +586,7 @@ def per_source_callback_handler( session: 可选 Session。 Returns: - (result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None) + (result_code: str, attempt: FreightRpaOnhandTaskAttempt | None) result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, validated, succeeded, failed} """ sess = session or db.session @@ -598,7 +598,7 @@ def per_source_callback_handler( callback_id = str((callback_payload or {}).get('callback_id') or '').strip() if callback_id: callback_attempt = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter_by(callback_id=callback_id) .one_or_none() ) @@ -614,12 +614,12 @@ def per_source_callback_handler( # [STEP 2] 三元组定位 attempt = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code_up, - ShippingTaskInventoryRpaAttempt.run_no == run_no, + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code_up, + FreightRpaOnhandTaskAttempt.run_no == run_no, ) ) .one_or_none() @@ -638,7 +638,7 @@ def per_source_callback_handler( attempt.error_code = 'trigger_identity_invalid' attempt.error_message = str((callback_payload or {}).get('error_message') or 'RPA trigger identity is invalid.')[:2000] attempt.updated_at = datetime.utcnow() - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt @@ -664,13 +664,13 @@ def per_source_callback_handler( except (TypeError, ValueError): current_attempt_no = 0 newer_count = ( - sess.query(func.count(ShippingTaskInventoryRpaAttempt.id)) + sess.query(func.count(FreightRpaOnhandTaskAttempt.id)) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code_up, - ShippingTaskInventoryRpaAttempt.attempt_no > current_attempt_no, - ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded', 'succeeded')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code_up, + FreightRpaOnhandTaskAttempt.attempt_no > current_attempt_no, + FreightRpaOnhandTaskAttempt.status.in_(('consumed', 'superseded', 'succeeded')), ) ) .scalar() @@ -714,7 +714,7 @@ def per_source_callback_handler( attempt.callback_file_path = str(callback_payload.get('callback_file_path') or '').strip() or None inventory_file_no = str(callback_payload.get('inventory_file_no') or '').strip() or None if inventory_file_no: - attempt.inventory_file_no = inventory_file_no + attempt.onhand_file_no = inventory_file_no error_code = str(callback_payload.get('error_code') or '').strip() or None error_message = str(callback_payload.get('error_message') or '').strip() or None @@ -723,15 +723,15 @@ def per_source_callback_handler( attempt.transaction_status = 'rejected' attempt.error_code = error_code attempt.error_message = error_message[:2000] if error_message else None - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt # 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功) if inventory_file_no: _inv = ( - sess.query(ShippingInventoryFile) - .filter(ShippingInventoryFile.inventory_file_no == inventory_file_no) + sess.query(FreightRpaOnhandReportFile) + .filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no) .one_or_none() ) if _inv is None or not is_snapshot_fresh(_inv): @@ -749,13 +749,13 @@ def per_source_callback_handler( attempt.error_message = ( f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000] ) - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt attempt.status = 'succeeded' attempt.transaction_status = 'succeeded' - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt( rpa_attempt_id=int(attempt.id), rpa_status='succeeded', @@ -766,7 +766,7 @@ def per_source_callback_handler( # 调用方在同一事务提交后,Job 才对 Worker 可见。 from app.services.shipping_notice.auto_progress_controller import submit_auto_progress - submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded', commit=False) + submit_auto_progress(task=task, trigger='onhand_rpa_callback_succeeded', commit=False) return 'succeeded', attempt @@ -785,7 +785,7 @@ def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: source_code = str(item.get('source_code') or '').strip().upper() source_run_no = str(item.get('source_run_no') or '').strip() lease_token = str(item.get('lease_token') or '').strip() - attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by( + attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by( task_no=task_no, source_code=source_code, source_run_no=source_run_no, ).one_or_none() if attempt is None or str(attempt.lease_token or '') != lease_token: @@ -829,15 +829,15 @@ def per_source_timeout_scan( task_no = str(task.task_no or '').strip() threshold = datetime.utcnow() - timedelta(seconds=max(int(timeout_seconds), 1)) candidates = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')), or_( - ShippingTaskInventoryRpaAttempt.triggered_at <= threshold, - ShippingTaskInventoryRpaAttempt.leased_at <= threshold, - ShippingTaskInventoryRpaAttempt.created_at <= threshold, + FreightRpaOnhandTaskAttempt.triggered_at <= threshold, + FreightRpaOnhandTaskAttempt.leased_at <= threshold, + FreightRpaOnhandTaskAttempt.created_at <= threshold, ), ) ) @@ -868,7 +868,7 @@ def per_source_timeout_scan( att.extra_json = extra # 超时扫描与正式回调共享同一准备轮次事实;否则 Attempt 已失败而 # PreparationAttempt 仍停在 waiting_external,工作台会错误禁用重试。 - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt( rpa_attempt_id=int(att.id), diff --git a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py index 32d675ba..9a670517 100644 --- a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py +++ b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py @@ -66,7 +66,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] if str(line.get('inventory_status') or '') != 'ready': raise ConflictError( 'Inventory not ready for post-OT wave', - code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY', + code='SHIPPING.REVIEW_LINE_ONHAND_NOT_READY', details={'snapshot_line_id': line.get('snapshot_line_id'), 'inventory_status': line.get('inventory_status')}, ) if str(line.get('match_result') or '') != 'matched': @@ -75,11 +75,11 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE', details={'snapshot_line_id': line.get('snapshot_line_id'), 'match_result': line.get('match_result')}, ) - is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage' + is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_onhand_shortage' if line.get('is_shortage') and not is_released_shortage: raise ConflictError( 'Line has inventory shortage', - code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', + code='SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', details={'snapshot_line_id': line.get('snapshot_line_id')}, ) req = _parse_qty(line.get('required_qty')) @@ -87,7 +87,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] if req is None or (avail is None and not is_released_shortage) or (avail is not None and avail < req and not is_released_shortage): raise ConflictError( 'Line cannot fulfill complete quantity with current inventory facts', - code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', + code='SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', details={'snapshot_line_id': line.get('snapshot_line_id')}, ) return req, avail @@ -311,13 +311,13 @@ def create_post_ot_fulfillment_wave( revision_id=None, ) # [D8] 波次按自身行重跑路由冻结(不继承首通知源);复用库存候选冻结链路。 - from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_wave_notice_routing + from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_wave_notice_routing routing_result = freeze_wave_notice_routing(notice, source_notice=None) if routing_result is None or not routing_result.source_codes: raise ConflictError( 'Inventory source routing is unresolved for selected fulfillment lines', - code='SHIPPING.REVIEW_LINE_INVENTORY_SOURCE_UNRESOLVED', + code='SHIPPING.REVIEW_LINE_ONHAND_SOURCE_UNRESOLVED', details={'snapshot_line_ids': [int(item) for item in selected_snapshot_line_ids]}, ) db.session.flush() @@ -351,7 +351,7 @@ def create_post_ot_fulfillment_wave( if ( key in accepted_snapshot_line_ids and current is not None - and current.decision_code == 'release_inventory_shortage' + and current.decision_code == 'release_onhand_shortage' ): current.line_status = 'task_created' current.task_id = int(order_task.id) @@ -476,7 +476,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li 列出可自动/人工履约的行(ready+matched+未关闭+未终态)。 核心逻辑:库存充足行可直接入 wave;库存不足行只有在已留下 - ``release_inventory_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。 + ``release_onhand_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。 Args: case: 复核 Case。 @@ -496,7 +496,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li if str(item.get('match_result') or '') != 'matched': continue decision_code = str((item.get('decision') or {}).get('decision_code') or '') - if item.get('is_shortage') and decision_code != 'release_inventory_shortage': + if item.get('is_shortage') and decision_code != 'release_onhand_shortage': continue if item.get('user_line_status') == 'auto_fulfill_failed': continue @@ -504,7 +504,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li continue req = _parse_qty(item.get('required_qty')) avail = _parse_qty(item.get('available_qty')) - is_released_shortage = decision_code == 'release_inventory_shortage' + is_released_shortage = decision_code == 'release_onhand_shortage' if req is None or (avail is None and not is_released_shortage) or ( avail is not None and avail < req and not is_released_shortage ): diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 96e1fea6..f01850e5 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -3,7 +3,7 @@ services/shipping_notice/process_gate_bridge.py 用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、 将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。 -依赖:process_gate_service、process_gate_contract、constants、inventory_rpa_workflow、 +依赖:process_gate_service、process_gate_contract、constants、onhand_rpa_workflow、 ShippingProcessExecution、ShippingOrderReviewCase、ShippingNotice。 逻辑:由 order_extraction_run_service / order_review_confirmation_service / order_review_draft_service / progress_workflow / process_gate_executor 调用; @@ -11,9 +11,9 @@ services/shipping_notice/process_gate_bridge.py 复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details; 确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定; 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code; - 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation - 供 ensure_inventory(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时, - 不把 inventory_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。 + 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_onhand_preparation + 供 ensure_onhand(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时, + 不把 onhand_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。 """ from __future__ import annotations @@ -60,7 +60,7 @@ def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str if upload_status == 'failed': return 'upload_failed' if isinstance(task, ShippingOrderTask): - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_have_shortage, inventory_matches_complete_for_task, has_ready_inventory_file_for_task, @@ -69,12 +69,12 @@ def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str if inventory_matches_complete_for_task(task): return 'shortage_review' if current_inventory_matches_have_shortage(task) else 'matched' return 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'created' - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) match_status = aggregate_match_status_for_task(match_task_id) or '' if match_status in {'fulfillable', 'partial', 'unfulfillable'}: return 'matched' - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if has_ready_inventory_file_for_task(task): return 'inventory_ready' return 'created' @@ -84,32 +84,32 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) """ 由任务事实推导库存准备门禁阻断原因码。 - 核心逻辑:pending_human_reason、最近 inventory_rpa_failed 事件与逐源 Attempt + 核心逻辑:pending_human_reason、最近 onhand_rpa_failed 事件与逐源 Attempt 失败事实优先于泛化 inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。 - 惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。 + 惰性导入 constants / onhand_rpa_workflow,避免与桥接模块循环依赖。 Args: task: 履约任务。 Returns: - 稳定阻断原因码(归属 inventory_preparation)。 + 稳定阻断原因码(归属 onhand_preparation)。 """ from app.services.shipping_notice.constants import ( PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_RPA_PENDING, ) - from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event + from app.services.shipping_notice.onhand_rpa_workflow import latest_task_event from app.services.shipping_notice.process_gate_projection import task_blocking_reason pending = str(task_blocking_reason(task) or '').strip() if pending == PH_RPA_PENDING: - return 'inventory_rpa_queued' + return 'onhand_rpa_queued' if pending == PH_RPA_EXHAUSTED: - return 'inventory_rpa_exhausted' + return 'onhand_rpa_exhausted' if getattr(task, 'id', None) is not None: - failed = latest_task_event(task, 'inventory_rpa_failed') + failed = latest_task_event(task, 'onhand_rpa_failed') if failed is not None: payload = getattr(failed, 'detail_json', None) if not isinstance(payload, dict): @@ -119,29 +119,29 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) code = str(payload.get('error_code') or '').strip().lower() blob = f'{err} {code}' if 'timeout' in blob or ('not ready' in blob and 'within' in blob): - return 'inventory_rpa_timeout' + return 'onhand_rpa_timeout' if 'login' in blob or 'auth' in blob: - return 'inventory_rpa_login_failed' + return 'onhand_rpa_login_failed' if 'export' in blob or 'rpa_export' in blob: - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' if 'empty' in blob: return 'inventory_file_empty' if 'identity' in blob or 'mismatch' in blob: return 'inventory_file_identity_mismatch' - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' # 逐源 Attempt 是当前库存 RPA 的正式失败事实;超时扫描不一定会留下旧 # ShippingTaskEvent,Gate 不能因此退化为“库存文件为空/缺失”。 - from app.models import ShippingTaskInventoryRpaAttempt + from app.models import FreightRpaOnhandTaskAttempt latest_attempt = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter( - ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or '').strip(), + FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or '').strip(), ) .order_by( - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), + FreightRpaOnhandTaskAttempt.attempt_no.desc(), + FreightRpaOnhandTaskAttempt.id.desc(), ) .first() ) @@ -152,16 +152,16 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) str(latest_attempt.error_message or '').strip().lower(), ]) if 'exhausted' in blob: - return 'inventory_rpa_exhausted' + return 'onhand_rpa_exhausted' if 'timeout' in blob or ('not ready' in blob and 'within' in blob): - return 'inventory_rpa_timeout' + return 'onhand_rpa_timeout' if 'login' in blob or 'auth' in blob: - return 'inventory_rpa_login_failed' + return 'onhand_rpa_login_failed' if 'empty' in blob: return 'inventory_file_empty' if 'identity' in blob or 'mismatch' in blob: return 'inventory_file_identity_mismatch' - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' # inv_unavail 仅说明当前没有可用库存文件;若本轮没有 RPA 失败审计, # 才使用该泛化原因,不能覆盖已记录的下载超时/登录/导出失败。 @@ -174,7 +174,7 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) return 'inventory_file_missing' # [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。 - from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_lines_for_task active_lines = active_inventory_lines_for_task(task) if isinstance(active_lines, list): @@ -216,7 +216,7 @@ def manual_upload_reason_code(task: ShippingOrderTask | ShippingNotice) -> str: return 'upload_rpa_pending' if pending == PH_UPLOAD_RPA_FAILED or status == 'upload_failed': # [STEP] 登录失败优先于泛化 upload_rpa_failed,便于责任方落到 admin - from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event + from app.services.shipping_notice.onhand_rpa_workflow import latest_task_event if getattr(task, 'id', None) is not None: failed = latest_task_event(task, 'upload_rpa_failed') or latest_task_event( @@ -532,26 +532,26 @@ def sync_execution_after_review_confirm( ) # [STEP] Task 与 Snapshot 已在确认事务中完成后,才执行正式库存源裁决。 # CandidateSet 是 inventory_source_routing 通过的必要业务事实。 - from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source + from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source adjudication = adjudicate_and_apply_inventory_source( task, execution_id=int(execution.id), ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - if not task_frozen_inventory_source_codes(task): + if not task_frozen_onhand_source_codes(task): # 无候选时不放行 routing;保留当前 Gate 事实,交由规则恢复动作处理。 return execution apply_gate_outcome( execution=execution, - gate_code='inventory_source_routing', + gate_code='onhand_source_routing', passed=True, effective_result={ 'findings': [], 'candidate_set_id': int(task.active_inventory_candidate_set_id), - 'source_codes': task_frozen_inventory_source_codes(task), + 'source_codes': task_frozen_onhand_source_codes(task), 'status': str(adjudication.status or 'resolved'), }, actor_type='user', @@ -673,14 +673,14 @@ def sync_inventory_routing_gate_for_case( blocking_reason_code: str | None = None, ) -> ShippingProcessGate | None: """ - 将库存源路由业务结果同步到 inventory_source_routing Gate。 + 将库存源路由业务结果同步到 onhand_source_routing Gate。 Returns: 更新后的 Gate;无 Execution 时尝试创建后同步。 """ return sync_review_gate_for_case( case=case, - gate_code='inventory_source_routing', + gate_code='onhand_source_routing', passed=passed, actor_id=actor_id, details=details, @@ -900,8 +900,8 @@ def _supersede_auto_inventory_poll_for_rpa_failure( 自动轮询 Attempt 不产生新的库存事实;其在 RPA 已失败后继续 queued/running 会使 sync_gate_from_business_result 早退,Gate 永久停留 waiting_external。 - 仅处理 trigger_type=auto 且 action_code=poll_inventory_preparation,绝不终止 - 用户主动 retry_inventory_preparation。 + 仅处理 trigger_type=auto 且 action_code=poll_onhand_preparation,绝不终止 + 用户主动 retry_onhand_preparation。 """ from app import db from app.models import ShippingProcessGateAttempt @@ -915,7 +915,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure( ): return gate = ShippingProcessGate.query.filter_by( - execution_id=int(execution.id), gate_code='inventory_preparation', + execution_id=int(execution.id), gate_code='onhand_preparation', ).with_for_update().first() if gate is None: return @@ -932,7 +932,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure( now = datetime.utcnow() for attempt in active_attempts: snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {} - if str(snapshot.get('action_code') or '').strip() != 'poll_inventory_preparation': + if str(snapshot.get('action_code') or '').strip() != 'poll_onhand_preparation': continue before = {'status': attempt.status, 'gate_code': gate.gate_code} attempt.status = 'superseded' @@ -965,10 +965,10 @@ def sync_fulfillment_gates_from_task( actor_id: str | int | None = None, ) -> None: """ - 按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。 + 按 ShippingNotice 履约状态同步 onhand_preparation→freight_upload_rpa→manual_upload_handoff。 核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果; - 建单后尚无库存行时不投影假失败,只露出 retry_inventory_preparation 供自动取数; + 建单后尚无库存行时不投影假失败,只露出 retry_onhand_preparation 供自动取数; RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断 manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。 由 auto_progress 与 Gate 恢复执行器在履约动作后调用。 @@ -995,7 +995,7 @@ def sync_fulfillment_gates_from_task( match_completed, ) from app.services.shipping_notice.process_gate_projection import task_blocking_reason - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( active_inventory_file_for_task, active_inventory_lines_for_task, ) @@ -1087,18 +1087,18 @@ def sync_fulfillment_gates_from_task( # 存在对应轮次时使用,避免旧任务的孤立轮次污染正式链。 preparation = None try: - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt prep_query = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(task.id), execution_id=int(execution.id)) - .filter(ShippingInventoryPreparationAttempt.status != 'superseded') + .filter(ShippingOnhandPreparationAttempt.status != 'superseded') ) if execution.candidate_set_id is not None: prep_query = prep_query.filter( - ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) + ShippingOnhandPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) ) - preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first() + preparation = prep_query.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()).first() except Exception: # noqa: BLE001 preparation = None # 已绑定库存行代表正式快照已成功落库;历史 PreparationAttempt 即使仍标为 @@ -1122,7 +1122,7 @@ def sync_fulfillment_gates_from_task( task_rpa_exhausted = str(task_blocking_reason(task) or '').strip() == 'rpa_exhausted' if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending): apply_gate_outcome( - execution=execution, gate_code='inventory_preparation', passed=False, + execution=execution, gate_code='onhand_preparation', passed=False, outcome='waiting_external', effective_result={'findings': [], **task_facts}, blocking_reason_code='inventory_preparation_waiting', actor_type=actor_type, actor_id=actor_id, @@ -1138,7 +1138,7 @@ def sync_fulfillment_gates_from_task( or 'inventory_preparation_failed' ) apply_gate_outcome( - execution=execution, gate_code='inventory_preparation', passed=False, + execution=execution, gate_code='onhand_preparation', passed=False, outcome='blocked_retryable', effective_result={'findings': [], **task_facts}, blocking_reason_code=preparation_reason, actor_type=actor_type, actor_id=actor_id, @@ -1147,7 +1147,7 @@ def sync_fulfillment_gates_from_task( return if preparation.status == 'succeeded' and required and len(prepared) == len(required): apply_gate_outcome( - execution=execution, gate_code='inventory_preparation', passed=True, + execution=execution, gate_code='onhand_preparation', passed=True, effective_result=task_facts, actor_type=actor_type, actor_id=actor_id, idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:passed', force=True, ) @@ -1160,22 +1160,22 @@ def sync_fulfillment_gates_from_task( # 必须退出自动处理中,回到可重试 Gate,不能因同一等待事实再次自动入队。 if pending_reason == PH_RPA_PENDING: outcome = 'waiting_external' - waiting_reason = 'inventory_rpa_queued' + waiting_reason = 'onhand_rpa_queued' elif pending_reason == PH_RPA_EXHAUSTED: # 兼容历史 rpa_exhausted:自动次数上限不得限制用户再次发起库存准备。 outcome = 'blocked_retryable' - waiting_reason = 'inventory_rpa_exhausted' + waiting_reason = 'onhand_rpa_exhausted' else: outcome = 'blocked_retryable' waiting_reason = inventory_preparation_reason_code(task) or 'inventory_preparation_failed' apply_gate_outcome( execution=execution, - gate_code='inventory_preparation', + gate_code='onhand_preparation', passed=False, outcome=outcome, effective_result={ 'findings': _fulfillment_blocking_finding( - gate_code='inventory_preparation', + gate_code='onhand_preparation', reason_code=waiting_reason, details=task_facts, ), @@ -1194,7 +1194,7 @@ def sync_fulfillment_gates_from_task( if not has_inventory_lines and status == 'created': prep_gate = ( ShippingProcessGate.query - .filter_by(execution_id=int(execution.id), gate_code='inventory_preparation') + .filter_by(execution_id=int(execution.id), gate_code='onhand_preparation') .first() ) if prep_gate is not None and str(prep_gate.status or '').strip().lower() in { @@ -1206,10 +1206,10 @@ def sync_fulfillment_gates_from_task( ) prep_gate.next_action_code = ( primary_next_action_for_gate( - gate_code='inventory_preparation', + gate_code='onhand_preparation', status='blocked_retryable', ) - or 'retry_inventory_preparation' + or 'retry_onhand_preparation' ) prep_gate.updated_at = datetime.utcnow() from app.services.shipping_notice.process_gate_service import ( @@ -1223,13 +1223,13 @@ def sync_fulfillment_gates_from_task( inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task) apply_gate_outcome( execution=execution, - gate_code='inventory_preparation', + gate_code='onhand_preparation', passed=inv_prep_passed, outcome=None if inv_prep_passed else 'blocked_retryable', effective_result={ 'findings': ( [] if inv_prep_passed else _fulfillment_blocking_finding( - gate_code='inventory_preparation', + gate_code='onhand_preparation', reason_code=str(inv_prep_reason or 'inventory_preparation_failed'), details=task_facts, ) @@ -1250,13 +1250,13 @@ def sync_fulfillment_gates_from_task( mapping_reason = 'inventory_mapping_required' if mapping_needed else None apply_gate_outcome( execution=execution, - gate_code='inventory_field_mapping', + gate_code='onhand_field_mapping', passed=not mapping_needed, outcome='blocked_retryable' if mapping_needed else None, effective_result={ 'findings': ( [] if not mapping_needed else _fulfillment_blocking_finding( - gate_code='inventory_field_mapping', + gate_code='onhand_field_mapping', reason_code=mapping_reason or 'inventory_mapping_required', details={ **task_facts, @@ -1281,8 +1281,8 @@ def sync_fulfillment_gates_from_task( classify_inventory_match_reason, ) - from app.models import ShippingNoticeLineInventoryMatch - current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + from app.models import ShippingNoticeLineOnhandMatch + current_match_rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() line_results = [{'disposition': row.match_result} for row in current_match_rows] # 库存已就绪但尚无匹配行:匹配 Gate 若仍是 pending/queued/running,说明匹配尚未执行完, # 不得投影成 inventory_match_failed(界面会显示 --,并与 auto-progress 并发踩踏)。 @@ -1290,13 +1290,13 @@ def sync_fulfillment_gates_from_task( if not match_passed and not current_match_rows: match_gate = ( ShippingProcessGate.query - .filter_by(execution_id=int(execution.id), gate_code='inventory_matching') + .filter_by(execution_id=int(execution.id), gate_code='onhand_matching') .first() ) match_gate_status = str(getattr(match_gate, 'status', '') or '').strip().lower() if match_gate else '' if match_gate is not None and match_gate_status in {'pending', 'queued', 'running'}: if not str(match_gate.next_action_code or '').strip(): - match_gate.next_action_code = 'retry_inventory_matching' + match_gate.next_action_code = 'retry_onhand_matching' match_gate.updated_at = datetime.utcnow() from app.services.shipping_notice.process_gate_service import ( _refresh_execution_pointers, @@ -1309,14 +1309,14 @@ def sync_fulfillment_gates_from_task( ) apply_gate_outcome( execution=execution, - gate_code='inventory_matching', + gate_code='onhand_matching', passed=match_passed, # 匹配已执行过但仍无终态事实时,才投影可重试失败并露出 retry_inventory_matching。 outcome='blocked_retryable' if not match_passed else None, effective_result={ 'findings': ( [] if match_passed else _fulfillment_blocking_finding( - gate_code='inventory_matching', + gate_code='onhand_matching', reason_code=str(match_reason or 'inventory_match_failed'), details={ **task_facts, @@ -1351,13 +1351,13 @@ def sync_fulfillment_gates_from_task( ) apply_gate_outcome( execution=execution, - gate_code='inventory_sufficiency', + gate_code='onhand_sufficiency', passed=sufficiency_ok, outcome='blocked_manual' if shortage else None, effective_result={ 'findings': ( [] if sufficiency_ok else _fulfillment_blocking_finding( - gate_code='inventory_sufficiency', + gate_code='onhand_sufficiency', reason_code=str(shortage_reason or 'inventory_insufficient'), details={**task_facts, 'match_status': match_status or None}, ) diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 81c210aa..8eac46fb 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -223,7 +223,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( }, }, { - 'gate_code': 'inventory_source_routing', + 'gate_code': 'onhand_source_routing', 'sequence_no': 12, 'label': '库存源路由', 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'}, @@ -236,56 +236,56 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( }, }, { - 'gate_code': 'inventory_preparation', + 'gate_code': 'onhand_preparation', 'sequence_no': 13, 'label': '库存文件或快照准备', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_preparation'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_preparation'}, 'responsible_party': 'worker', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_inventory_preparation', - 'waiting_external': 'poll_inventory_preparation', - 'blocked_manual': 'retry_inventory_preparation', + 'blocked_retryable': 'retry_onhand_preparation', + 'waiting_external': 'poll_onhand_preparation', + 'blocked_manual': 'retry_onhand_preparation', }, }, { - 'gate_code': 'inventory_field_mapping', + 'gate_code': 'onhand_field_mapping', 'sequence_no': 14, 'label': '库存字段映射', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_field_mapping'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_field_mapping'}, 'responsible_party': 'system', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_inventory_field_mapping', + 'blocked_retryable': 'retry_onhand_field_mapping', # 字段映射是库存模板治理,不允许用户确认技术映射。 - 'blocked_manual': 'retry_inventory_field_mapping', + 'blocked_manual': 'retry_onhand_field_mapping', }, }, { - 'gate_code': 'inventory_matching', + 'gate_code': 'onhand_matching', 'sequence_no': 15, 'label': 'Reservation + 料号匹配', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_matching'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_matching'}, 'responsible_party': 'worker', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_inventory_matching', - 'blocked_manual': 'open_inventory_match_review', + 'blocked_retryable': 'retry_onhand_matching', + 'blocked_manual': 'open_onhand_match_review', }, }, { - 'gate_code': 'inventory_sufficiency', + 'gate_code': 'onhand_sufficiency', 'sequence_no': 16, 'label': '库存满足性', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_sufficiency'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_sufficiency'}, 'responsible_party': 'owner', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'recheck_inventory_sufficiency', + 'blocked_retryable': 'recheck_onhand_sufficiency', 'blocked_manual': 'open_shortage_review', }, }, @@ -366,17 +366,17 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'retry_with_latest_rules', 'recheck_freeze_readiness', 'retry_task_creation', - 'retry_inventory_preparation', - 'reload_inventory_result', - 'poll_inventory_preparation', - 'retry_inventory_field_mapping', - 'retry_inventory_matching', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', - 'retry_inventory_from_matching', - 'override_line_inventory_source', - 'open_inventory_match_review', - 'recheck_inventory_sufficiency', + 'retry_onhand_preparation', + 'reload_onhand_result', + 'poll_onhand_preparation', + 'retry_onhand_field_mapping', + 'retry_onhand_matching', + 'retry_onhand_from_preparation', + 'retry_onhand_from_field_mapping', + 'retry_onhand_from_matching', + 'override_line_onhand_source', + 'open_onhand_match_review', + 'recheck_onhand_sufficiency', 'open_shortage_review', 'recheck_excel_readiness', 'regenerate_excel_artifact', @@ -405,7 +405,7 @@ PROCESS_GATE_ACTION_PRESENTATION: Final[dict[str, dict[str, str]]] = { for _code in { 'open_order_review', 'open_profile_review', 'edit_order_fields', 'edit_reservation', 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', 'open_shortage_review', + 'open_onhand_match_review', 'open_shortage_review', }: PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'navigation' # ``ui_handler`` 是页面宿主能力标识,不参与动作授权或业务裁决。后端在这里声明 @@ -418,16 +418,16 @@ for _code, _ui_handler in { 'confirm_customer': {'ui_handler': 'customer_resolution'}, 'adjudicate_duplicate': {'ui_handler': 'duplicate_review'}, 'resolve_field_conflicts': {'ui_handler': 'field_conflicts'}, - 'open_inventory_match_review': {'ui_handler': 'inventory_match_review'}, + 'open_onhand_match_review': {'ui_handler': 'inventory_match_review'}, 'open_shortage_review': {'ui_handler': 'shortage_review'}, }.items(): PROCESS_GATE_ACTION_PRESENTATION[_code].update(_ui_handler) # 人工上传确认由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。 PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['dispatch'] = 'dialog' PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_confirmation' -for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}: +for _code in {'retry_onhand_from_preparation', 'retry_onhand_from_field_mapping', 'retry_onhand_from_matching'}: PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery' -for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}: +for _code in {'poll_onhand_preparation', 'poll_freight_upload_rpa'}: PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'refresh' def action_presentation( @@ -478,25 +478,25 @@ def inventory_preparation_primary_action( """裁决库存准备 Gate 面向业务用户的主动作。 单源合并(用户拍板):库存失败只保留 2 个按钮 —— - ``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching`` + ``retry_onhand_preparation``(显式重跑 RPA)与 ``retry_onhand_matching`` (复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。 - 已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入 - ``retry_inventory_matching``。 - 边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。 - 因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用 + 已下线的 ``reload_onhand_result``(只重读)不再独立成主动作,其「复用快照」行为已并入 + ``retry_onhand_matching``。 + 边界(STP 多候选,ensure_onhand auto 模式):缺快照停人工待处理、不隐式触发 RPA。 + 因此获取库存未成功(无行级匹配结果)时,``retry_onhand_matching`` 由阶段能力禁用 (disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task), - 重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。 + 重抓必须走显式的 ``retry_onhand_preparation``;本函数只裁决按钮位次,不禁用按钮。 """ normalized_status = str(status or '').strip().lower() normalized_reason = str(blocking_reason_code or '').strip().lower() if normalized_status == 'waiting_external': - return 'poll_inventory_preparation' - if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}: + return 'poll_onhand_preparation' + if normalized_reason in {'onhand_rpa_timeout', 'onhand_rpa_exhausted'}: # [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力 # 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。 - return 'retry_inventory_matching' + return 'retry_onhand_matching' if normalized_status in {'blocked_manual', 'blocked_retryable'}: - return 'retry_inventory_preparation' + return 'retry_onhand_preparation' return None @@ -534,10 +534,10 @@ def gate_side_recovery_actions( # [STEP] 库存准备 RPA 超时/耗尽:主恢复已合并为 retry_inventory_matching(优先复用已有快照 # 重匹配,无快照则回退 RPA);侧路保留显式 retry_inventory_preparation(强制重抓)供用户选择。 if ( - code == 'inventory_preparation' - and reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'} + code == 'onhand_preparation' + and reason in {'onhand_rpa_timeout', 'onhand_rpa_exhausted'} ): - sides.append('retry_inventory_preparation') + sides.append('retry_onhand_preparation') # [STEP] 人工上传交接(Gate 20):主动作是凭据登记,货代 RPA 仍允许用户显式重试。 if ( code == 'manual_upload_handoff' @@ -547,8 +547,8 @@ def gate_side_recovery_actions( # [STEP] 行级库存源人工覆写(方案 3·放开):通知准备(Excel 生成前)与库存匹配阶段 # 均允许用户把某行库存源覆写为任一已启用源后再重匹配;Excel 锁与源启用校验由执行器负责。 # 已取代旧 D5 多文件冲突逐行选源(select_line_inventory_source,已下线)。 - if code in {'inventory_source_routing', 'inventory_preparation', 'inventory_matching'}: - sides.append('override_line_inventory_source') + if code in {'onhand_source_routing', 'onhand_preparation', 'onhand_matching'}: + sides.append('override_line_onhand_source') return tuple(sides) @@ -582,7 +582,7 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'inventory_source_unavailable', 'inventory_source_conflicted', 'inventory_source_changed', - 'inventory_source_identity_mismatch', + 'onhand_source_identity_mismatch', 'inventory_multi_file_conflict', 'inventory_sku_not_found', 'inventory_reservation_not_found', @@ -623,11 +623,11 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'task_creation_failed', 'inventory_preparation_failed', 'inventory_preparation_waiting', - 'inventory_rpa_queued', - 'inventory_rpa_timeout', - 'inventory_rpa_login_failed', - 'inventory_rpa_export_failed', - 'inventory_rpa_exhausted', + 'onhand_rpa_queued', + 'onhand_rpa_timeout', + 'onhand_rpa_login_failed', + 'onhand_rpa_export_failed', + 'onhand_rpa_exhausted', 'inventory_file_missing', 'inventory_file_empty', 'inventory_file_identity_mismatch', @@ -693,18 +693,18 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'cross_source_conflict': 'field_conflict_resolution', 'pdf_preferred_critical_conflict': 'field_conflict_resolution', 'pdf_preferred': 'field_conflict_resolution', - 'no_inventory_source_candidates': 'inventory_source_routing', - 'require_manual_review': 'inventory_source_routing', - 'inventory_source_unavailable': 'inventory_source_routing', - 'inventory_source_conflicted': 'inventory_source_routing', - 'inventory_source_changed': 'inventory_source_routing', - 'inventory_source_identity_mismatch': 'inventory_source_routing', - 'inventory_multi_file_conflict': 'inventory_matching', - 'inventory_sku_not_found': 'inventory_matching', - 'inventory_reservation_not_found': 'inventory_matching', - 'inventory_warehouse_mismatch': 'inventory_matching', - 'inventory_required_column_missing': 'inventory_field_mapping', - 'inventory_column_ambiguous': 'inventory_field_mapping', + 'no_inventory_source_candidates': 'onhand_source_routing', + 'require_manual_review': 'onhand_source_routing', + 'inventory_source_unavailable': 'onhand_source_routing', + 'inventory_source_conflicted': 'onhand_source_routing', + 'inventory_source_changed': 'onhand_source_routing', + 'onhand_source_identity_mismatch': 'onhand_source_routing', + 'inventory_multi_file_conflict': 'onhand_matching', + 'inventory_sku_not_found': 'onhand_matching', + 'inventory_reservation_not_found': 'onhand_matching', + 'inventory_warehouse_mismatch': 'onhand_matching', + 'inventory_required_column_missing': 'onhand_field_mapping', + 'inventory_column_ambiguous': 'onhand_field_mapping', 'excel_template_missing': 'excel_readiness', 'excel_input_incomplete': 'excel_readiness', 'artifact_validation_failed': 'artifact_generation', @@ -753,20 +753,20 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'run_cancelled': 'order_freeze_readiness', 'pending_orders_present': 'order_freeze_readiness', 'task_creation_failed': 'task_creation', - 'inventory_preparation_failed': 'inventory_preparation', - 'inventory_preparation_waiting': 'inventory_preparation', - 'inventory_rpa_queued': 'inventory_preparation', - 'inventory_rpa_timeout': 'inventory_preparation', - 'inventory_rpa_login_failed': 'inventory_preparation', - 'inventory_rpa_export_failed': 'inventory_preparation', - 'inventory_rpa_exhausted': 'inventory_preparation', - 'inventory_file_missing': 'inventory_preparation', - 'inventory_file_empty': 'inventory_preparation', - 'inventory_file_identity_mismatch': 'inventory_preparation', - 'inventory_mapping_required': 'inventory_field_mapping', - 'inventory_match_failed': 'inventory_matching', - 'inventory_insufficient': 'inventory_sufficiency', - 'inventory_shortage_review_required': 'inventory_sufficiency', + 'inventory_preparation_failed': 'onhand_preparation', + 'inventory_preparation_waiting': 'onhand_preparation', + 'onhand_rpa_queued': 'onhand_preparation', + 'onhand_rpa_timeout': 'onhand_preparation', + 'onhand_rpa_login_failed': 'onhand_preparation', + 'onhand_rpa_export_failed': 'onhand_preparation', + 'onhand_rpa_exhausted': 'onhand_preparation', + 'inventory_file_missing': 'onhand_preparation', + 'inventory_file_empty': 'onhand_preparation', + 'inventory_file_identity_mismatch': 'onhand_preparation', + 'inventory_mapping_required': 'onhand_field_mapping', + 'inventory_match_failed': 'onhand_matching', + 'inventory_insufficient': 'onhand_sufficiency', + 'inventory_shortage_review_required': 'onhand_sufficiency', 'excel_not_ready': 'excel_readiness', 'artifact_generation_failed': 'artifact_generation', 'manual_upload_pending': 'manual_upload_handoff', @@ -884,16 +884,16 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: if recovery_plan_for_action(current_gate=code, action_code=action) is not None: return True - if action == 'retry_inventory_matching' and code in { - 'inventory_preparation', 'inventory_matching', 'inventory_sufficiency', + if action == 'retry_onhand_matching' and code in { + 'onhand_preparation', 'onhand_matching', 'onhand_sufficiency', }: return True - if action == 'reload_inventory_result' and code == 'inventory_preparation': + if action == 'reload_onhand_result' and code == 'onhand_preparation': return True # 人工覆写行级库存源(方案 3·放开):通知准备(取数失败/多候选)与匹配阶段(Excel 前)均可。 # 已取代旧 D5 逐行选源(select_line_inventory_source,已下线)。 - if action == 'override_line_inventory_source' and code in { - 'inventory_source_routing', 'inventory_preparation', 'inventory_matching', + if action == 'override_line_onhand_source' and code in { + 'onhand_source_routing', 'onhand_preparation', 'onhand_matching', }: return True navigation_owners = { @@ -904,8 +904,8 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: 'confirm_customer': {'customer_resolution'}, 'adjudicate_duplicate': {'duplicate_detection'}, 'resolve_field_conflicts': {'field_conflict_resolution'}, - 'open_inventory_match_review': {'inventory_matching'}, - 'open_shortage_review': {'inventory_sufficiency'}, + 'open_onhand_match_review': {'onhand_matching'}, + 'open_shortage_review': {'onhand_sufficiency'}, 'regenerate_manual_upload_todo': {'manual_upload_handoff'}, } # 人工交接 Gate 可由用户显式重新发起 RPA;自动上传开关不影响该恢复入口。 @@ -1153,17 +1153,17 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = { 'inventory_source_unavailable': 'needs_human', # 候选源配置被禁用(需人工改路由) 'inventory_source_conflicted': 'needs_human', # 路由规则冲突 'inventory_source_changed': 'retryable_tech', # 配置漂移,可重跑规则 - 'inventory_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认 + 'onhand_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认 'retry_with_latest_rules': 'retryable_tech', # --- 库存准备 / RPA --- 'inventory_preparation_failed': 'retryable_tech', 'inventory_preparation_waiting': 'retryable_tech', - 'inventory_rpa_queued': 'retryable_tech', - 'inventory_rpa_timeout': 'retryable_tech', - 'inventory_rpa_login_failed': 'retryable_tech', - 'inventory_rpa_export_failed': 'retryable_tech', - 'inventory_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传 + 'onhand_rpa_queued': 'retryable_tech', + 'onhand_rpa_timeout': 'retryable_tech', + 'onhand_rpa_login_failed': 'retryable_tech', + 'onhand_rpa_export_failed': 'retryable_tech', + 'onhand_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传 'inventory_file_missing': 'retryable_tech', 'inventory_file_empty': 'retryable_tech', 'inventory_file_identity_mismatch': 'needs_human', @@ -1244,9 +1244,9 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = { INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = ( 'order_freeze_readiness', # 订单 Snapshot 冻结(sub_stage=frozen) - 'inventory_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated) - 'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready) - 'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking) + 'onhand_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated) + 'onhand_preparation', # 多源快照准备(sub_stage=snapshots_ready) + 'onhand_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking) ) INVENTORY_SUB_STAGES: Final[frozenset[str]] = frozenset({ @@ -1369,9 +1369,9 @@ def derive_position(*, gate_code: str | None, review_status: str | None) -> str 'order_field_extraction': 'parse_review', 'customer_resolution': 'customer_review', 'reservation_validation': 'rsv_req', - 'inventory_preparation': 'inventory_pending', - 'inventory_matching': 'ready_to_match', - 'inventory_sufficiency': 'shortage_review', + 'onhand_preparation': 'inventory_pending', + 'onhand_matching': 'ready_to_match', + 'onhand_sufficiency': 'shortage_review', 'order_freeze_readiness': 'order_freeze', 'excel_readiness': 'ready_to_export', 'artifact_generation': 'export_ready', @@ -1404,44 +1404,44 @@ def derive_todo_category(*, user_mode: str, position: str | None = None) -> str: # ============================================================ STAGE_CAPABILITY_DEFINITIONS: Final[dict[str, dict[str, Any]]] = { - 'override_line_inventory_source': { + 'override_line_onhand_source': { 'stage': 'fulfillment_prep', 'scope': 'line', - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'invalidate': { - 'inventory_field_mapping', 'inventory_matching', - 'inventory_sufficiency', 'excel_readiness', 'artifact_generation', + 'onhand_field_mapping', 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', }, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', }, - 'retry_inventory_preparation': { + 'retry_onhand_preparation': { 'stage': 'fulfillment_prep', 'scope': 'task', - 'action_code': 'retry_inventory_preparation', + 'action_code': 'retry_onhand_preparation', 'invalidate': { - 'inventory_field_mapping', 'inventory_matching', - 'inventory_sufficiency', 'excel_readiness', 'artifact_generation', + 'onhand_field_mapping', 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', }, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', }, # 重新匹配库存:只在通知准备阶段内、已有匹配结果(且 Excel 未生成)时可用。 # 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游满足性/Excel, # 因此不重置回 inventory_preparation,也不作废上游 source/mapping。 - 'retry_inventory_matching': { + 'retry_onhand_matching': { 'stage': 'fulfillment_prep', 'scope': 'task', - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'invalidate': { - 'inventory_matching', 'inventory_sufficiency', + 'onhand_matching', 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', }, 'invalidate_change_type': 'inventory_field_mapping_changed', - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', }, - 'reload_inventory_result': { + 'reload_onhand_result': { 'stage': 'fulfillment_prep', 'scope': 'task', - 'action_code': 'reload_inventory_result', + 'action_code': 'reload_onhand_result', 'invalidate': frozenset(), 'reset_to': None, }, diff --git a/backend/app/services/shipping_notice/process_gate_dependency.py b/backend/app/services/shipping_notice/process_gate_dependency.py index c1449f33..5c0e4280 100644 --- a/backend/app/services/shipping_notice/process_gate_dependency.py +++ b/backend/app/services/shipping_notice/process_gate_dependency.py @@ -21,13 +21,13 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'customer_resolution', 'duplicate_detection', 'field_conflict_resolution', - 'inventory_source_routing', + 'onhand_source_routing', 'order_freeze_readiness', 'task_creation', - 'inventory_preparation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -36,8 +36,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'reservation_changed': ( 'duplicate_detection', 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -45,8 +45,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { ), 'part_number_changed': ( 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -54,8 +54,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { ), 'quantity_changed': ( 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -65,37 +65,37 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'duplicate_detection', 'order_freeze_readiness', 'task_creation', - 'inventory_preparation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'inventory_source_changed': ( - 'inventory_preparation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'inventory_file_changed': ( - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'inventory_field_mapping_changed': ( - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -113,7 +113,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'task_creation', ), 'field_conflict_resolved': ( - 'inventory_source_routing', + 'onhand_source_routing', 'order_freeze_readiness', 'task_creation', ), @@ -125,15 +125,15 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'reservation_confirmed': ( 'duplicate_detection', 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'line_fulfillment_decision_changed': ( - 'inventory_sufficiency', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -153,13 +153,13 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = { 'field_conflict_resolution': ('duplicate_detection',), 'task_creation': ('field_conflict_resolution',), 'order_freeze_readiness': ('task_creation',), - 'inventory_source_routing': ('order_freeze_readiness',), - 'inventory_preparation': ('inventory_source_routing',), - 'inventory_field_mapping': ('inventory_preparation',), - 'inventory_matching': ('inventory_field_mapping',), - 'inventory_sufficiency': ('inventory_matching',), + 'onhand_source_routing': ('order_freeze_readiness',), + 'onhand_preparation': ('onhand_source_routing',), + 'onhand_field_mapping': ('onhand_preparation',), + 'onhand_matching': ('onhand_field_mapping',), + 'onhand_sufficiency': ('onhand_matching',), # 滚动导出仅要求已完成库存匹配;库存不足仍由 inventory_sufficiency 独立阻断未导出行。 - 'excel_readiness': ('inventory_matching',), + 'excel_readiness': ('onhand_matching',), 'artifact_generation': ('excel_readiness',), 'freight_upload_rpa': ('artifact_generation',), 'manual_upload_handoff': ('freight_upload_rpa',), @@ -217,5 +217,5 @@ def assert_process_gate_dependency_integrity() -> None: ) # 仅重新生成 Excel 不得失效库存匹配。 excel_only = set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only']) - assert 'inventory_matching' not in excel_only + assert 'onhand_matching' not in excel_only assert 'artifact_generation' in excel_only diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index efd03c70..646eff2f 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -3,9 +3,9 @@ services/shipping_notice/process_gate_executor.py 用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。 依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、 - inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 + onhand_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 document_layout.lifecycle、process_gate_contract、process_gate_bridge、 - inventory_candidate_projection、recovery_invalidation_service。 + onhand_candidate_projection、recovery_invalidation_service。 逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态; 库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 Run/版面路径; co8 后文档/Run 解析仅经 review_case_id / task_id,不再读 WorkflowItem; @@ -73,7 +73,7 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({ 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', 'regenerate_manual_upload_todo', }) @@ -81,8 +81,8 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({ # 库存准备:仅这些已有动作码强制 mode=retry_rpa(跳过快照复用、新建 Attempt)。 # poll / 首次自动投递不得落入此集合;禁止「人工入口一律 retry_rpa」。 _FORCE_INVENTORY_RPA_ACTION_CODES: frozenset[str] = frozenset({ - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', + 'retry_onhand_preparation', + 'retry_onhand_from_preparation', }) # 人工入口:前端应导航,不把业务状态改为 passed。 @@ -94,7 +94,7 @@ _NAVIGATION_ACTIONS: frozenset[str] = frozenset({ 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', }) @@ -191,16 +191,16 @@ def _dispatch_action( 'retry_customer_resolution': _handle_recheck_task_gates, 'retry_duplicate_detection': _handle_recheck_task_gates, 'retry_task_creation': _handle_retry_task_creation, - 'retry_inventory_preparation': _handle_retry_inventory_preparation, - 'reload_inventory_result': _handle_reload_inventory_result, - 'poll_inventory_preparation': _handle_retry_inventory_preparation, - 'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping, - 'retry_inventory_matching': _handle_retry_inventory_matching, - 'retry_inventory_from_preparation': _handle_retry_inventory_preparation, - 'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping, - 'retry_inventory_from_matching': _handle_retry_inventory_from_matching, - 'override_line_inventory_source': _handle_override_line_inventory_source, - 'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency, + 'retry_onhand_preparation': _handle_retry_inventory_preparation, + 'reload_onhand_result': _handle_reload_inventory_result, + 'poll_onhand_preparation': _handle_retry_inventory_preparation, + 'retry_onhand_field_mapping': _handle_retry_inventory_field_mapping, + 'retry_onhand_matching': _handle_retry_inventory_matching, + 'retry_onhand_from_preparation': _handle_retry_inventory_preparation, + 'retry_onhand_from_field_mapping': _handle_retry_inventory_from_field_mapping, + 'retry_onhand_from_matching': _handle_retry_inventory_from_matching, + 'override_line_onhand_source': _handle_override_line_inventory_source, + 'recheck_onhand_sufficiency': _handle_recheck_inventory_sufficiency, 'recheck_excel_readiness': _handle_recheck_excel_readiness, 'regenerate_excel_artifact': _handle_regenerate_excel, 'poll_freight_upload_rpa': _handle_freight_upload_rpa, @@ -213,8 +213,8 @@ def _dispatch_action( 'confirm_customer': _manual_open('confirm_customer', 'customer_resolution'), 'adjudicate_duplicate': _manual_open('adjudicate_duplicate', 'duplicate_detection'), 'resolve_field_conflicts': _manual_open('resolve_field_conflicts', 'field_conflict_resolution'), - 'open_inventory_match_review': _manual_open('open_inventory_match_review', 'inventory_matching'), - 'open_shortage_review': _manual_open('open_shortage_review', 'inventory_sufficiency'), + 'open_onhand_match_review': _manual_open('open_onhand_match_review', 'onhand_matching'), + 'open_shortage_review': _manual_open('open_shortage_review', 'onhand_sufficiency'), } handler = handlers.get(action_code) if handler is None: @@ -374,7 +374,7 @@ def _resolve_line_inventory_scope( 由 snapshot_line_id / line_scope_key 解析行级库存作用域。 核心逻辑:snapshot_line_id → SnapshotLine.line_no → CandidateLine.source_codes_json。 - Gate 直调 ensure_inventory 时绕过 progress_workflow,必须在此收窄源范围。 + Gate 直调 ensure_onhand 时绕过 progress_workflow,必须在此收窄源范围。 Args: task: 当前 OT / 兼容 Notice owner。 @@ -396,7 +396,7 @@ def _resolve_line_inventory_scope( return None from app.models import ShippingOrderSnapshot - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) scoped_line = next( @@ -819,10 +819,10 @@ def _handle_retry_inventory_preparation( """ 重试/轮询库存准备。 - 核心逻辑:按已有动作码映射 ensure_inventory mode(retry_inventory_preparation → + 核心逻辑:按已有动作码映射 ensure_inventory mode(retry_onhand_preparation → retry_rpa;poll → auto + allow_auto_retry=False;首次 gate_attempt_passed 保持 auto); 若携带 line_scope_key/snapshot_line_id,则按该行 candidate.source_codes_json 收窄 - RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory 后按任务事实推导 + RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory(阶段码 ensure_onhand)后按任务事实推导 细粒度阻断码,再同步履约门禁。 Args: @@ -834,8 +834,8 @@ def _handle_retry_inventory_preparation( Gate Attempt outcome 字典(outcome / blocking_reason_code / effective_result_json 等)。 """ from app.models import ShippingNotice - from app.services.shipping_notice.inventory_workflow import ensure_inventory - from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round + from app.services.shipping_notice.onhand_workflow import ensure_inventory + from app.services.shipping_notice.onhand_recovery_service import create_inventory_preparation_round from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, @@ -854,7 +854,7 @@ def _handle_retry_inventory_preparation( # [STEP 0A] inventory_preparation 只消费 routing 已冻结的 CandidateSet。 # 若历史数据越过 routing,直接阻断,不在库存准备阶段偷偷补做裁决。 if task is not None: - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, get_active_candidate_sources, @@ -874,26 +874,26 @@ def _handle_retry_inventory_preparation( 'blocking_reason_code': 'inventory_source_routing_required', 'effective_result_json': {'findings': [], 'routing_required': True}, 'output_snapshot': { - 'action_code': str(payload.get('action_code') or 'retry_inventory_preparation'), + 'action_code': str(payload.get('action_code') or 'retry_onhand_preparation'), 'routing_required': True, }, } - if task is not None and payload.get('action_code') == 'poll_inventory_preparation': + if task is not None and payload.get('action_code') == 'poll_onhand_preparation': # 回调已将本轮准备收口为失败后,已排队的旧 poll 只能重投影正式 Gate。 # 若继续调用 ensure_inventory,会把精确的 RPA 超时覆盖为泛化的缺库存文件。 - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt - failed_preparation_query = ShippingInventoryPreparationAttempt.query.filter_by( + failed_preparation_query = ShippingOnhandPreparationAttempt.query.filter_by( task_id=int(task.id), execution_id=int(execution.id), status='failed', ) if execution.candidate_set_id is not None: failed_preparation_query = failed_preparation_query.filter( - ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) + ShippingOnhandPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) ) failed_preparation = failed_preparation_query.order_by( - ShippingInventoryPreparationAttempt.attempt_no.desc() + ShippingOnhandPreparationAttempt.attempt_no.desc() ).first() if failed_preparation is not None: prep_reason = inventory_preparation_reason_code(task) @@ -907,7 +907,7 @@ def _handle_retry_inventory_preparation( 'poll_skipped_after_callback_failure': True, }, 'output_snapshot': { - 'action_code': 'poll_inventory_preparation', + 'action_code': 'poll_onhand_preparation', 'poll_skipped_after_callback_failure': True, }, } @@ -925,7 +925,7 @@ def _handle_retry_inventory_preparation( else payload.get('snapshot_line_id') ), ) - if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: + if task is not None and payload.get('action_code') != 'poll_onhand_preparation' and not is_initial_auto_dispatch: # 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实, # 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。 if not task.order_snapshot_id: @@ -948,11 +948,11 @@ def _handle_retry_inventory_preparation( # override_line_inventory_source)。 # 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope # 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。 - if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation': + if str(payload.get('action_code') or '').strip() == 'retry_onhand_preparation': from app.services.shipping_notice.upload_attempt_service import latest_export_artifact if latest_export_artifact(task) is None: - from app.services.shipping_notice.inventory_candidate_freeze_service import ( + from app.services.shipping_notice.onhand_candidate_freeze_service import ( refresh_candidates_from_current_routing, refresh_line_candidates_from_current_routing, ) @@ -975,9 +975,9 @@ def _handle_retry_inventory_preparation( if refreshed_scope is not None: line_scope = refreshed_scope if payload.get('action_code') in { - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', + 'retry_onhand_preparation', + 'retry_onhand_from_preparation', + 'retry_onhand_from_field_mapping', }: invalidate_inventory_downstream( execution=execution, @@ -991,7 +991,7 @@ def _handle_retry_inventory_preparation( task=task, execution_id=int(execution.id), recovery_plan_id=int(recovery_plan_id) if recovery_plan_id else None, - action_code=str(payload.get('action_code') or 'retry_inventory_preparation'), + action_code=str(payload.get('action_code') or 'retry_onhand_preparation'), operation_id=str(payload.get('operation_id') or '').strip() or None, gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None, ) @@ -1016,13 +1016,13 @@ def _handle_retry_inventory_preparation( inventory_payload['mode'] = 'auto' else: inventory_payload['mode'] = 'retry_rpa' - if action_code == 'poll_inventory_preparation': + if action_code == 'poll_onhand_preparation': # [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试, # 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。 inventory_payload['allow_auto_retry'] = False response = ensure_inventory(inventory_payload) if preparation_round is not None: - from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round + from app.services.shipping_notice.onhand_recovery_service import sync_inventory_preparation_round rpa_result = ((response.get('data') or {}).get('rpa') or {}) if isinstance(response, dict) else {} sync_inventory_preparation_round(preparation_attempt=preparation_round, result=rpa_result) @@ -1032,7 +1032,7 @@ def _handle_retry_inventory_preparation( else 'inventory_preparation_failed' ) outcome = _tool_outcome( - action_code='retry_inventory_preparation', + action_code='retry_onhand_preparation', response=response, # 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成; # Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分 @@ -1057,7 +1057,7 @@ def _handle_override_line_inventory_source( 校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写; 覆写后把该行候选钉为所选源。人工指定即定论:不再重跑路由规则。 - 当前在 routing:passed 后由 complete → enqueue 首投库存准备(按冻结源取数)。 - - 当前在准备/匹配:定向回 inventory_preparation,mode=auto(有快照复用,无则 RPA)。 + - 当前在准备/匹配:定向回 onhand_preparation,mode=auto(有快照复用,无则 RPA)。 Args: execution: 门禁执行上下文。 @@ -1069,12 +1069,12 @@ def _handle_override_line_inventory_source( """ from app.core.errors import ConflictError, ValidationError from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, list_database_inventory_sources, ) from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - from app.services.shipping_notice.inventory_candidate_freeze_service import ( + from app.services.shipping_notice.onhand_candidate_freeze_service import ( freeze_manual_line_source_selection, ) @@ -1123,7 +1123,7 @@ def _handle_override_line_inventory_source( event_type='review_line_source_overridden', aggregate_type='shipping_notice', aggregate_id=str(task.task_no), - action='override_line_inventory_source', + action='override_line_onhand_source', actor_type='user' if actor_id else 'system', actor_id=actor_id, task_no=task.task_no, @@ -1139,7 +1139,7 @@ def _handle_override_line_inventory_source( 'selected_line_no': line_no, 'all_lines_selected': False, }, 'output_snapshot': { - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'candidate_set_id': candidate_result.candidate_set_id, 'all_lines_selected': False, }, @@ -1148,7 +1148,7 @@ def _handle_override_line_inventory_source( # 人工指定源即定论:冻结候选后不再重跑路由规则。routing Gate 以 passed 收口, # complete_gate_attempt → _enqueue_auto_progress_after_gate_pass 首投 inventory_preparation #(按已冻结源取数:有 ready 快照复用,否则再 RPA)。禁止在本 Attempt 内递归推进。 - if gate.gate_code == 'inventory_source_routing': + if gate.gate_code == 'onhand_source_routing': return { 'outcome': 'passed', 'effective_result_json': { @@ -1156,7 +1156,7 @@ def _handle_override_line_inventory_source( 'selected_line_no': line_no, 'all_lines_selected': True, }, 'output_snapshot': { - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'candidate_set_id': candidate_result.candidate_set_id, 'all_lines_selected': True, }, @@ -1172,7 +1172,7 @@ def _handle_override_line_inventory_source( task.task_no, trigger='manual_override_source', operator_id=actor_id, - resume_gate_code='inventory_preparation', + resume_gate_code='onhand_preparation', inventory_mode='auto', ) sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id) @@ -1181,7 +1181,7 @@ def _handle_override_line_inventory_source( # RPA 失败则保留 inventory_preparation 的人工恢复入口,后续 Gate 不得被放行。 db.session.flush() preparation_gate = ShippingProcessGate.query.filter_by( - execution_id=int(execution.id), gate_code='inventory_preparation', + execution_id=int(execution.id), gate_code='onhand_preparation', ).first() gate_status = str(getattr(preparation_gate, 'status', '') or '').strip().lower() reason_code = str(getattr(preparation_gate, 'blocking_reason_code', '') or '').strip() or None @@ -1201,7 +1201,7 @@ def _handle_override_line_inventory_source( 'inventory_preparation_status': gate_status or 'blocked_retryable', }, 'output_snapshot': { - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'inventory_preparation_status': gate_status or 'blocked_retryable', }, } @@ -1216,14 +1216,14 @@ def _task_has_frozen_inventory_source(task: ShippingOrderTask) -> bool: """ 任务是否已冻结库存源候选(CandidateSet 已存在且至少有一个 Source)。 - 【AI 触发时机】:inventory_preparation Gate 执行前判断是否需要补做路由裁决。 + 【AI 触发时机】:onhand_preparation Gate 执行前判断是否需要补做路由裁决。 核心逻辑:统一以冻结 CandidateSet 为库存源真相;有候选源即视为已裁决/冻结, 没有则说明 routing Gate 虽被复核门禁同步判为 passed,但候选从未落库,需补裁决。 """ - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - return bool(task_frozen_inventory_source_codes(task)) + return bool(task_frozen_onhand_source_codes(task)) def _resolve_shipping_notice(execution: ShippingProcessExecution) -> ShippingNotice | None: @@ -1247,8 +1247,8 @@ def _handle_reload_inventory_result( RPA 超时阻断,让用户明确选择“重新获取库存”或上传库存文件。 """ from app.models import ShippingNotice - from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, sync_fulfillment_gates_from_task, @@ -1260,7 +1260,7 @@ def _handle_reload_inventory_result( 'outcome': 'blocked_retryable', 'blocking_reason_code': 'inventory_preparation_failed', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + 'output_snapshot': {'action_code': 'reload_onhand_result', 'snapshot_found': False}, } response = _try_reuse_inventory_snapshot( task, @@ -1280,7 +1280,7 @@ def _handle_reload_inventory_result( 'outcome': 'blocked_retryable', 'blocking_reason_code': inventory_preparation_reason_code(task), 'effective_result_json': {'findings': [], 'snapshot_found': False}, - 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + 'output_snapshot': {'action_code': 'reload_onhand_result', 'snapshot_found': False}, } sync_fulfillment_gates_from_task( execution=execution, @@ -1288,7 +1288,7 @@ def _handle_reload_inventory_result( actor_id=payload.get('actor_user_id'), ) return _tool_outcome( - action_code='reload_inventory_result', + action_code='reload_onhand_result', response=response, blocking_reason_code=inventory_preparation_reason_code(task), ) @@ -1304,7 +1304,7 @@ def _handle_retry_inventory_field_mapping( 重试库存字段映射:检查活跃库存文件 mapping_confirmed / 已解析行,不重跑库存准备。 """ from app.models import ShippingNotice - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome task = _resolve_order_task(execution) @@ -1313,10 +1313,10 @@ def _handle_retry_inventory_field_mapping( 'outcome': 'blocked_retryable', 'blocking_reason_code': 'inventory_mapping_required', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'retry_inventory_field_mapping'}, + 'output_snapshot': {'action_code': 'retry_onhand_field_mapping'}, } inv_file = active_inventory_file_for_task(task) - from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_lines_for_task mapped = bool( inv_file is not None @@ -1325,7 +1325,7 @@ def _handle_retry_inventory_field_mapping( ) apply_gate_outcome( execution=execution, - gate_code='inventory_field_mapping', + gate_code='onhand_field_mapping', passed=mapped, # 映射来自已发布库存模板,缺失或不确定只能由系统重试/配置治理解决, # 不能把技术映射确认伪装为人工业务操作。 @@ -1345,13 +1345,13 @@ def _handle_retry_inventory_field_mapping( return { 'outcome': 'passed', 'effective_result_json': {'findings': [], 'mapping_confirmed': True}, - 'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': True}, + 'output_snapshot': {'action_code': 'retry_onhand_field_mapping', 'passed': True}, } return { 'outcome': 'blocked_retryable', 'blocking_reason_code': 'inventory_mapping_required', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': False}, + 'output_snapshot': {'action_code': 'retry_onhand_field_mapping', 'passed': False}, } @@ -1364,14 +1364,14 @@ def _handle_retry_inventory_from_field_mapping( """ 从库存字段映射恢复:失效匹配下游后重跑映射;映射通过后仍同 Attempt 嵌套匹配。 - Follow-up P1:映射 Attempt 应收口后仅 enqueue ``inventory_matching`` Attempt, + Follow-up P1:映射 Attempt 应收口后仅 enqueue ``onhand_matching`` Attempt, 禁止在本函数内直接调用 ``_handle_retry_inventory_matching``(跨 Gate 嵌套债务)。 """ from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream invalidate_inventory_downstream( execution=execution, - action_code='retry_inventory_from_field_mapping', + action_code='retry_onhand_from_field_mapping', attempt_id=payload.get('attempt_id'), actor_id=payload.get('actor_user_id'), ) @@ -1401,11 +1401,11 @@ def _handle_retry_inventory_matching( 核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和 “匹配成功但库存不足”。匹配成功但库存不足时,前置的 - ``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency; - 当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的 + ``sync_fulfillment_gates_from_task`` 已将缺口写入 onhand_sufficiency; + 当前 onhand_matching Attempt 必须以 passed 收口,否则会覆盖正确的 满足性 Gate 归属并再次显示“进入库存匹配处理”。 行级点击(line_scope_key/snapshot_line_id)走 match_inventory_line,并在回退 - ensure_inventory 时携带该行 source_codes。 + ensure_onhand 时携带该行 source_codes。 """ from app.services.shipping_notice.fulfillment_workflow import match_inventory, match_inventory_line from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task @@ -1438,7 +1438,7 @@ def _handle_retry_inventory_matching( sufficient = bool(task is not None and match_completed(task)) match_status = 'fulfillable' if sufficient else ('unfulfillable' if match_complete else '') has_shortage = match_complete and not sufficient - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task shortage = [ row for row in load_current_match_facts_by_task(getattr(task, 'id', None)).values() @@ -1455,7 +1455,7 @@ def _handle_retry_inventory_matching( 'shortage': shortage, }, 'output_snapshot': { - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'tool_status': 'passed', 'business_result': 'fulfillable', }, @@ -1473,13 +1473,13 @@ def _handle_retry_inventory_matching( 'shortage': shortage, }, 'output_snapshot': { - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'tool_status': 'needs_human', 'business_result': 'inventory_shortage', }, } outcome = _tool_outcome( - action_code='retry_inventory_matching', + action_code='retry_onhand_matching', response=response, blocking_reason_code='inventory_match_failed', invalidate_change_type=None, @@ -1498,7 +1498,7 @@ def _handle_retry_inventory_from_matching( invalidate_inventory_downstream( execution=execution, - action_code='retry_inventory_from_matching', + action_code='retry_onhand_from_matching', attempt_id=payload.get('attempt_id'), actor_id=payload.get('actor_user_id'), ) @@ -1529,11 +1529,11 @@ def _handle_recheck_inventory_sufficiency( 'blocking_reason_code': 'inventory_insufficient', 'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'}, 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency'}, + 'output_snapshot': {'action_code': 'recheck_onhand_sufficiency'}, } # [BE-满足性复盘] 复核先按当前放行/匹配事实重算任务级履约态,避免"Gate 认为满足、 # 任务却仍标 unfulfillable/shortage"的旧状态残留。仅在确有匹配行时重算(空事实不误标缺货)。 - from app.models import ShippingNoticeLineInventoryMatch as _MatchRow + from app.models import ShippingNoticeLineOnhandMatch as _MatchRow if getattr(task, 'id', None) is not None and ( _MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None @@ -1542,16 +1542,16 @@ def _handle_recheck_inventory_sufficiency( from app.services.shipping_notice.fulfillment_workflow import match_completed sufficient = match_completed(task) - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch shortage = [ {'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty} - for row in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + for row in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'} ] match_status = 'fulfillable' if sufficient else 'unfulfillable' apply_gate_outcome( execution=execution, - gate_code='inventory_sufficiency', + gate_code='onhand_sufficiency', passed=sufficient, outcome=None if sufficient else 'blocked_manual', effective_result={ @@ -1569,14 +1569,14 @@ def _handle_recheck_inventory_sufficiency( return { 'outcome': 'passed', 'effective_result_json': {'findings': [], 'match_status': match_status}, - 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True}, + 'output_snapshot': {'action_code': 'recheck_onhand_sufficiency', 'passed': True}, } return { 'outcome': 'blocked_manual', 'blocking_reason_code': 'inventory_insufficient', 'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'}, 'effective_result_json': {'findings': [], 'shortage': shortage}, - 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': False}, + 'output_snapshot': {'action_code': 'recheck_onhand_sufficiency', 'passed': False}, } @@ -1786,7 +1786,7 @@ def _handle_inventory_reroute( from app.models import ShippingOrderReviewCase from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing - if gate.gate_code != 'inventory_source_routing': + if gate.gate_code != 'onhand_source_routing': raise ValidationError( 'Action does not belong to this gate', code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', diff --git a/backend/app/services/shipping_notice/process_gate_job_service.py b/backend/app/services/shipping_notice/process_gate_job_service.py index ff00fd24..71cddbb2 100644 --- a/backend/app/services/shipping_notice/process_gate_job_service.py +++ b/backend/app/services/shipping_notice/process_gate_job_service.py @@ -75,7 +75,7 @@ def cancel_inventory_external_wait_polls(*, gate_id: int, reason: str) -> int: 其执行入口会再次读取 Gate 并自行停止。 Args: - gate_id: inventory_preparation Gate 主键。 + gate_id: onhand_preparation Gate 主键。 reason: 取消原因,写入 Job message 供审计排查。 Returns: @@ -238,13 +238,13 @@ def schedule_waiting_external_poll( execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if execution is None: return None - if str(gate.gate_code or '').strip() == 'inventory_preparation' and execution.task_id: + if str(gate.gate_code or '').strip() == 'onhand_preparation' and execution.task_id: from app.models import ShippingNotice from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.models import ShippingOrderTask task = db.session.get(ShippingOrderTask, int(execution.task_id)) - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task has_inventory_lines = bool(task is not None and has_ready_inventory_file_for_task(task)) if task is not None and has_inventory_lines: @@ -257,8 +257,8 @@ def schedule_waiting_external_poll( # 外部轮询超时是新的、可恢复的业务事实;不能保留原来的 # inventory_rpa_queued,否则页面会同时显示“等待外部”和“人工处理”。 timeout_reason = ( - 'inventory_rpa_timeout' - if str(gate.gate_code or '').strip() == 'inventory_preparation' + 'onhand_rpa_timeout' + if str(gate.gate_code or '').strip() == 'onhand_preparation' else (gate.blocking_reason_code or 'gate_invalidated') ) timeout_action = primary_next_action_for_gate( @@ -314,11 +314,11 @@ def schedule_waiting_external_poll( # (例如从 inventory_matching 回到 inventory_preparation)完成后,原 Gate # 可能短暂保留 waiting_external,但不能把准备阶段的轮询动作投递到该原 Gate; # 否则 executor 的归属校验会把过期 poll 误记为技术失败。 - if not action and str(gate.gate_code or '').strip() == 'inventory_preparation': - action = 'poll_inventory_preparation' + if not action and str(gate.gate_code or '').strip() == 'onhand_preparation': + action = 'poll_onhand_preparation' if ( - str(gate.gate_code or '').strip() != 'inventory_preparation' - and str(action or '').strip() == 'poll_inventory_preparation' + str(gate.gate_code or '').strip() != 'onhand_preparation' + and str(action or '').strip() == 'poll_onhand_preparation' ): _LOGGER.info( 'skip stale inventory-preparation poll: gate_id=%s gate_code=%s', @@ -344,7 +344,7 @@ def schedule_waiting_external_poll( execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if execution is None: return None - if str(gate.gate_code or '').strip() == 'inventory_preparation': + if str(gate.gate_code or '').strip() == 'onhand_preparation': poll_count = int(effective.get('poll_count') or 0) + 1 effective['poll_count'] = poll_count gate.effective_result_json = effective @@ -391,7 +391,7 @@ def run_inventory_external_wait_poll(*, gate_id: int) -> dict[str, Any]: outcome = _handle_retry_inventory_preparation( execution=execution, gate=gate, - payload={'action_code': 'poll_inventory_preparation'}, + payload={'action_code': 'poll_onhand_preparation'}, ) db.session.flush() db.session.refresh(gate) diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 933e53f7..91852971 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -49,7 +49,7 @@ _PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS: frozenset[str] = frozenset({ 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', }) @@ -63,7 +63,7 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = { 'confirm_customer': 'draft', 'adjudicate_duplicate': 'draft', 'resolve_field_conflicts': 'evidence', - 'open_inventory_match_review': 'draft', + 'open_onhand_match_review': 'draft', 'open_shortage_review': 'draft', } @@ -134,8 +134,8 @@ def _resolve_recovery_next_action( """ 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - [STEP 1] 库存 RPA 超时/耗尽下发 ``retry_inventory_matching``(优先复用已有快照重匹配, - 无快照则回退 RPA);其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。 + [STEP 1] 库存 RPA 超时/耗尽下发 ``retry_onhand_matching``(优先复用已有快照重匹配, + 无快照则回退 RPA);其他库存准备失败下发 ``retry_onhand_preparation``,由用户明确重新触发 RPA。 [STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。 [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留 RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。 @@ -148,27 +148,27 @@ def _resolve_recovery_next_action( has_formal_task = bool(execution and getattr(execution, 'task_id', None)) # [STEP 1] RPA 超时/耗尽时先重读已有结果,其他库存准备失败仍允许重新运行 RPA。 - if blocking_gate_code == 'inventory_preparation': + if blocking_gate_code == 'onhand_preparation': inventory_action = inventory_preparation_primary_action(status, normalized_reason) if inventory_action: return inventory_action, False # 库存匹配失败属于业务可恢复阻断;即使 Gate 责任方是 worker, # 业务用户仍必须能重新提交匹配,不能只投影“可重试”状态而隐藏按钮。 - if blocking_gate_code == 'inventory_matching' and ( + if blocking_gate_code == 'onhand_matching' and ( has_formal_task or status == 'blocked_retryable' ): - return 'retry_inventory_matching', False + return 'retry_onhand_matching', False # 库存不足只阻断履约决策,不能把已经确认的活动 Excel 误判为库存源失效。 # 因此默认复用该快照执行重匹配;用户若明确选择重新获取库存,再由 RecoveryPlan # 回到 inventory_preparation 强制触发 RPA。 if ( - blocking_gate_code == 'inventory_sufficiency' + blocking_gate_code == 'onhand_sufficiency' and has_formal_task and _has_confirmed_inventory_for_matching(execution) ): - return 'retry_inventory_matching', False + return 'retry_onhand_matching', False # [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。 if ( @@ -203,15 +203,15 @@ def _resolve_recovery_next_action( # 正式 OT 的库存匹配只能重试,不能下发无写操作的复核导航入口。 if not next_action: recovery_targets = full.get('recovery_targets') or [] - if recovery_targets and blocking_gate_code == 'inventory_matching' and not has_formal_task: - next_action = 'open_inventory_match_review' + if recovery_targets and blocking_gate_code == 'onhand_matching' and not has_formal_task: + next_action = 'open_onhand_match_review' technical_auto_only = False - elif recovery_targets and blocking_gate_code == 'inventory_sufficiency': + elif recovery_targets and blocking_gate_code == 'onhand_sufficiency': next_action = 'open_shortage_review' technical_auto_only = False # 库存准备/匹配/货代上传 RPA 在 blocked_retryable 时仍允许业务用户恢复。 if not next_action and blocking_gate_code in { - 'inventory_preparation', 'inventory_matching', 'freight_upload_rpa', + 'onhand_preparation', 'onhand_matching', 'freight_upload_rpa', }: candidate = _projection_primary_next_action( gate_code=blocking_gate_code, status=status, @@ -531,7 +531,7 @@ def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) - """判断正式任务是否已有可复用、未失效的已确认库存快照。""" if not execution.task_id: return False - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task task = ShippingOrderTask.query.get(int(execution.task_id)) return bool(task is not None and has_ready_inventory_file_for_task(task)) @@ -573,12 +573,12 @@ def _ensure_editable_row_source_actions( if not _row_source_editable(execution): return code = str(gate_code or '').strip().lower() - if code not in {'inventory_preparation', 'inventory_matching'}: + if code not in {'onhand_preparation', 'onhand_matching'}: return # 方案 3·放开:覆写(任意已启用源)作为**唯一**行源编辑动作;D5 的「选定」不再作为独立入口, # 多源歧义行也由覆写下拉承担(覆写接受任意已启用源),避免两处选源入口重复(问题 3/4)。 # retry_inventory_* 仍按其门禁语义在 blocking 分支授权,避免在推进态错误暴露重试入口。 - for side in ('override_line_inventory_source',): + for side in ('override_line_onhand_source',): if side not in allowed_actions and is_business_user_action(side): allowed_actions.append(side) @@ -630,12 +630,12 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, blocking = None if ( isinstance(current, dict) - and str(current.get('gate_code') or '').strip().lower() == 'inventory_matching' + and str(current.get('gate_code') or '').strip().lower() == 'onhand_matching' and str(current.get('status') or '').strip().lower() == 'pending' and _has_confirmed_inventory_for_matching(execution) ): # 库存快照已确认但匹配未落终态,说明自动推进已中断;不能继续显示系统处理中。 - current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_inventory_matching'} + current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_matching'} if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | { 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', }: @@ -686,23 +686,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, action_items: list[dict[str, str]] = [] is_formal_inventory_matching = bool( getattr(execution, 'task_id', None) - and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_matching' + and str((blocking or {}).get('gate_code') or '').strip().lower() == 'onhand_matching' ) is_formal_inventory_sufficiency = bool( getattr(execution, 'task_id', None) - and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_sufficiency' + and str((blocking or {}).get('gate_code') or '').strip().lower() == 'onhand_sufficiency' ) recovery_targets = full.get('recovery_targets') or [] if is_formal_inventory_matching: recovery_targets = [ target for target in recovery_targets - if str(target.get('action_code') or '').strip() == 'retry_inventory_from_preparation' + if str(target.get('action_code') or '').strip() == 'retry_onhand_from_preparation' ] elif is_formal_inventory_sufficiency: # Gate 16 对用户只公开稳定动作码:重匹配复用当前快照;重新获取库存才回到 RPA。 recovery_targets = [ target for target in recovery_targets - if str(target.get('action_code') or '').strip() == 'retry_inventory_preparation' + if str(target.get('action_code') or '').strip() == 'retry_onhand_preparation' ] # 一个 Notice 只能有一个 Excel;错误导出需要创建新的 Notice,而非替代旧 Artifact。 recovery_targets = [ diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index 845f8f63..8a82dcae 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -122,21 +122,21 @@ def _primary_recovery_action( *, execution: ShippingProcessExecution, gate: ShippingProcessGate, ) -> str | None: """按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。""" - if gate.gate_code == 'inventory_preparation': + if gate.gate_code == 'onhand_preparation': return inventory_preparation_primary_action(gate.status, gate.blocking_reason_code) # 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。 - if gate.gate_code == 'inventory_matching' and execution.task_id: - return 'retry_inventory_matching' - if gate.gate_code == 'inventory_sufficiency' and execution.task_id: + if gate.gate_code == 'onhand_matching' and execution.task_id: + return 'retry_onhand_matching' + if gate.gate_code == 'onhand_sufficiency' and execution.task_id: from app.models import ShippingOrderTask - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task task = ShippingOrderTask.query.get(int(execution.task_id)) if ( task is not None and has_ready_inventory_file_for_task(task) ): - return 'retry_inventory_matching' + return 'retry_onhand_matching' return gate.next_action_code or primary_next_action_for_gate( gate_code=gate.gate_code, status=gate.status, ) @@ -196,6 +196,7 @@ def request_gate_action( 核心逻辑:校验 action 属于契约且与当前门禁主要动作一致(或为同门禁允许的附属动作); 创建 queued Attempt 后,同步动作立即 execute_queued_attempt,异步动作入队 Gate Job。 客户端禁止提交起始阶段/目标状态/Worker 名。 + retry_onhand_from_* 打在错误 Gate 上时返回 SHIPPING.RECOVERY_TARGET_INVALID。 Args: execution_no / gate_code: 定位目标。 @@ -246,7 +247,7 @@ def request_gate_action( # 跨阶段恢复目标先做 Gate 归属校验;错误 Gate 必须返回稳定的 # RECOVERY_TARGET_INVALID,而不是被普通技术动作权限错误遮蔽。 recovery_definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action) - if action.startswith('retry_inventory_from_') and recovery_definition is None: + if action.startswith('retry_onhand_from_') and recovery_definition is None: raise ValidationError( 'Recovery target is not allowed for current gate', code='SHIPPING.RECOVERY_TARGET_INVALID', @@ -310,14 +311,14 @@ def request_gate_action( # 「重新匹配库存」用专用重匹配编排(只作废匹配下游、经 inventory_matching 重跑), # 避免走 execute_stage_capability 的「宽作废 + 重抓 RPA」,否则会错误重抓库存。 if stage_exempt: - if action == 'retry_inventory_matching': + if action == 'retry_onhand_matching': result = execute_stage_capability_rematch( execution=execution, actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key, ) - elif action == 'override_line_inventory_source': + elif action == 'override_line_onhand_source': # [ROOT CAUSE FIX] 行级覆写必须携带用户选定的 line_no/source_code;通用 # execute_stage_capability 不接收 payload 会丢弃这两个关键字段,导致「操作成功」 # 后选源不落库、不触发 RPA、刷新回原样。此处委托专门的负载透传执行器。 diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index 5080cb3b..9fef160e 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -953,10 +953,10 @@ def _abort_active_attempt_as_superseded( """把占位活动 Attempt 收口为 superseded,并将 Gate 复位为可重评状态。 触发时机:业务事实已判定为 passed,但该 Gate 上存在一个非本轮自动轮询、 - 且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_inventory_source)。 + 且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_onhand_source)。 仅将 Attempt 置为 superseded、清空租约,并把 Gate 状态回退到 pending,让下方 常规 queue+complete 写入 passed;否则静默丢弃 passed,或被该 Attempt 的后续失败 - 覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。 + 覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / onhand_matching 曾因此永卡失败态)。 """ now = _utc_now() active_attempt.status = 'superseded' @@ -1090,8 +1090,8 @@ def _enqueue_auto_progress_after_gate_pass( """门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。 核心逻辑:刷新指针后对「当前未通过 Gate」入队唯一 Attempt/Job。典型场景: - 人工指定库存源使 ``inventory_source_routing`` passed 后,下一道仍是 - ``pending`` 且 ``next_action_code`` 为空的 ``inventory_preparation``——必须在此 + 人工指定库存源使 ``onhand_source_routing`` passed 后,下一道仍是 + ``pending`` 且 ``next_action_code`` 为空的 ``onhand_preparation``——必须在此 补种首投动作并入队,按已冻结源取数,禁止静默 return 导致永久「库存文件未准备」。 """ try: @@ -1154,8 +1154,8 @@ def _enqueue_auto_progress_after_gate_pass( # 初次进入库存准备也使用 retry_inventory_preparation 执行器;仅当还未创建 # 本 Execution 的库存 RPA Attempt 时自动投递一次。失败后的同一动作保留人工重试, # 不能由 AutoProgress 无限重放。 - if next_gate.next_action_code == 'retry_inventory_preparation': - from app.models import ShippingTaskInventoryRpaAttempt + if next_gate.next_action_code == 'retry_onhand_preparation': + from app.models import FreightRpaOnhandTaskAttempt from app.models import ShippingOrderTask task = db.session.get(ShippingOrderTask, int(execution.task_id)) @@ -1164,7 +1164,7 @@ def _enqueue_auto_progress_after_gate_pass( return task_no = str(getattr(task, 'task_no', '') or '').strip() existing = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter_by(task_no=task_no) .first() if task_no else None @@ -1173,7 +1173,7 @@ def _enqueue_auto_progress_after_gate_pass( return if ( ( - next_gate.next_action_code in {'retry_inventory_matching'} + next_gate.next_action_code in {'retry_onhand_matching'} and not _auto_match_enabled() ) or ( @@ -1312,8 +1312,8 @@ def sync_gate_from_business_result( 核心逻辑:无活动 Attempt 时自动 queue+complete;用于业务接线接入统一服务。 已通过门禁在 allow_repass 时先置 invalidated 再重评(输入变化重跑)。 - 已有活动 Attempt 时:仅 auto poll_inventory_preparation 可提前收口; - 其余(含库存就绪的 retry_inventory_preparation)留给外层 Attempt 统一 complete。 + 已有活动 Attempt 时:仅 auto poll_onhand_preparation 可提前收口; + 其余(含库存就绪的 retry_onhand_preparation)留给外层 Attempt 统一 complete。 Args: invalidate_change_type: 通过后失效类型;None 时库存源路由默认 inventory_source_changed。 @@ -1358,7 +1358,7 @@ def sync_gate_from_business_result( ) is_auto_poll = ( active_attempt.trigger_type == 'auto' - and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation' + and str(snapshot.get('action_code') or '').strip() == 'poll_onhand_preparation' ) if is_auto_poll and passed: return complete_gate_attempt( @@ -1378,7 +1378,7 @@ def sync_gate_from_business_result( is_conflicting_user_line_action = ( active_attempt.trigger_type in {'user_manual', 'user_retry'} and str(snapshot.get('action_code') or '').strip() in { - 'override_line_inventory_source', + 'override_line_onhand_source', } ) if is_conflicting_user_line_action and passed: @@ -1430,7 +1430,7 @@ def sync_gate_from_business_result( 'blocked_manual' if blocking_reason_code else 'blocked_retryable' ) resolved_invalidate = invalidate_change_type - if resolved_invalidate is None and passed and gate_code == 'inventory_source_routing': + if resolved_invalidate is None and passed and gate_code == 'onhand_source_routing': resolved_invalidate = 'inventory_source_changed' return complete_gate_attempt( attempt_id=int(attempt.id), @@ -1475,7 +1475,7 @@ def execute_stage_capability( 核心步骤: [STEP 1] 作废下游门禁:按 inventory_source_changed 失效链重算(容量声明 invalidate - 时才作废;如 reload_inventory_result 声明为空集合则跳过,直接重读)。 + 时才作废;如 reload_onhand_result 声明为空集合则跳过,直接重读)。 [STEP 2] 重置执行指针:若有 reset_to,把 execution 拉回能力定义的起始 gate。 [STEP 3] 幂等重跑:解析 notice task_no 后调用 run_task_auto_progress 推进;失败判定 以返回值(status=failed / status=conflict)或异常为准,二者均置 reran=False @@ -1522,7 +1522,7 @@ def execute_stage_capability( # 用户点击「重新获取库存」必须作为定向人工恢复进入库存准备 Gate; # 否则 AutoProgress 会把历史 RPA 失败当作自动重试而拒绝入队。 resume_gate_code=str(reset_to or '').strip() or None, - inventory_mode='retry_rpa' if reset_to == 'inventory_preparation' else 'auto', + inventory_mode='retry_rpa' if reset_to == 'onhand_preparation' else 'auto', line_scope_key=str(line_scope_key).strip() or None, ) # run_task_auto_progress 对失败返回 dict(status=failed / status=conflict),并非抛异常; @@ -1561,7 +1561,7 @@ def execute_stage_capability_rematch( 【AI 触发时机】:通知准备阶段用户点击「重新匹配库存」(即使 Gate 已推进到满足性/Excel 生成) 时由 request_gate_action 调用;与 execute_stage_capability 的「宽作废 + 重抓」不同,此处 保留已抓取库存与字段映射,只作废匹配及下游(inventory_field_mapping_changed),再经 - inventory_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel), + onhand_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel), 避免错误重抓 RPA 或重做字段映射。 Args: @@ -1584,27 +1584,27 @@ def execute_stage_capability_rematch( )) match_gate = ( ShippingProcessGate.query - .filter_by(execution_id=int(execution.id), gate_code='inventory_matching') + .filter_by(execution_id=int(execution.id), gate_code='onhand_matching') .first() ) if match_gate is None: db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', 'reran': False, 'reran_reason': 'inventory_matching_gate_missing', } attempt = queue_gate_attempt( execution_no=str(execution.execution_no), - gate_code='inventory_matching', + gate_code='onhand_matching', trigger_type='user_retry', actor_type=actor_type, actor_id=actor_id, idempotency_key=str(idempotency_key or ''), expected_gate_version=None, input_snapshot={ - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'payload': { 'actor_user_id': actor_id, 'idempotency_key': str(idempotency_key or ''), @@ -1619,7 +1619,7 @@ def execute_stage_capability_rematch( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', 'reran': False, 'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}', } @@ -1628,7 +1628,7 @@ def execute_stage_capability_rematch( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', 'reran': reran, 'gate_status': updated_gate.status, 'current_gate_code': execution.current_gate_code, @@ -1647,13 +1647,13 @@ def execute_stage_capability_override_source( """执行「行级库存源覆写」阶段能力:作废库存下游 → 重置回准备 → 按用户所选源冻结该行并重跑。 【AI 触发时机】:通知准备阶段用户在某行「选择库存源」下拉选定后点击勾勾(提交 - override_line_inventory_source)时由 request_gate_action 调用。 + override_line_onhand_source)时由 request_gate_action 调用。 关键差异 / root cause 说明: - - `override_line_inventory_source` 是「行级」动作,必须携带用户选定的 ``line_no`` / + - `override_line_onhand_source` 是「行级」动作,必须携带用户选定的 ``line_no`` / ``source_code``;而通用 ``execute_stage_capability`` 的签名不接收 payload,会把这两个 关键字段静默丢弃,导致「操作成功」弹窗后选源既不落库、也不触发 RPA、刷新回原样。 - - 本函数保留通用能力「作废下游 + 重置回 inventory_preparation + 幂等重跑」的语义, + - 本函数保留通用能力「作废下游 + 重置回 onhand_preparation + 幂等重跑」的语义, 但把选源通过 executor 的 ``_handle_override_line_inventory_source`` 真正冻结到 CandidateSet(freeze_manual_line_source_selection),再交由 run_task_auto_progress 按新候选重取/匹配库存,从而让 RPA 正常触发。 @@ -1678,10 +1678,10 @@ def execute_stage_capability_override_source( actor_type=actor_type, actor_id=actor_id, # 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。 - exclude_gate_codes={'inventory_preparation'} - {''}, + exclude_gate_codes={'onhand_preparation'} - {''}, )) - # 与 STAGE_CAPABILITY_DEFINITIONS['override_line_inventory_source'] 保持一致。 - execution.current_gate_code = 'inventory_preparation' + # 与 STAGE_CAPABILITY_DEFINITIONS['override_line_onhand_source'] 保持一致。 + execution.current_gate_code = 'onhand_preparation' prepared_payload = dict(payload or {}) prepared_payload.setdefault('idempotency_key', str(idempotency_key or '')) try: @@ -1694,7 +1694,7 @@ def execute_stage_capability_override_source( idempotency_key=str(idempotency_key or ''), expected_gate_version=None, input_snapshot={ - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'payload': prepared_payload, }, ) @@ -1704,7 +1704,7 @@ def execute_stage_capability_override_source( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', 'reran': False, 'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}', } @@ -1712,7 +1712,7 @@ def execute_stage_capability_override_source( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', 'reran': reran, 'gate_status': updated_gate.status, 'current_gate_code': execution.current_gate_code, diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 35a3e855..9bb468bd 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -42,10 +42,10 @@ _WRITE_ACTION_CODES = frozenset({ 'adjudicate_duplicate', 'reconcile_and_progress', 'open_profile_review', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', - 'upload_inventory_file', - 'retry_inventory_preparation', + 'upload_onhand_file', + 'retry_onhand_preparation', 'retry_parse', 'retry_failed_documents', 'regenerate_excel', @@ -58,9 +58,9 @@ _WRITE_ACTION_CODES = frozenset({ # 建单前禁止下发的履约写动作(匹配 / Excel / 上传等)。 _POST_CREATE_ONLY_ACTION_CODES = frozenset({ - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', - 'upload_inventory_file', + 'upload_onhand_file', 'regenerate_excel', 'download_excel', 'open_manual_upload', @@ -68,8 +68,8 @@ _POST_CREATE_ONLY_ACTION_CODES = frozenset({ _POST_CREATE_STAGES = frozenset({ 'order_creating', - 'inventory_fetching', - 'inventory_matching', + 'onhand_fetching', + 'onhand_matching', 'excel_generating', 'freight_uploading', 'completed', @@ -89,8 +89,8 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'mark_manual_uploaded': 'open_manual_upload', 'regenerate_manual_upload_todo': 'open_manual_upload', # [BE-05] Notice ui_state / Gate 业务动作收口到统一契约意图。 - 'rematch': 'open_inventory_match_review', - 'match_inventory': 'open_inventory_match_review', + 'rematch': 'open_onhand_match_review', + 'match_inventory': 'open_onhand_match_review', 'generate_excel': 'regenerate_excel', 'confirm_inventory_source': 'open_inventory_source_review', # 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由 @@ -196,8 +196,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: 核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传 → freight_uploading; - 导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching; - matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。 + 导出/Excel → excel_generating;waiting_inventory/parsed → onhand_fetching; + matching/inventory_ready/matched → onhand_matching;建单中 → order_creating。 领域映射唯一来源,禁止写状态机反向依赖投影私有函数。 Args: @@ -221,7 +221,7 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: export_path = '' projected_upload = None try: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match = str(aggregate_match_status_for_task(int(owner.id)) or '').strip().lower() if owner.id else '' from app.services.shipping_notice.upload_attempt_service import ( latest_export_artifact, @@ -270,20 +270,20 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: if ps == 'matched' and export_path: return ('automating', 'excel_generating') - if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching': - return ('automating', 'inventory_matching') + if ps in {'matching', 'inventory_ready', 'matched'} or step == 'onhand_matching': + return ('automating', 'onhand_matching') # 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。 - if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching': - return ('automating', 'inventory_fetching') + if ps in {'waiting_inventory', 'parsed'} or step == 'onhand_fetching': + return ('automating', 'onhand_fetching') if ps == 'pending_review': return ('waiting_review', 'waiting_review') if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating': return ('automating', 'order_creating') - if ps in {'fetching_inventory', 'inventory_fetching'}: - return ('automating', 'inventory_fetching') + if ps in {'fetching_inventory', 'onhand_fetching'}: + return ('automating', 'onhand_fetching') if ps in {'parsing', 'parsed_pending'}: return ('automating', 'order_creating') # [BE-03] 未知状态 fail-closed:禁止猜测为正常「创建订单中」。 @@ -560,11 +560,11 @@ def reconcile_processing_projection_facts( gate_stage = { # 正式 20-Gate 进入履约后,兼容 OT 字段可能尚未被旧写路径同步。 # 读投影必须以 Gate 统一覆盖,避免历史 waiting_review 重新污染批次中心。 - 'inventory_source_routing': 'inventory_source_resolving', - 'inventory_preparation': 'inventory_fetching', - 'inventory_field_mapping': 'inventory_fetching', - 'inventory_matching': 'inventory_matching', - 'inventory_sufficiency': 'inventory_matching', + 'onhand_source_routing': 'onhand_source_resolving', + 'onhand_preparation': 'onhand_fetching', + 'onhand_field_mapping': 'onhand_fetching', + 'onhand_matching': 'onhand_matching', + 'onhand_sufficiency': 'onhand_matching', 'excel_readiness': 'excel_generating', 'artifact_generation': 'excel_generating', 'freight_upload_rpa': 'freight_uploading', @@ -687,8 +687,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = { 'document_parsing': 'document_parsing', 'order_creating': 'order_creating', 'waiting_review': 'waiting_human_review', - 'inventory_fetching': 'inventory_fetch', - 'inventory_matching': 'inventory_match', + 'onhand_fetching': 'inventory_fetch', + 'onhand_matching': 'inventory_match', 'excel_generating': 'excel_generate', 'freight_uploading': 'freight_upload', 'completed': 'completed', @@ -851,9 +851,9 @@ def apply_user_projection_fields( if user_stage is None: if old_stage in {'document_parsing', 'order_creating'}: user_stage = 'document_parsing' - elif old_stage in {'inventory_fetching'}: + elif old_stage in {'onhand_fetching'}: user_stage = 'inventory_fetch' - elif old_stage in {'inventory_matching'}: + elif old_stage in {'onhand_matching'}: user_stage = 'inventory_match' elif old_stage in {'excel_generating'}: user_stage = 'excel_generate' @@ -980,9 +980,9 @@ def apply_user_projection_fields( # ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None ===== _ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = { - 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', - 'retry_inventory_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', - 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', + 'retry_onhand_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', + 'retry_onhand_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', + 'open_onhand_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', 'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review', 'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa', 'regenerate_excel': 'workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact', @@ -991,8 +991,8 @@ def apply_user_projection_fields( 'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review', } _ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = { - 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', - 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', + 'retry_onhand_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', + 'open_onhand_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', 'open_order_review': 'chat.shippingProcessing.action.open_order_review', 'retry_freight_upload_rpa': 'chat.shippingProcessing.action.retry_freight_upload_rpa', 'match_inventory': 'chat.shippingProcessing.action.match_inventory', @@ -1031,7 +1031,7 @@ def apply_user_projection_fields( # waiting_human 仅按 Gate/领域阻断映射精确业务入口。 if user_status == 'waiting_human': if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}: - code = 'open_inventory_match_review' + code = 'open_onhand_match_review' return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} if bcode in {'order_review_required', 'freeze_not_ready'}: code = 'open_order_review' @@ -1113,11 +1113,11 @@ def apply_user_projection_fields( # 仅依据正式 current_gate 的顺序和已投影事实派生,避免重新引入 APX 六 Gate。 gate_code = str((payload.get('current_gate') or {}).get('gate_code') or '').strip() gate_order = { - 'inventory_source_routing': 0, - 'inventory_preparation': 1, - 'inventory_field_mapping': 2, - 'inventory_matching': 3, - 'inventory_sufficiency': 4, + 'onhand_source_routing': 0, + 'onhand_preparation': 1, + 'onhand_field_mapping': 2, + 'onhand_matching': 3, + 'onhand_sufficiency': 4, 'excel_readiness': 5, 'artifact_generation': 6, 'manual_upload_handoff': 7, @@ -1138,7 +1138,7 @@ def apply_user_projection_fields( # 正式 OT 的库存事实只从 CandidateSet、Preparation/Link/File、LineMatch 与 Gate # 读取;step_payload_json 不再作为库存运行事实或恢复动作来源。 try: - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_facts, ) candidate_facts = project_inventory_candidate_facts(order_task) @@ -1163,8 +1163,8 @@ def apply_user_projection_fields( payload['projection_data_inconsistent'] = True # P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。 try: - from app.models import ShippingTaskInventoryRpaAttempt - attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all() + from app.models import FreightRpaOnhandTaskAttempt + attempts = FreightRpaOnhandTaskAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all() facts['rpa_attempts'] = [{ 'source_code': a.source_code, 'attempt_no': a.attempt_no, 'source_run_no': a.source_run_no, 'status': a.status, diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index c2c6a03b..bfda969f 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -41,7 +41,7 @@ WORKFLOW_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({ 'extracting', 'pending_review', 'building_order', - 'inventory_matching', + 'onhand_matching', 'generating_excel', 'manual_upload_pending', 'reparse_failed', @@ -242,11 +242,11 @@ SHIPPING_PROCESSING_STAGES: Final[tuple[str, ...]] = ( 'candidate_creating', 'customer_resolving', 'duplicate_checking', - 'inventory_source_resolving', + 'onhand_source_resolving', 'waiting_review', 'order_creating', - 'inventory_fetching', - 'inventory_matching', + 'onhand_fetching', + 'onhand_matching', 'excel_generating', 'freight_uploading', 'completed', @@ -283,11 +283,11 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = ( 'resolve_field_conflicts', 'adjudicate_duplicate', 'open_inventory_source_review', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', - 'upload_inventory_file', - 'retry_inventory_preparation', - 'retry_inventory_matching', + 'upload_onhand_file', + 'retry_onhand_preparation', + 'retry_onhand_matching', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', @@ -916,7 +916,7 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'path_id_hash', 'revision_no', # 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。 - 'inventory_source_id', + 'source_id', 'connector_type', 'config_version', 'report_path_json', @@ -987,11 +987,11 @@ I18N_KEY_INVENTORY: Final[tuple[str, ...]] = ( 'chat.shippingProcessing.stage.candidate_creating', 'chat.shippingProcessing.stage.customer_resolving', 'chat.shippingProcessing.stage.duplicate_checking', - 'chat.shippingProcessing.stage.inventory_source_resolving', + 'chat.shippingProcessing.stage.onhand_source_resolving', 'chat.shippingProcessing.stage.waiting_review', 'chat.shippingProcessing.stage.order_creating', - 'chat.shippingProcessing.stage.inventory_fetching', - 'chat.shippingProcessing.stage.inventory_matching', + 'chat.shippingProcessing.stage.onhand_fetching', + 'chat.shippingProcessing.stage.onhand_matching', 'chat.shippingProcessing.stage.excel_generating', 'chat.shippingProcessing.stage.freight_uploading', 'chat.shippingProcessing.stage.completed', @@ -1004,9 +1004,9 @@ I18N_KEY_INVENTORY: Final[tuple[str, ...]] = ( 'chat.shippingProcessing.action.none', 'chat.shippingProcessing.action.open_order_review', 'chat.shippingProcessing.action.edit_formal_task', - 'chat.shippingProcessing.action.open_inventory_match_review', + 'chat.shippingProcessing.action.open_onhand_match_review', 'chat.shippingProcessing.action.open_shortage_review', - 'chat.shippingProcessing.action.upload_inventory_file', + 'chat.shippingProcessing.action.upload_onhand_file', 'chat.shippingProcessing.action.retry', 'chat.shippingProcessing.action.refresh', 'chat.shippingProcessing.action.regenerate_excel', diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index c312255b..5aba8258 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -2,14 +2,14 @@ services/shipping_notice/progress_workflow.py 用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。 -依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 +依赖:customer_identity_gate、tool_common、query_service、onhand_workflow、fulfillment_workflow、 process_gate_contract.derive_user_mode、ui_state._process_gate_user_summary_for_task、 state_machine(双读回退)、tool_response、process_gate_bridge。 逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交 当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度; 早停粗分类优先 Gate derive_user_mode,无 Execution 时回退 resolve_task_ui_state; - inventory_preparation 的 retryable_tech 阻断不早停,交给 ensure_inventory(复用快照或 RPA)。 + onhand_preparation 的 retryable_tech 阻断不早停,交给 ensure_onhand(复用快照或 RPA)。 """ from __future__ import annotations @@ -29,11 +29,11 @@ from app.services.shipping_notice.constants import ( RS_PARSE_REVIEW, RS_RSV_REQ, ) -from app.services.shipping_notice.inventory_source_gate import ( +from app.services.shipping_notice.onhand_source_gate import ( is_inventory_source_stable, ensure_inventory_source_review_state, ) -from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory +from app.services.shipping_notice.onhand_workflow import ensure_inventory as _legacy_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 resolve_task_ui_state from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event @@ -46,8 +46,8 @@ def _entry_user_mode(task) -> str: 自动推进入口早停:从 Gate 推导用户处置模式。 无活动 Execution 时回退 resolve_task_ui_state.user_mode。 - inventory_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker - 继续走 ensure_inventory(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。 + onhand_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker + 继续走 ensure_onhand(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。 """ from app.services.shipping_notice.process_gate_contract import ( derive_user_mode, @@ -73,7 +73,7 @@ def _entry_user_mode(task) -> str: # blocked_retryable + inventory_file_empty;契约上属 retryable_tech,应由 # submit_auto_progress 入队 ensure_inventory,而不是入口 must_human 停机。 if ( - gate_code == 'inventory_preparation' + gate_code == 'onhand_preparation' and status == 'blocked_retryable' and user_mode_for_blocking_reason(reason_code) == 'retryable_tech' ): @@ -131,10 +131,10 @@ def _entry_position(task) -> str | None: # --------------------------------------------------------------------------- _RESUME_GATE_CODE_LEGACY_ENTRY = { - # inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现) - 'inventory_preparation': 'ensure_inventory', + # inventory_preparation → 调 onhand_workflow.ensure_inventory 逻辑(复用旧实现) + 'onhand_preparation': 'ensure_onhand', # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key=订单项次) - 'inventory_matching': 'match_inventory', + 'onhand_matching': 'match_inventory', # None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传) 'auto': 'auto_progress_full', None: 'auto_progress_full', @@ -223,18 +223,18 @@ def _dispatch_legacy_orchestration( 'resume_gate_code': resume_gate_code, 'mode': inventory_mode, } - if entry == 'ensure_inventory': + if entry == 'ensure_onhand': # [T4 集成] 库存准备:如果存在 per-source 候选冻结,优先走 per_source_rpa_service 逐源准备 from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, + from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) - frozen_sources = task_frozen_inventory_source_codes(task) + frozen_sources = task_frozen_onhand_source_codes(task) if frozen_sources and len(frozen_sources) >= 1: scoped_source_codes: list[str] | None = None scope_key = str(line_scope_key or '').strip() if scope_key: - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines try: scoped_line_id = int(scope_key) @@ -342,7 +342,7 @@ def run_task_auto_progress( """ 唯一 AutoProgress Orchestrator Facade。 【AI 触发时机】:所有需要推进发货任务状态的入口(Tool API、Batch Orchestrator、Retry Decision、 - Gate Handler post-action)均应调用本函数;禁止直接调 inventory_workflow.ensure_inventory + Gate Handler post-action)均应调用本函数;禁止直接调 onhand_workflow.ensure_onhand 或 fulfillment_workflow.match_inventory 绕过并发锁。 核心步骤: @@ -777,7 +777,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。 - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if not has_ready_inventory_file_for_task(task): 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"} diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index e1acd230..24bf903b 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -3,7 +3,7 @@ services/shipping_notice/query_service.py 用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 - ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、 + ShippingReservation、ShippingNoticeLine、ShippingNoticeLineOnhandMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、 ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、 order_review_projection(任务中心 STP retry 动作投影)。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; @@ -43,8 +43,8 @@ from app.models import ( FileAsset, ShippingExportArtifact, ShippingExportArtifactLine, - ShippingInventoryVerification, - ShippingInventoryFile, + ShippingOnhandVerification, + FreightRpaOnhandReportFile, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, @@ -64,9 +64,9 @@ from app.models import ( ShippingCustomerShadowResolution, ShippingProcessExecution, ShippingProcessGate, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ShippingNoticeLine, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingTaskEvent, ShippingUploadAttempt, ) @@ -125,9 +125,9 @@ _REVIEW_TODO_GATE_CODES = frozenset({ 'reservation_validation', }) _EXCEPTION_TODO_GATE_CODES = frozenset({ - 'inventory_sufficiency', + 'onhand_sufficiency', 'freight_upload_rpa', - 'inventory_source_routing', + 'onhand_source_routing', 'excel_readiness', }) _RUNNING_EXECUTION_STATUSES = frozenset({'active', 'waiting_external'}) @@ -281,8 +281,8 @@ class TaskProjection(str, Enum): def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" inventory_task_id = int(getattr(task, 'order_task_id', None) or task.id) - verifications = ShippingInventoryVerification.query.filter_by(task_id=inventory_task_id).order_by( - ShippingInventoryVerification.created_at, ShippingInventoryVerification.id, + verifications = ShippingOnhandVerification.query.filter_by(task_id=inventory_task_id).order_by( + ShippingOnhandVerification.created_at, ShippingOnhandVerification.id, ).all() artifacts = [] if isinstance(task, ShippingNotice): @@ -307,7 +307,7 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] ).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else [] return { 'inventory_verifications': [{ - 'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id, + 'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.onhand_snapshot_id, 'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None, 'lines': [{ 'reservation_id': reservation_ids.get(int(line.reservation_id), str(line.reservation_id)), 'required_qty': str(line.required_qty), @@ -486,7 +486,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: """Tool data 基础字段(裁剪前)。""" if isinstance(task, ShippingOrderTask): header, lines, _field_display = _order_values_for_projection(task) - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(task.id).values()) customer = _order_task_customer_projection(task) @@ -517,7 +517,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: 'conversation_id': task.conversation_id, 'step_payload': task.step_payload_json or {}, **inventory, - 'inventory_snapshot': _serialize_inventory_snapshot(task), + 'onhand_snapshot': _serialize_inventory_snapshot(task), } from app.services.shipping_notice.notice_upload import max_notice_chars from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode @@ -560,9 +560,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: } raw_content = str(getattr(workflow_owner, 'raw_content', None) or "").strip() lines = payload["lines"] - from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link + from app.services.shipping_notice.onhand_snapshot_store import serialize_inventory_snapshot_link - payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task) + payload["onhand_snapshot"] = serialize_inventory_snapshot_link(task) # Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。 if raw_content and not lines: limit = max_notice_chars() @@ -574,7 +574,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: def _current_match_projection(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: """从关联 OT 的行级 Match 生成通知准备读模型,禁止读取 Notice 聚合缓存。""" - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) rows = list(load_current_match_facts_by_task(task_id).values()) @@ -652,7 +652,7 @@ def _order_values_for_projection(task: ShippingOrderTask | ShippingNotice) -> tu def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None: """工作台任务摘要中的库存快照投影。""" - from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link + from app.services.shipping_notice.onhand_snapshot_store import serialize_inventory_snapshot_link return serialize_inventory_snapshot_link(task) @@ -675,7 +675,7 @@ def _order_task_customer_projection(task: ShippingOrderTask) -> dict[str, Any]: def _order_task_inventory_projection(task: ShippingOrderTask) -> dict[str, Any]: """从 CandidateSet 与行级 Match 读取 OT 库存路由投影,禁止读 OT 旧列。""" - from app.services.shipping_notice.inventory_candidate_projection import project_inventory_candidate_facts + from app.services.shipping_notice.onhand_candidate_projection import project_inventory_candidate_facts facts = project_inventory_candidate_facts(task) sources = list(facts.get('sources') or []) @@ -816,7 +816,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str for result in (task_disposition_capability(task, action),) } step_payload = task.step_payload_json or {} - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(task.id).values()) from app.services.shipping_notice.process_gate_projection import task_blocking_reason @@ -852,7 +852,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str 'destination_country': header.get('destination_country'), 'warehouse_hint': header.get('warehouse_hint'), **inventory, - 'inventory_snapshot': _serialize_inventory_snapshot(task), + 'onhand_snapshot': _serialize_inventory_snapshot(task), 'shortage': {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, 'line_results': match_facts, 'order_snapshot_id': getattr(workflow_owner, 'order_snapshot_id', None), @@ -864,13 +864,13 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str workflow_payload = getattr(workflow_owner, 'step_payload_json', None) or {} step_payload = workflow_payload header = current_header_field_values_or_empty(workflow_owner) - from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes inventory_facts = active_inventory_runtime_facts(workflow_owner) - source_codes = task_frozen_inventory_source_codes(workflow_owner) + source_codes = task_frozen_onhand_source_codes(workflow_owner) routing = (getattr(inventory_facts.get('candidate_set'), 'routing_rule_version_json', None) or {}) - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_task_id = getattr(workflow_owner, 'id', None) or task.id match_facts = list(load_current_match_facts_by_task(match_task_id).values()) match_status_projection = ( @@ -931,7 +931,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "inventory_source_method": routing.get('adjudication_method'), "inventory_source_config_version": inventory_facts.get('source_config_version'), "inventory_routing_fingerprint": routing.get('routing_fingerprint'), - "inventory_snapshot": _serialize_inventory_snapshot(workflow_owner), + "onhand_snapshot": _serialize_inventory_snapshot(workflow_owner), "shortage": {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, "line_results": match_facts, "created_at": task.created_at.isoformat() if task.created_at else None, @@ -1424,9 +1424,9 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: if snapshot is not None: matches_by_snapshot_line_id = { int(item.snapshot_line_id): item - for item in ShippingNoticeLineInventoryMatch.query.filter( - ShippingNoticeLineInventoryMatch.task_id == int(owner.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + for item in ShippingNoticeLineOnhandMatch.query.filter( + ShippingNoticeLineOnhandMatch.task_id == int(owner.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ).all() if item.snapshot_line_id is not None } @@ -1434,9 +1434,9 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: # 必须来自本 Notice 的 ShippingNoticeLine,避免不同通知波次串行。 matches_by_snapshot_line_id = { int(item.snapshot_line_id): item - for item in ShippingNoticeLineInventoryMatch.query.filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + for item in ShippingNoticeLineOnhandMatch.query.filter( + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ).all() if item.snapshot_line_id is not None } @@ -1453,7 +1453,7 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, 'shortage_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).shortage_qty if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, - 'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).inventory_status + 'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).onhand_status if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, } for item in rows] @@ -2175,15 +2175,15 @@ def _order_task_todo_category_sql_expr(): reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, "")) ready_file = exists( select(1) - .select_from(ShippingTaskInventoryLink) - .join(ShippingInventoryFile, ShippingInventoryFile.id == ShippingTaskInventoryLink.inventory_file_id) + .select_from(ShippingTaskOnhandLink) + .join(FreightRpaOnhandReportFile, FreightRpaOnhandReportFile.id == ShippingTaskOnhandLink.onhand_file_id) .where( - ShippingTaskInventoryLink.task_id == ShippingOrderTask.id, - ShippingTaskInventoryLink.is_active.is_(True), - ShippingTaskInventoryLink.invalidated_at.is_(None), - ShippingInventoryFile.snapshot_status == 'ready', - ShippingInventoryFile.invalidated_at.is_(None), - ShippingInventoryFile.line_count > 0, + ShippingTaskOnhandLink.task_id == ShippingOrderTask.id, + ShippingTaskOnhandLink.is_active.is_(True), + ShippingTaskOnhandLink.invalidated_at.is_(None), + FreightRpaOnhandReportFile.snapshot_status == 'ready', + FreightRpaOnhandReportFile.invalidated_at.is_(None), + FreightRpaOnhandReportFile.line_count > 0, ) ) incomplete_match = exists( @@ -2192,24 +2192,24 @@ def _order_task_todo_category_sql_expr(): .where( ShippingOrderSnapshotLine.snapshot_id == ShippingOrderTask.order_snapshot_id, ~exists( - select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, - ShippingNoticeLineInventoryMatch.snapshot_line_id == ShippingOrderSnapshotLine.id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result != 'preparing', + select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineOnhandMatch.snapshot_line_id == ShippingOrderSnapshotLine.id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.match_result != 'preparing', ) ), ) ) has_shortage = exists( - select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), + select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), db.or_( - ShippingNoticeLineInventoryMatch.match_result != 'matched', + ShippingNoticeLineOnhandMatch.match_result != 'matched', db.and_( - ShippingNoticeLineInventoryMatch.shortage_qty.isnot(None), - ShippingNoticeLineInventoryMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')), + ShippingNoticeLineOnhandMatch.shortage_qty.isnot(None), + ShippingNoticeLineOnhandMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')), ), ), ) @@ -2242,7 +2242,7 @@ def _order_task_todo_category_sql_expr(): ), literal("in_progress"), ), - (stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")), + (stage.in_(("onhand_source_resolving", "notification_preparation", "onhand_fetching", "onhand_matching", "order_creating")), literal("in_progress")), else_=literal("exception"), ) @@ -2623,10 +2623,10 @@ def _todo_category_sql_filter(allowed: frozenset[str]): clauses.append( db.or_( workflow_current_step.isnot(None), - exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None), )), artifact_exists, upload_pending, @@ -2705,9 +2705,9 @@ def _task_todo_category_sql_expr(): artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(("ready", "uploading", "uploaded")))) upload_success = _verified_upload_success_sql_expr() upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(("pending", "running", "failed", "unknown")))) - match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), + match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), )) return case( (upload_success, literal("done")), @@ -2847,7 +2847,7 @@ def _todo_tasks_base_query( workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) upload_success = _verified_upload_success_sql_expr() - match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) + match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True))) if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) if customer_needle: @@ -3259,7 +3259,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]: workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) upload_success = _verified_upload_success_sql_expr() - match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) + match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True))) pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count() pending += _visible_orphan_intakes_query(user_id, is_admin=is_admin).count() category_expr = _task_todo_category_sql_expr() diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 41cfa7b7..1dacfaa8 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -94,7 +94,7 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool: return False from app.services.shipping_notice.process_gate_projection import task_blocking_reason pending_reason = str(task_blocking_reason(task) or '').strip() - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task return ( pending_reason == PH_RPA_PENDING @@ -112,7 +112,7 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: task = get_task_by_ref(task_no) from app.services.shipping_notice.process_gate_projection import task_blocking_reason if task and str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING: - from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at + from app.services.shipping_notice.onhand_rpa_workflow import next_inventory_rpa_recheck_at scheduled_at = next_inventory_rpa_recheck_at(task) if scheduled_at is None: @@ -224,7 +224,7 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_ORDER_EXTRACTION, JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_PROCESS_GATE, - JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS, + JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS, JobType.SHIPPING_PDF_AUTOMARK, JobType.SHIPPING_STP_AUTO_CREATE, JobType.SHIPPING_LINE_AUTO_FULFILL, diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py index ce987717..6254837b 100644 --- a/backend/app/services/shipping_notice/recovery_invalidation_service.py +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -15,11 +15,11 @@ from sqlalchemy import false from app import db from app.models import ( ShippingExportArtifact, - ShippingInventoryVerification, - ShippingInventoryMapping, - ShippingNoticeLineInventoryMatch, + ShippingOnhandVerification, + FreightRpaOnhandMapping, + ShippingNoticeLineOnhandMatch, ShippingProcessExecution, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ShippingUploadAttempt, ShippingNotice, ) @@ -43,10 +43,10 @@ def _noticed_snapshot_line_ids(task_id: int) -> set[int]: return {int(row[0]) for row in rows if row[0] is not None} -def _match_row_source_codes(row: ShippingNoticeLineInventoryMatch) -> set[str]: +def _match_row_source_codes(row: ShippingNoticeLineOnhandMatch) -> set[str]: """从匹配事实抽取规范化库存源集合,供行级失效过滤。""" codes: set[str] = set() - primary = str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + primary = str(getattr(row, 'source_code', '') or '').strip().upper() if primary: codes.add(primary) for raw in list(getattr(row, 'allowed_source_codes_snapshot', None) or []): @@ -89,10 +89,10 @@ def invalidate_inventory_downstream( task = db.session.get(ShippingOrderTask, task_id) result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} change_type = { - 'retry_inventory_preparation': 'inventory_file_changed', - 'retry_inventory_from_preparation': 'inventory_file_changed', - 'retry_inventory_from_field_mapping': 'inventory_field_mapping_changed', - 'retry_inventory_from_matching': 'inventory_matching_changed', + 'retry_onhand_preparation': 'inventory_file_changed', + 'retry_onhand_from_preparation': 'inventory_file_changed', + 'retry_onhand_from_field_mapping': 'inventory_field_mapping_changed', + 'retry_onhand_from_matching': 'inventory_matching_changed', }.get(action_code, 'inventory_matching_changed') result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id) scoped_codes = { @@ -103,8 +103,8 @@ def invalidate_inventory_downstream( line_scoped = bool(scoped_codes) protected_line_ids = _noticed_snapshot_line_ids(task_id) if line_scoped else set() scoped_snapshot_line_id = int(snapshot_line_id) if snapshot_line_id is not None else None - if action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}: - links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() + if action_code in {'retry_onhand_preparation', 'retry_onhand_from_preparation'}: + links = ShippingTaskOnhandLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() for link in links: link_code = str(getattr(link, 'matched_source_code', '') or '').strip().upper() if line_scoped and link_code and link_code not in scoped_codes: @@ -118,26 +118,26 @@ def invalidate_inventory_downstream( link.invalidation_reason = action_code result['links'].append(int(link.id)) affected_file_ids = [ - int(link.inventory_file_id) - for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all() - if link.inventory_file_id and ( + int(link.onhand_file_id) + for link in ShippingTaskOnhandLink.query.filter_by(task_id=task_id).all() + if link.onhand_file_id and ( not line_scoped or str(getattr(link, 'matched_source_code', '') or '').strip().upper() in scoped_codes ) ] if action_code in { - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', + 'retry_onhand_preparation', + 'retry_onhand_from_preparation', + 'retry_onhand_from_field_mapping', } and affected_file_ids: - mappings = ShippingInventoryMapping.query.filter( - ShippingInventoryMapping.inventory_file_id.in_(affected_file_ids), - ShippingInventoryMapping.status == 'active', + mappings = FreightRpaOnhandMapping.query.filter( + FreightRpaOnhandMapping.onhand_file_id.in_(affected_file_ids), + FreightRpaOnhandMapping.status == 'active', ).with_for_update().all() for mapping in mappings: mapping.status = 'invalidated' result['mappings'].append(int(mapping.id)) - matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() + matches = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() for row in matches: row_line_id = int(getattr(row, 'snapshot_line_id', 0) or 0) if line_scoped and row_line_id in protected_line_ids: @@ -154,7 +154,7 @@ def invalidate_inventory_downstream( row.invalidation_reason = action_code result['matches'].append(int(row.id)) if not line_scoped: - verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() + verifications = ShippingOnhandVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() for verification in verifications: verification.status = 'superseded' result['verifications'].append(int(verification.id)) diff --git a/backend/app/services/shipping_notice/recovery_plan_contract.py b/backend/app/services/shipping_notice/recovery_plan_contract.py index 4f549e5f..cf3e623e 100644 --- a/backend/app/services/shipping_notice/recovery_plan_contract.py +++ b/backend/app/services/shipping_notice/recovery_plan_contract.py @@ -12,50 +12,50 @@ from typing import Any RECOVERY_PLAN_ACTIONS: dict[str, dict[str, dict[str, Any]]] = { - 'inventory_matching': { - 'retry_inventory_from_preparation': { - 'target_gate': 'inventory_preparation', - 'resume_after_gate': 'inventory_matching', - 'allowed_intermediate_gates': ('inventory_field_mapping',), + 'onhand_matching': { + 'retry_onhand_from_preparation': { + 'target_gate': 'onhand_preparation', + 'resume_after_gate': 'onhand_matching', + 'allowed_intermediate_gates': ('onhand_field_mapping',), 'invalidate_change_type': 'inventory_file_changed', - 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, - 'retry_inventory_from_field_mapping': { - 'target_gate': 'inventory_field_mapping', - 'resume_after_gate': 'inventory_matching', + 'retry_onhand_from_field_mapping': { + 'target_gate': 'onhand_field_mapping', + 'resume_after_gate': 'onhand_matching', 'allowed_intermediate_gates': (), 'invalidate_change_type': 'inventory_field_mapping_changed', - 'invalidates': ('inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, }, # 库存有缺口时仍由 Gate 16 负责恢复入口;数量事实只读,恢复动作回到正式库存链路。 - 'inventory_sufficiency': { + 'onhand_sufficiency': { # 公开动作:用户明确选择“重新获取库存”时回到准备 Gate,强制创建新的 RPA # Attempt;不能要求客户端传递内部的 retry_inventory_from_preparation。 - 'retry_inventory_preparation': { - 'target_gate': 'inventory_preparation', - 'resume_after_gate': 'inventory_sufficiency', - 'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'), + 'retry_onhand_preparation': { + 'target_gate': 'onhand_preparation', + 'resume_after_gate': 'onhand_sufficiency', + 'allowed_intermediate_gates': ('onhand_field_mapping', 'onhand_matching'), 'invalidate_change_type': 'inventory_file_changed', - 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, - 'retry_inventory_from_preparation': { - 'target_gate': 'inventory_preparation', - 'resume_after_gate': 'inventory_sufficiency', - 'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'), + 'retry_onhand_from_preparation': { + 'target_gate': 'onhand_preparation', + 'resume_after_gate': 'onhand_sufficiency', + 'allowed_intermediate_gates': ('onhand_field_mapping', 'onhand_matching'), 'invalidate_change_type': 'inventory_file_changed', - 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, - 'retry_inventory_from_matching': { - 'target_gate': 'inventory_matching', - 'resume_after_gate': 'inventory_sufficiency', + 'retry_onhand_from_matching': { + 'target_gate': 'onhand_matching', + 'resume_after_gate': 'onhand_sufficiency', 'allowed_intermediate_gates': (), 'invalidate_change_type': 'inventory_matching_changed', - 'invalidates': ('inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, }, diff --git a/backend/app/services/shipping_notice/recovery_plan_service.py b/backend/app/services/shipping_notice/recovery_plan_service.py index cda86b68..90fafb1e 100644 --- a/backend/app/services/shipping_notice/recovery_plan_service.py +++ b/backend/app/services/shipping_notice/recovery_plan_service.py @@ -107,8 +107,8 @@ def complete_recovery_plan_for_attempt( resolved_outcome = str(outcome) rematch_reached_shortage_review = ( resolved_outcome == 'blocked_manual' - and str(plan.action_code or '') == 'retry_inventory_from_matching' - and str(plan.resume_after_gate or '') == 'inventory_sufficiency' + and str(plan.action_code or '') == 'retry_onhand_from_matching' + and str(plan.resume_after_gate or '') == 'onhand_sufficiency' and str(business_result_code or '') == 'inventory_shortage_review_required' ) excel_regeneration_reached_manual_upload = ( diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index a54ce91a..da3610e4 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -103,7 +103,7 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No from app.models import ShippingOrderTask owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task review_status = _clean_text(getattr(owner, "review_status", None)).lower() - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) match_status = _clean_text(aggregate_match_status_for_task(match_task_id)).lower() pending_reason = _clean_text(getattr(owner, "pending_human_reason", None)).lower() diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 00aa364a..75e5253c 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -3,7 +3,7 @@ services/shipping_notice/reservation_id.py 用途:提取、标准化并校验发货通知与库存中的 Reservation ID。 依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。 -逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用; +逻辑:由 notice_lines、onhand_snapshot、match、extract、EML 补充解析等多个模块复用; 归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。 另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为 5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并 diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 658de766..eda02bf1 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -17,8 +17,8 @@ from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, - ShippingInventoryVerification, - ShippingInventoryVerificationLine, + ShippingOnhandVerification, + ShippingOnhandVerificationLine, ShippingOrderSnapshot, ShippingOrderTask, ShippingReservation, @@ -190,12 +190,12 @@ def _transfer_confirmed_revision( def record_inventory_verification( task: ShippingNotice, *, inventory_snapshot_id: int | None, source_config_version: str | None, line_results: list[dict[str, Any]], -) -> ShippingInventoryVerification: +) -> ShippingOnhandVerification: """把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。""" reservations = ensure_task_reservations(task) by_key = {row.reservation_id: row for row in reservations} - verification = ShippingInventoryVerification( - task_id=task.id, inventory_snapshot_id=inventory_snapshot_id, + verification = ShippingOnhandVerification( + task_id=task.id, onhand_snapshot_id=inventory_snapshot_id, source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)}, ) db.session.add(verification) @@ -218,7 +218,7 @@ def record_inventory_verification( seen_reservation_ids.add(reservation_id) available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0') status = 'available' if available >= required else 'shortage' - db.session.add(ShippingInventoryVerificationLine( + db.session.add(ShippingOnhandVerificationLine( verification_id=verification.id, reservation_id=reservation.id, required_qty=required, available_qty=available, status=status, detail_json={'line_status': item.get('line_status')}, )) @@ -236,7 +236,7 @@ def reserve_available_for_artifact( task: ShippingNotice, *, artifact: ShippingExportArtifact, - verification: ShippingInventoryVerification, + verification: ShippingOnhandVerification, released_snapshot_line_ids: set[int] | None = None, selected_snapshot_line_ids: set[int] | None = None, ) -> list[ShippingReservation]: @@ -244,7 +244,7 @@ def reserve_available_for_artifact( 锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。 核心逻辑:默认只消费 ``available`` Reservation;调用方仅可传入从活动 - ``release_inventory_shortage`` 决定解析出的冻结行 ID,使该行的 shortage + ``release_onhand_shortage`` 决定解析出的冻结行 ID,使该行的 shortage Verification 作为放行审计的一部分绑定到 Artifact,其他 shortage 不得被捎带导出。 Args: @@ -311,7 +311,7 @@ def current_available_snapshot_line_ids( released_snapshot_line_ids: set[int] | None = None, selected_snapshot_line_ids: set[int] | None = None, closed_snapshot_line_ids: set[int] | None = None, -) -> tuple[ShippingInventoryVerification, set[int]]: +) -> tuple[ShippingOnhandVerification, set[int]]: """ 取得最新核验中可导出的冻结订单行。 @@ -328,8 +328,8 @@ def current_available_snapshot_line_ids( (最新核验轮次, 本次可导出的冻结订单行 ID)。 """ verification = ( - ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') - .order_by(ShippingInventoryVerification.id.desc()).first() + ShippingOnhandVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') + .order_by(ShippingOnhandVerification.id.desc()).first() ) if verification is None: raise ConflictError('No inventory verification is available', code='SHIPPING.ROLLING_EXPORT_NOT_READY') diff --git a/backend/app/services/shipping_notice/routing_operators.py b/backend/app/services/shipping_notice/routing_operators.py index 374ca01d..01b4117c 100644 --- a/backend/app/services/shipping_notice/routing_operators.py +++ b/backend/app/services/shipping_notice/routing_operators.py @@ -2,7 +2,7 @@ services/shipping_notice/routing_operators.py 用途:执行库存源路由规则允许的比较操作。 -依赖:无业务服务依赖;由 inventory_routing_engine 调用。 +依赖:无业务服务依赖;由 onhand_routing_engine 调用。 逻辑:操作符白名单限制规则表达能力,避免管理员配置任意代码、SQL 或正则执行。 """ diff --git a/backend/app/services/shipping_notice/rpa_sinks.py b/backend/app/services/shipping_notice/rpa_sinks.py index 9fd7cf4a..fc0fba2b 100644 --- a/backend/app/services/shipping_notice/rpa_sinks.py +++ b/backend/app/services/shipping_notice/rpa_sinks.py @@ -2,15 +2,22 @@ services/shipping_notice/rpa_sinks.py 用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把 - /api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器。 -依赖:freight_rpa.common.callback_sinks(register_sink)、inventory_rpa_workflow(快照落盘/ - 批量 ingest)、per_source_rpa_service(Attempt 认领)、inventory_configuration_test(配置测试)、 - receipt_report_storage(inbound 归档入口 + 业务桥留守)、schedule.freight_inbound_rpa_finalize + /api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器,并把文件/报表 + 事实 kind 接到 reports.dispatch 的处理函数(阶段 B Task 7)。 +依赖:freight_rpa.common.callback_sinks(register_sink——进度类回调注册表)、 + freight_rpa.reports.dispatch(register_report_handler——文件/报表事实处理函数注册表)、 + onhand_rpa_workflow(快照落盘/批量 ingest)、per_source_rpa_service(Attempt 认领)、 + onhand_configuration_test(配置测试)、inbound_report_storage(inbound 归档入口 + + 业务桥留守)、in_transit_transfer.inbound_report_handler / onhand_report_handler + (Task 7 的两个文件事实处理函数)、schedule.freight_rpa_inbound_finalize (inbound 进度/领取处理器,Task 11 已随排程壳平移改名)。 逻辑:由组合根(app.create_app)调用 register_onhand_sinks() / register_inbound_sinks() 完成 - 注册(幂等,重复注册覆盖)。各 sink 仅做两件事:① 复刻旧 shipping-notice rpa 回调端点 - 端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入旧路由 - 等价的 payload['repair']=True。业务事务边界完全由被包装的域内函数保持,本层不碰 db。 + 注册(幂等,重复注册覆盖)。进度类 sink 仅做两件事:① 复刻旧 shipping-notice rpa + 回调端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入 + 旧路由等价的 payload['repair']=True。文件事实处理函数经 register_report_handler 注册 + (Task 7:inbound→handle_inbound_report、onhand→handle_onhand_report)——归档入口 + 终态 commit 后经 dispatch_report_fact 投递 ReportFact 调入;业务事务边界完全由被 + 包装的域内函数保持,本层只做接线,不碰 db。 """ from __future__ import annotations @@ -47,57 +54,74 @@ def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) def _onhand_repair_sink(**payload: Any) -> dict[str, Any]: """受控库存回调修复:等价旧 /rpa/inventory-repair——payload['repair']=True 后走 batch-ready ingest。""" - from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory_batch payload['repair'] = True return rpa_report_inventory_batch(payload) def register_onhand_sinks() -> None: - """组合根入口:注册全部 onhand 回调 sink(幂等;create_app 每次启动调用)。 + """组合根入口:注册全部 onhand 回调 sink 与 onhand 事实处理函数(幂等;create_app 每次启动调用)。 - 核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀;被包装函数全部住在 + 核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀,被包装函数全部住在 shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch) - 与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线。 + 与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线; + 文件事实处理函数走 reports.dispatch(Task 7):'onhand' kind 经 + register_report_handler 注册 handle_onhand_report(在手文件归档终态 commit 后由 + dispatch_report_fact 调入),进度类 sink 仍走 register_sink、envelope 不变。 """ from app.services.freight_rpa.common.callback_sinks import register_sink - from app.services.shipping_notice import inventory_configuration_test, inventory_rpa_workflow + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice import onhand_configuration_test, onhand_rpa_workflow + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch - register_sink('onhand-ready', _bare(inventory_rpa_workflow.rpa_report_inventory)) - register_sink('onhand-batch-ready', _bare(inventory_rpa_workflow.rpa_report_inventory_batch)) + register_sink('onhand-ready', _bare(onhand_rpa_workflow.rpa_report_inventory)) + register_sink('onhand-batch-ready', _bare(onhand_rpa_workflow.rpa_report_inventory_batch)) register_sink('onhand-batch-claimed', _success_data_envelope(claim_inventory_batch)) - register_sink('onhand-batch-progress', _bare(inventory_rpa_workflow.report_inventory_batch_progress)) + register_sink('onhand-batch-progress', _bare(onhand_rpa_workflow.report_inventory_batch_progress)) register_sink( 'onhand-configuration-test-start', - _ok_data_envelope(inventory_configuration_test.report_batch_test_progress), + _ok_data_envelope(onhand_configuration_test.report_batch_test_progress), ) register_sink( 'onhand-configuration-test-analyze', - _ok_data_envelope(inventory_configuration_test.report_test_export), + _ok_data_envelope(onhand_configuration_test.report_test_export), ) register_sink( 'onhand-configuration-test-complete', - _ok_data_envelope(inventory_configuration_test.report_batch_test_exports), + _ok_data_envelope(onhand_configuration_test.report_batch_test_exports), ) register_sink('onhand-repair', _onhand_repair_sink) + # [STEP Task 7] 文件事实处理函数注册:onhand 归档终态 commit 后经 + # dispatch_report_fact 投递 ReportFact(report_kind='onhand')到本处理函数。 + register_report_handler('onhand', handle_onhand_report) def register_inbound_sinks() -> None: - """组合根入口:注册全部 inbound(收料)回调 sink(幂等;create_app 每次启动调用)。 + """组合根入口:注册全部 inbound(收料)回调 sink 与 inbound 事实处理函数(幂等;create_app 每次启动调用)。 - 核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的 - 业务处理器 = receipt_report_storage.ingest_receipt_callback(归档能力下沉 - freight_rpa.inbound.report_archive 后的域内入口,内部把「终态推进在途调拨来源任务 - + 调拨证据同步 + 排程终态归集」业务桥作为 on_terminal 钩子注入——业务桥留守 - shipping_notice,与拆分前调用方向一致);unit/batch-progress 处理器仍住排程壳 - (Task 11 已平移改名为 schedule.freight_inbound_rpa_finalize),按「处理函数住在哪个包」 - 由本层接注册表。三个 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。 + 核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的 + 业务处理器 = inbound_report_storage.ingest_receipt_callback(归档能力下沉 + freight_rpa.inbound.report_archive 后的域内入口;批次 B Task 6 起归档入口不再收 + on_terminal 钩子——终态 commit 后由 report_archive 直接投递 ReportFact); + unit/batch-progress 处理器仍住排程壳 + (Task 11 已平移改名为 schedule.freight_rpa_inbound_finalize),按「处理函数住在哪个包」 + 由本层接注册表。三个进度类 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。 + 文件事实处理函数走 reports.dispatch(Task 7):'inbound' kind 经 register_report_handler + 注册 in_transit_transfer.handle_inbound_report(调拨推进/证据同步/排程收口均由该 + 处理函数承担,freight_rpa 不 import 桥与 finalize),进度类 sink 仍走 register_sink、 + envelope 不变。 """ from app.services.freight_rpa.common.callback_sinks import register_sink - from app.services.schedule import freight_inbound_rpa_finalize - from app.services.shipping_notice import receipt_report_storage + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + from app.services.schedule import freight_rpa_inbound_finalize + from app.services.shipping_notice import inbound_report_storage - register_sink('inbound-batch-ready', _success_data_envelope(receipt_report_storage.ingest_receipt_callback)) - register_sink('inbound-unit-progress', _success_data_envelope(freight_inbound_rpa_finalize.mark_receipt_unit_processing)) - register_sink('inbound-batch-progress', _success_data_envelope(freight_inbound_rpa_finalize.report_receipt_batch_progress)) + register_sink('inbound-batch-ready', _success_data_envelope(inbound_report_storage.ingest_receipt_callback)) + register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_receipt_unit_processing)) + register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_receipt_batch_progress)) + # [STEP Task 7] 文件事实处理函数注册:inbound 归档各终态 commit 后经 + # dispatch_report_fact 投递 ReportFact(report_kind='inbound')到调拨侧处理函数。 + register_report_handler('inbound', handle_inbound_report) diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index d03bdb00..78f1529e 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -120,7 +120,7 @@ def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: owner = task if isinstance(task, ShippingNotice) and task.order_task_id: owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or '' upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip() diff --git a/backend/app/services/shipping_notice/shipping_notice_creation_service.py b/backend/app/services/shipping_notice/shipping_notice_creation_service.py index 2f2c76f3..55ed4598 100644 --- a/backend/app/services/shipping_notice/shipping_notice_creation_service.py +++ b/backend/app/services/shipping_notice/shipping_notice_creation_service.py @@ -88,8 +88,8 @@ def create_shipping_notice_after_inventory_gate( # 正式 Notice 只能建立在当前库存匹配事实完整通过之后;库存准备失败或仍有未处理行时, # OT 必须停留在通知准备阶段,不得产生 Notice/NoticeLine。 - from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink - fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by( + from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch, ShippingTaskOnhandLink + fact_rows = ShippingNoticeLineOnhandMatch.query.filter_by( task_id=int(order_task.id), is_current=True, ).all() by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None} @@ -106,7 +106,7 @@ def create_shipping_notice_after_inventory_gate( or ( not ( str(by_line[int(line_id)].match_result or '').strip().lower() == 'matched' - and str(by_line[int(line_id)].inventory_status or '').strip().lower() == 'ready' + and str(by_line[int(line_id)].onhand_status or '').strip().lower() == 'ready' ) and int(line_id) not in released_ids ) @@ -114,29 +114,29 @@ def create_shipping_notice_after_inventory_gate( ): raise ConflictError( "Inventory matching must pass before creating a shipping notice", - code="SHIPPING.INVENTORY_GATE_NOT_PASSED", + code="SHIPPING.ONHAND_GATE_NOT_PASSED", ) inventory_facts_by_snapshot_line_id: dict[int, dict[str, object]] = {} for snapshot_line_id in target_ids: match = by_line[int(snapshot_line_id)] inventory_file = ( - db.session.get(ShippingInventoryFile, int(match.inventory_snapshot_id)) - if match.inventory_snapshot_id is not None + db.session.get(FreightRpaOnhandReportFile, int(match.onhand_snapshot_id)) + if match.onhand_snapshot_id is not None else None ) link = ( - ShippingTaskInventoryLink.query.filter_by( + ShippingTaskOnhandLink.query.filter_by( task_id=int(order_task.id), - inventory_file_id=int(inventory_file.id), - matched_source_code=match.inventory_source_code, + onhand_file_id=int(inventory_file.id), + matched_source_code=match.source_code, is_active=True, - ).order_by(ShippingTaskInventoryLink.id.desc()).first() + ).order_by(ShippingTaskOnhandLink.id.desc()).first() if inventory_file is not None else None ) inventory_facts_by_snapshot_line_id[int(snapshot_line_id)] = { - 'inventory_source_code': match.inventory_source_code, + 'inventory_source_code': match.source_code, 'inventory_file_id': int(inventory_file.id) if inventory_file is not None else None, 'inventory_warehouse_id': ( str(getattr(link, 'matched_warehouse_id', '') or '').strip().upper() diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 22c99824..062b3380 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -489,9 +489,9 @@ _ACTIVITY_TO_PROCESSING_STAGE: dict[str, str] = { 'review_required': 'waiting_review', 'waiting_review': 'waiting_review', 'order_creating': 'order_creating', - 'inventory_source_resolving': 'inventory_source_resolving', - 'inventory_fetching': 'inventory_fetching', - 'inventory_matching': 'inventory_matching', + 'onhand_source_resolving': 'onhand_source_resolving', + 'onhand_fetching': 'onhand_fetching', + 'onhand_matching': 'onhand_matching', 'excel_generating': 'excel_generating', 'freight_uploading': 'freight_uploading', 'completed': 'completed', @@ -2092,14 +2092,14 @@ def _project_order_task_work_item( inventory_preparation = None if notice is not None: try: - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt preparation_task_id = getattr(order_task, 'id', None) if order_task is not None else getattr(notice, 'order_task_id', None) preparation = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(preparation_task_id)) - .filter(ShippingInventoryPreparationAttempt.status != 'superseded') - .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .filter(ShippingOnhandPreparationAttempt.status != 'superseded') + .order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()) .first() ) source_attempts = list(getattr(preparation, 'source_attempts', []) or []) if preparation else [] @@ -2113,7 +2113,7 @@ def _project_order_task_work_item( 'attempt_no': int(preparation.attempt_no), 'status': row.status, 'rpa_attempt_id': row.rpa_attempt_id, - 'inventory_file_id': row.inventory_file_id, + 'inventory_file_id': row.onhand_file_id, } for row in source_attempts } @@ -2137,7 +2137,7 @@ def _project_order_task_work_item( # PreparationAttempt 读取发生在首次用户态归一化之后;立即重新应用 # fail-closed 规则,防止异常分支保留旧 primary_action/available_actions。 payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task) - payload['inventory_preparation'] = inventory_preparation + payload['onhand_preparation'] = inventory_preparation # pre_ot_stp 是内部责任阶段,不是会话时间线展示枚举;最终输出统一为正式建单节点。 if str(payload.get('user_stage') or '').strip().lower() == 'pre_ot_stp': @@ -3330,8 +3330,8 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) - # 空 Candidate Case 的同一入口用于解析处置;不得借动作码跳到订单复核。 return 'order_review' if lifecycle_stage == 'order_review' else 'intake_parse' if code in { - 'open_inventory_match_review', 'match_inventory', 'rematch', 'open_shortage_review', - 'upload_inventory_file', 'retry_inventory_preparation', 'regenerate_excel', 'generate_excel', + 'open_onhand_match_review', 'match_inventory', 'rematch', 'open_shortage_review', + 'upload_onhand_file', 'retry_onhand_preparation', 'regenerate_excel', 'generate_excel', }: return 'fulfillment_prep' if code in { diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py index d12e0582..c1835b6c 100644 --- a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -14,7 +14,7 @@ import logging from flask import current_app from app import db -from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt +from app.models import ShippingOrderTask, FreightRpaOnhandTaskAttempt _LOGGER = logging.getLogger(__name__) @@ -67,8 +67,8 @@ def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int: """ task_nos = [ str(row[0]) - for row in db.session.query(ShippingTaskInventoryRpaAttempt.task_no) - .filter(ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running'))) + for row in db.session.query(FreightRpaOnhandTaskAttempt.task_no) + .filter(FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running'))) .distinct() .all() ] diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index ea85d0dc..76302cee 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -364,7 +364,7 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N 将命名业务事实迁移写入 ShippingNotice 的领域结果字段与 review/pending 事实。 核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。 - 库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。 + 库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → onhand_fetching 等)。 Args: task: 待更新的 ShippingNotice 实例(尚未 commit)。 diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_onhand_match.py similarity index 94% rename from backend/app/services/shipping_notice/stp_line_inventory_match.py rename to backend/app/services/shipping_notice/stp_line_onhand_match.py index a246421e..18b08f1d 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_onhand_match.py @@ -1,10 +1,10 @@ """ -services/shipping_notice/stp_line_inventory_match.py +services/shipping_notice/stp_line_onhand_match.py 用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。 -依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、 - inventory_source_rules、ShippingOrderSnapshot。 -逻辑:ensure_inventory 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制 +依赖:stp_onhand_freeze、reservation_id、onhand_snapshot_store、onhand_source_repository、 + onhand_source_rules、ShippingOrderSnapshot。 +逻辑:ensure_onhand 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制 __source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 @@ -18,21 +18,21 @@ from typing import Any from app import db from app.models import ShippingOrderSnapshot, ShippingNotice -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( compute_routing_fingerprint, extract_routing_context, ) from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id from app.services.shipping_notice.reservation_id import validated_reservation_id -from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes +from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes def _norm_part(value: Any) -> str: @@ -142,7 +142,7 @@ def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> st return validated_reservation_id(header_values.get('reservation_id')) -def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: +def prepare_candidate_onhand_lines(task: ShippingNotice) -> dict[str, Any]: """ 为任务准备全部冻结候选源的有效库存行(打上 __source_code 标签)。 @@ -156,8 +156,8 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: Returns: status / lines / missing_source_codes / loaded_source_codes / evidence。 """ - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines - from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot current_set = get_active_candidate_set(task) if current_set is None: @@ -174,7 +174,7 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: } candidate_lines = get_active_candidate_lines(task) - task_level_codes = list(task_frozen_inventory_source_codes(task)) + task_level_codes = list(task_frozen_onhand_source_codes(task)) required_codes: list[str] = [] for line in candidate_lines: for raw in list(getattr(line, 'source_codes_json', None) or []): @@ -225,21 +225,21 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: evidence.append({ 'source_code': code, 'status': 'snapshot_empty', - 'inventory_file_no': snapshot.inventory_file_no, + 'inventory_file_no': snapshot.onhand_file_no, 'required': in_required, }) continue for row in lines: tagged = dict(row) tagged['__source_code'] = code - tagged['__inventory_file_no'] = snapshot.inventory_file_no + tagged['__inventory_file_no'] = snapshot.onhand_file_no merged.append(tagged) loaded.append(code) evidence.append({ 'source_code': code, 'status': 'loaded', 'candidate_set_id': int(current_set.id), - 'inventory_file_no': snapshot.inventory_file_no, + 'inventory_file_no': snapshot.onhand_file_no, 'line_count': len(lines), 'required': in_required, }) @@ -540,7 +540,7 @@ def match_order_lines_across_candidates( } -def apply_line_inventory_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None: +def apply_line_onhand_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None: """ 将跨候选匹配结果交给行级 Match 持久化;不再把库存匹配事实写入 OT.step_payload_json。 """ @@ -556,10 +556,10 @@ def multi_source_recovery_source_codes(task: ShippingNotice) -> list[str]: candidate_hit_source_codes;若冲突行缺失该候选(如历史事实未记录),回退为全部可用 库存源(list_database_inventory_sources)兜底,保证用户在候选缺失时仍能指定库存源。 """ - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_source_repository import ( list_database_inventory_sources, ) - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( load_current_match_facts_by_task, ) codes: list[str] = [] @@ -603,7 +603,7 @@ def apply_forced_match_source_filter( 过滤后的库存行;无强制源时原样返回。 """ if task.__class__.__name__ == 'ShippingOrderTask': - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines selected = set() for row in get_active_candidate_lines(task): selected.update(str(code or '').strip().upper() for code in (getattr(row, 'source_codes_json', None) or []) if str(code or '').strip()) diff --git a/backend/app/services/shipping_notice/stp_inventory_freeze.py b/backend/app/services/shipping_notice/stp_onhand_freeze.py similarity index 91% rename from backend/app/services/shipping_notice/stp_inventory_freeze.py rename to backend/app/services/shipping_notice/stp_onhand_freeze.py index 5458af24..dd6855ce 100644 --- a/backend/app/services/shipping_notice/stp_inventory_freeze.py +++ b/backend/app/services/shipping_notice/stp_onhand_freeze.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/stp_inventory_freeze.py +services/shipping_notice/stp_onhand_freeze.py 用途:建单时将资格服务的行级库存源候选冻结到 CandidateSet,供后续库存准备消费。 -依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。 +依赖:onhand_source_gate、onhand_source_repository、onhand_source_rules、tool_common。 逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved; 多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review); 冻结结果写入 ShippingTaskEvent(candidates_frozen / inventory_source_resolved_at_build)。 @@ -13,18 +13,18 @@ from __future__ import annotations from typing import Any from app.models import ShippingNotice -from app.services.shipping_notice.inventory_candidate_freeze_service import ( +from app.services.shipping_notice.onhand_candidate_freeze_service import ( freeze_candidates_for_task, ) -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_sources, ) -from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, _candidate, compute_routing_fingerprint, @@ -56,7 +56,7 @@ def collect_frozen_candidate_codes(line_projections: list[dict[str, Any]] | None return codes -def freeze_stp_inventory_candidates_on_task( +def freeze_stp_onhand_candidates_on_task( task: ShippingNotice, *, line_projections: list[dict[str, Any]] | None, @@ -183,7 +183,7 @@ def freeze_stp_inventory_candidates_on_task( return adjudication -def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]: +def task_frozen_onhand_source_codes(task: ShippingNotice) -> list[str]: """ 读取任务上冻结的候选库存源(单源任务则回退 inventory_source_code)。 diff --git a/backend/app/services/shipping_notice/stp_progress_contract.py b/backend/app/services/shipping_notice/stp_progress_contract.py index 669c5204..da7b7fec 100644 --- a/backend/app/services/shipping_notice/stp_progress_contract.py +++ b/backend/app/services/shipping_notice/stp_progress_contract.py @@ -103,7 +103,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: ).strip().lower() direct_match_status = getattr(task, 'match_status', None) if direct_match_status is None and task.__class__.__name__ == 'ShippingOrderTask': - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(getattr(task, 'id', None)).values()) match_status = 'matched' if match_facts and all( @@ -112,7 +112,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: for row in match_facts ) else ('shortage' if match_facts else '') elif direct_match_status is None: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_status = str(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) or '').strip().lower() else: match_status = str(direct_match_status or '').strip().lower() @@ -128,7 +128,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: artifact = latest_export_artifact(task) has_export = bool(str(getattr(artifact, 'file_name', '') or '').strip()) projected_upload = project_notice_upload_status(task) - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task progress_state = ( 'uploaded' if projected_upload == 'uploaded' else 'upload_failed' if projected_upload == 'failed' else diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index be308e4c..91359f89 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -93,7 +93,7 @@ def _target_is_safe(task: ShippingNotice) -> bool: if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ: return False - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_for_task, has_ready_inventory_file_for_task, ) diff --git a/backend/app/services/shipping_notice/task_disposition_service.py b/backend/app/services/shipping_notice/task_disposition_service.py index 7157ad02..4e49fe5f 100644 --- a/backend/app/services/shipping_notice/task_disposition_service.py +++ b/backend/app/services/shipping_notice/task_disposition_service.py @@ -25,9 +25,9 @@ from app.models import ( ShippingCustomerShadowResolution, ShippingNotice, ShippingTaskEvent, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ShippingTaskPurgeAudit, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ) from app.models.shipping_task_line import ShippingTaskFieldConflict @@ -307,8 +307,8 @@ def move_task_to_recycle_bin( ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() ) or getattr(owner_task, 'candidate_id', None) - or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first()) - or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first() + or bool(db.session.query(ShippingNoticeLineOnhandMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first()) + or db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(owner_task.id)).first() or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first() or ( isinstance(task, ShippingNotice) @@ -442,11 +442,11 @@ def purge_task_permanently( if isinstance(task, ShippingOrderTask): blocking_counts = { 'current_order_extraction': int(bool(task.current_order_extraction_id)), - 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'onhand_snapshot': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(), 'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(), 'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(), - 'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'inventory_link': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(), } blocking = {key: value for key, value in blocking_counts.items() if value} @@ -465,7 +465,7 @@ def purge_task_permanently( )) return - from app.models import ShippingTemporaryInventorySession + from app.models import ShippingTemporaryOnhandSession # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 owner = task if hasattr(task, 'current_order_extraction_id') else None @@ -481,19 +481,19 @@ def purge_task_permanently( 'source_intake': int(bool(task.source_intake_id)), 'source_candidate': int(bool(task.source_candidate_id)), 'current_order_extraction': int(bool(task.current_order_extraction_id)), - 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'onhand_snapshot': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'successor': int(_has_successor(task)), 'duplicate_link': int(bool(task.duplicate_source_task_id)), 'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter( ShippingNotice.duplicate_source_task_id == int(task.id), ).count(), 'external_upload_fact': int(_has_external_fulfillment(task)), - 'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'inventory_link': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'export_artifact': db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).count(), 'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(), 'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(), 'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(), - 'temporary_inventory_session': db.session.query(ShippingTemporaryInventorySession.id).filter_by(task_id=int(task.id)).count(), + 'temporary_inventory_session': db.session.query(ShippingTemporaryOnhandSession.id).filter_by(task_id=int(task.id)).count(), 'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(), 'non_disposition_event': db.session.query(ShippingTaskEvent.id).filter( ShippingTaskEvent.task_id == int(task.id), diff --git a/backend/app/services/shipping_notice/task_field_gate.py b/backend/app/services/shipping_notice/task_field_gate.py index 7e14be0b..a1f59044 100644 --- a/backend/app/services/shipping_notice/task_field_gate.py +++ b/backend/app/services/shipping_notice/task_field_gate.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/task_field_gate.py 用途:未解决订单字段冲突门禁,阻断库存/匹配/导出下游副作用。 依赖:task_field_conflict_service、i18n、tool_response、query_service.serialize_task_for_tool。 -逻辑:inventory_workflow / inventory_rpa_workflow / fulfillment_workflow 在副作用前调用。 +逻辑:onhand_workflow / onhand_rpa_workflow / fulfillment_workflow 在副作用前调用。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 063f2a77..2f642678 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -45,7 +45,7 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.user_facing_status import user_facing_task_stage -from app.services.shipping_notice.inventory_workflow import ensure_inventory +from app.services.shipping_notice.onhand_workflow import ensure_inventory from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, assert_no_exact_duplicate_notices, @@ -65,7 +65,7 @@ from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool: """读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。""" - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task return has_ready_inventory_file_for_task(task) @@ -352,8 +352,8 @@ def _apply_notice_edit_change_effects( 按 Schema change_effect 选择性失效下游;无 legacy 全量 reset。 核心逻辑: - rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT inventory_source_resolving; - rerun_inventory_matching → 清匹配/导出、OT inventory_matching; + rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT onhand_source_resolving; + rerun_inventory_matching → 清匹配/导出、OT onhand_matching; regenerate_excel → 仅清导出、OT excel_generating; require_revision → 全量下游 reset; none → 跳过重型 reset(Excel 冻结由 assert_formal_task_not_excel_frozen 拦截)。 @@ -368,7 +368,7 @@ def _apply_notice_edit_change_effects( """ from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields from app.services.shipping_notice.order_task_service import sync_order_task_processing_state - from app.services.shipping_notice.inventory_source_gate import ( + from app.services.shipping_notice.onhand_source_gate import ( adjudicate_and_apply_inventory_source, clear_inventory_source_confirmation, ) @@ -394,23 +394,23 @@ def _apply_notice_edit_change_effects( if 'rerun_inventory_source_resolution' in effects: clear_inventory_source_confirmation(task) _reset_notice_export_downstream(task) - _set_notice_invalidated_from_stage(task, 'inventory_source_resolving') + _set_notice_invalidated_from_stage(task, 'onhand_source_resolving') adjudication = adjudicate_and_apply_inventory_source(task) - from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable + from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable stable = is_inventory_source_stable(task) if order_task is not None: if stable: sync_order_task_processing_state( order_task, - stage='inventory_fetching', + stage='onhand_fetching', status='processing', ) _clear_notice_invalidated_from_stage(task) else: sync_order_task_processing_state( order_task, - stage='inventory_source_resolving', + stage='onhand_source_resolving', status='blocked', ) applied.add('rerun_inventory_source_resolution') @@ -418,11 +418,11 @@ def _apply_notice_edit_change_effects( if 'rerun_inventory_matching' in effects: _reset_notice_export_downstream(task) - _set_notice_invalidated_from_stage(task, 'inventory_matching') + _set_notice_invalidated_from_stage(task, 'onhand_matching') if order_task is not None: sync_order_task_processing_state( order_task, - stage='inventory_matching', + stage='onhand_matching', status='processing', ) applied.add('rerun_inventory_matching') @@ -881,7 +881,7 @@ def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) -> """ if order_task is None: return None - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task facts = list(load_current_match_facts_by_task(order_task.id).values()) if not facts: diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index 2e462d20..edab89c3 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -3,8 +3,8 @@ services/shipping_notice/tool_common.py 用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。 依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。 -逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用; - log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/ +逻辑:task_workflow / onhand_workflow / fulfillment_workflow / decision_workflow 共用; + log_task_event 对 onhand_rpa_/inventory_source_/export_/notice_replace/ freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent; 另提供 generic/XFA/LLM 等主链灰度开关读取。 """ @@ -76,9 +76,9 @@ def auto_progress_enabled() -> bool: return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False) -def auto_rpa_inventory_enabled() -> bool: - """是否允许自动触发 RPA 导出库存。""" - return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True) +def auto_rpa_onhand_enabled() -> bool: + """是否允许自动触发 RPA 导出在手库存(SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED)。""" + return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED", True) def rpa_inventory_timeout_seconds() -> int: @@ -236,7 +236,7 @@ def set_task_step_progress( stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。 Args: - stage: 15 阶契约码(如 inventory_fetching / inventory_matching / + stage: 15 阶契约码(如 onhand_fetching / onhand_matching / excel_generating / freight_uploading);禁止传入 CheckPoint 时代 stepN_* 遗留键(已全部清除)。 step_title: 展示用步骤名。 @@ -404,7 +404,7 @@ def log_task_event( event_name = str(event_type or '') dual_write = event_name.startswith(( - 'inventory_rpa_', + 'onhand_rpa_', 'inventory_source_', 'export_', 'notice_replace', @@ -512,11 +512,11 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) - name = str(event_type or '').strip() err_blob = f"{detail.get('error') or ''} {detail.get('error_code') or ''}".lower() mapping = { - 'inventory_rpa_queued': 'inventory_rpa_queued', - 'inventory_rpa_started': 'inventory_rpa_queued', - 'inventory_rpa_timeout': 'inventory_rpa_timeout', - 'inventory_rpa_exhausted': 'inventory_rpa_exhausted', - 'inventory_rpa_failed': 'inventory_rpa_export_failed', + 'onhand_rpa_queued': 'onhand_rpa_queued', + 'onhand_rpa_started': 'onhand_rpa_queued', + 'onhand_rpa_timeout': 'onhand_rpa_timeout', + 'onhand_rpa_exhausted': 'onhand_rpa_exhausted', + 'onhand_rpa_failed': 'onhand_rpa_export_failed', 'notice_replaced': 'attachment_replaced', 'notice_replace_extract_failed': 'document_text_unavailable', 'freight_cancellation_completed': 'task_voided_for_correction', @@ -528,14 +528,14 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) - } if name in mapping: code = mapping[name] - if name == 'inventory_rpa_failed': + if name == 'onhand_rpa_failed': if 'timeout' in err_blob or ('not ready' in err_blob and 'within' in err_blob): - return 'inventory_rpa_timeout' + return 'onhand_rpa_timeout' if 'login' in err_blob or 'auth' in err_blob: - return 'inventory_rpa_login_failed' + return 'onhand_rpa_login_failed' if 'export' in err_blob: - return 'inventory_rpa_export_failed' - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' + return 'onhand_rpa_export_failed' if name == 'notice_replace_extract_failed': from app.services.shipping_notice.error_explainability_contract import ( primary_attachment_reason_from_warnings, @@ -545,8 +545,8 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) - ) return from_warnings or code return code - if name.startswith('inventory_rpa_') and name.endswith('_failed'): - return 'inventory_rpa_export_failed' + if name.startswith('onhand_rpa_') and name.endswith('_failed'): + return 'onhand_rpa_export_failed' if name.startswith('upload_rpa') and 'fail' in name: return 'upload_rpa_failed' return None diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index b7b8b700..695da145 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -3,7 +3,7 @@ services/shipping_notice/tool_response.py 用途:统一构建发货通知 Tool 的 JSON 响应结构。 依赖:state_machine.resolve_task_ui_state(位置派生);ShippingProcessExecution。 -逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应; +逻辑:由 task_workflow、onhand_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应; 已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。 """ diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 6e38cc90..b70bca39 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -2,7 +2,7 @@ services/shipping_notice/tools.py 用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。 -依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow。 +依赖:customer_identity_gate、task_workflow、onhand_workflow、onhand_rpa_workflow、fulfillment_workflow。 逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。 """ @@ -10,8 +10,8 @@ from __future__ import annotations from app.services.shipping_notice import ( fulfillment_workflow, - inventory_rpa_workflow, - inventory_workflow, + onhand_rpa_workflow, + onhand_workflow, task_workflow, ) from app.services.shipping_notice import customer_identity_gate @@ -29,37 +29,37 @@ remove_notice_line = task_workflow.remove_notice_line confirm_customer = customer_identity_gate.confirm_customer # 库存阶段 -ensure_inventory = inventory_workflow.ensure_inventory -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 +ensure_inventory = onhand_workflow.ensure_inventory +upload_inventory_file = onhand_workflow.upload_inventory_file +rpa_report_inventory = onhand_rpa_workflow.rpa_report_inventory +rpa_report_inventory_batch = onhand_rpa_workflow.rpa_report_inventory_batch +repair_task_inventory_attachment = onhand_rpa_workflow.repair_task_inventory_attachment def create_temporary_inventory_session(payload: dict): """创建对话上传库存候选会话;仅供 Dify 临时库存固定分支调用。""" - from app.services.shipping_notice.inventory_temporary_session import create_temporary_inventory_session as _create + from app.services.shipping_notice.onhand_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 + from app.services.shipping_notice.onhand_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 + from app.services.shipping_notice.onhand_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 + from app.services.shipping_notice.onhand_temporary_session import confirm_temporary_inventory_use as _confirm return _confirm(payload) diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 76d4bceb..d7b5d9f0 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -4,9 +4,9 @@ services/shipping_notice/ui_state.py 用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、 query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、 - process_gate_projection、line_inventory_match_projection、inventory_candidate_projection、 + process_gate_projection、line_onhand_match_projection、onhand_candidate_projection、 order_review_fulfillment_decision_service(短缺放行模板字段)、 - order_review_workbench_projection、inventory_source_repository(preparation.source_options)。 + order_review_workbench_projection、onhand_source_repository(preparation.source_options)。 逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode); Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id); 五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列), @@ -56,7 +56,7 @@ from app.services.shipping_notice.constants import ( RS_PARSE_REVIEW, RS_SHORTAGE_REVIEW, ) -from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable +from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable from app.services.shipping_notice.lifecycle_projection import ( LIFECYCLE_STAGES, project_lifecycle, @@ -90,7 +90,7 @@ _REVIEW_ENTRY_POSITIONS = { } _NEXT_AUTO_STEP_BY_POSITION: dict[str, str] = { - POSITION_INVENTORY_PENDING: "ensure_inventory", + POSITION_INVENTORY_PENDING: "ensure_onhand", POSITION_ORDER_FREEZE: "freeze_order", POSITION_READY_MATCH: "match_inventory", POSITION_READY_EXPORT: "generate_excel", @@ -407,12 +407,12 @@ def _derived_entry_surface( if user_mode in {'must_human', 'wait_manual_upload'}: return 'task_workbench' if code in { - 'inventory_preparation', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', - 'inventory_source_routing', + 'onhand_source_routing', 'order_freeze_readiness', }: return 'task_workbench' @@ -467,11 +467,11 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: """ from app import db from app.models import ShippingOrderTask - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_facts, ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import multi_source_recovery_source_codes from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS owner = task @@ -488,7 +488,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: ) status = 'candidates_frozen' if candidate_projection.get('current_set') else '' method = 'candidate_set' if candidate_projection.get('current_set') else '' - frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(owner) + frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_onhand_source_codes(owner) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') @@ -503,7 +503,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: compact_resolutions: list[dict[str, Any]] = [] resolution_source = list(candidate_projection.get('line_resolutions') or []) if not resolution_source and getattr(owner, 'id', None) is not None: - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch resolution_source = [{ 'line_index': row.line_index, @@ -511,7 +511,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'disposition': row.match_result, 'effective_reservation_id': row.reservation_id, 'part_number': row.part_number, - 'resolved_inventory_source_code': row.inventory_source_code, + 'resolved_inventory_source_code': row.source_code, 'inventory_file_no': row.matched_file_no, 'inventory_row_index': row.matched_row_index, 'match_attempt_id': row.match_attempt_id, @@ -519,9 +519,9 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'matched_qty': row.matched_qty or row.available_qty, 'shortage_qty': row.shortage_qty, 'inventory_row_ref': dict(row.detail_json or {}).get('inventory_row_ref'), - } for row in ShippingNoticeLineInventoryMatch.query.filter_by( + } for row in ShippingNoticeLineOnhandMatch.query.filter_by( task_id=int(owner.id), is_current=True, - ).order_by(ShippingNoticeLineInventoryMatch.line_no, ShippingNoticeLineInventoryMatch.id).all()] + ).order_by(ShippingNoticeLineOnhandMatch.line_no, ShippingNoticeLineOnhandMatch.id).all()] for item in resolution_source: disposition = str(item.get('disposition') or 'unknown') counts[disposition] = counts.get(disposition, 0) + 1 @@ -778,19 +778,19 @@ def _stage_capabilities_for_task( } if source_locked: cap.update(disabled('excel_locked')) - elif code == 'retry_inventory_preparation': + elif code == 'retry_onhand_preparation': # 重抓:候选源或失败源任一在场即可重试(库存文件未准备时通常走候选源)。 retry_available = has_candidates or bool(failed_codes) cap['enabled'] = retry_available cap['disabled_reason'] = None if retry_available else 'no_candidates' - elif code == 'override_line_inventory_source': + elif code == 'override_line_onhand_source': cap['enabled'] = has_candidates cap['disabled_reason'] = None if has_candidates else 'no_candidates' - elif code == 'reload_inventory_result': + elif code == 'reload_onhand_result': has_prior = bool(resolved_codes) cap['enabled'] = has_prior cap['disabled_reason'] = None if has_prior else 'no_prior_result' - elif code == 'retry_inventory_matching': + elif code == 'retry_onhand_matching': cap['enabled'] = has_match_result cap['disabled_reason'] = None if has_match_result else 'no_match_result' result.append(cap) @@ -814,15 +814,15 @@ def _build_stage_context( preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉; preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染); Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询; - inventory_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。 + onhand_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。 """ from app import db from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask from app.models.shipping_excel_template import ShippingExportArtifact from app.models.shipping_fulfillment import ShippingUploadAttempt from app.core.errors import ConflictError - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.line_onhand_match_projection import ( inventory_rpa_is_running, load_current_match_facts_by_task, project_line_inventory_view, @@ -1014,27 +1014,27 @@ def _build_stage_context( inventory_sources: list[dict[str, Any]] = [] latest_preparation = None if getattr(order_task, 'id', None): - from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt + from app.models.shipping_onhand_preparation import ShippingOnhandPreparationAttempt latest_preparation = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(order_task.id)) - .filter(ShippingInventoryPreparationAttempt.status != 'superseded') - .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .filter(ShippingOnhandPreparationAttempt.status != 'superseded') + .order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()) .first() ) - from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download + from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download downloadable_inventory = resolve_task_inventory_download(order_task) for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []): inventory_sources.append({ 'source_code': source_attempt.source_code, 'status': source_attempt.status, - 'inventory_file_id': source_attempt.inventory_file_id, + 'inventory_file_id': source_attempt.onhand_file_id, }) # [STEP] 人工覆写库存源:下发全部已启用源,供前端行级下拉(override_line_inventory_source)。 - from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources + from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources source_options = [ { @@ -1352,7 +1352,7 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] 核心逻辑:先把 Notice 解析到 order_task_id 对应的 OT,再优先读 active_process_execution_id,回退按 OT.id 取最新非 superseded Execution; - 套用 apply_post_ot_gate_rules,使 inventory_preparation 等系统等待 + 套用 apply_post_ot_gate_rules,使 onhand_preparation 等系统等待 不进入 current_blocking_gate。货代上传聚合的 available_actions 依赖此路径。 同一 HTTP 请求内按 task 主键 memo,避免 build_task_ui_state / resolve 等路径重复查库。 diff --git a/backend/app/services/shipping_notice/workflow_ledger_service.py b/backend/app/services/shipping_notice/workflow_ledger_service.py index 03f87138..d40d8b6e 100644 --- a/backend/app/services/shipping_notice/workflow_ledger_service.py +++ b/backend/app/services/shipping_notice/workflow_ledger_service.py @@ -336,7 +336,7 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool: Returns: True 表示已进入 matched 或更后阶段。 """ - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) match_status = aggregate_match_status_for_task(match_task_id) or '' from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/freight_rpa_sources.yaml similarity index 99% rename from backend/config/shipping_inventory_sources.yaml rename to backend/config/freight_rpa_sources.yaml index f8f961c0..749bf183 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/freight_rpa_sources.yaml @@ -1,4 +1,4 @@ -# backend/config/shipping_inventory_sources.yaml +# backend/config/freight_rpa_sources.yaml # 历史库存源配置:仅用于期初数据导入和人工核对,不能恢复为运行时真相源。 # 新增或修改库存源、报表路径、查询参数和别名必须维护在数据库后台。 # 本文件保留 site_id、selector 等旧字段,导入时需显式映射或丢弃;新运行时不得读取。 diff --git a/backend/migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py b/backend/migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py new file mode 100644 index 00000000..73159c52 --- /dev/null +++ b/backend/migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py @@ -0,0 +1,564 @@ +""" +migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py + +用途:批次 S 只改表结构——29 张货代 RPA / 发货库存表一次 rename,并改写这些表上的 + inventory/receipt 列名,以及名称里含旧表名的索引、主键、唯一、检查、外键。 + 模型类与 __tablename__ 仍用旧名,留到后续任务。 +依赖:alembic.op、SQLAlchemy 反射;down_revision 为当前单 head tt16c7d8e9f0a1b2。 +逻辑:先按列规则改列,再 rename_table(PG/SQLite 都会改外键指向的表),最后扫全库 + 对象名,把旧表名替换成新表名。验证批次索引 + ix_inventory_test_run_validation_batch 一对一改成 + ix_fr_onhand_cfg_test_runs_validation_batch_id。历史迁移没有单列 + recipient 索引,升级在新表上补建 ix_fr_inbound_notif_deliveries_recipient_user_id, + 降级删掉,不还原一个不存在的旧名。复合索引 + ix_shipping_receipt_delivery_file_recipient 不含完整旧表名,不改。 + PostgreSQL 用 ALTER ... RENAME;SQLite 对索引是重建,对表内约束是 batch 重建。 + downgrade 按相反顺序还原。不改 29 张以外的表(含 shipping_notice_freight_cancellations)上的列。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = "s17b1c2d3e4f5a" +down_revision = "tt16c7d8e9f0a1b2" +branch_labels = None +depends_on = None + +# PostgreSQL 标识符上限(NAMEDATALEN-1)。ASCII 名称按字符计即按字节计。 +_MAX_IDENTIFIER_LENGTH = 63 + +# (旧表, 新表)。顺序与批次 S 任务书一致。 +_TABLE_RENAMES: list[tuple[str, str]] = [ + ("shipping_inventory_sources", "freight_rpa_sources"), + ("shipping_rpa_profiles", "freight_rpa_profiles"), + ("shipping_inventory_fields", "freight_rpa_onhand_fields"), + ("shipping_inventory_source_parsing_binding_audits", "freight_rpa_onhand_source_parsing_binding_audits"), + ("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles"), + ("shipping_inventory_structure_analyses", "freight_rpa_onhand_structure_analyses"), + ("shipping_inventory_configuration_test_runs", "freight_rpa_onhand_configuration_test_runs"), + ("shipping_inventory_validation_batches", "freight_rpa_onhand_validation_batches"), + ("shipping_inventory_routing_rules", "freight_rpa_onhand_routing_rules"), + ("shipping_inventory_routing_rule_conditions", "freight_rpa_onhand_routing_rule_conditions"), + ("shipping_inventory_routing_rule_versions", "freight_rpa_onhand_routing_rule_versions"), + ("shipping_inventory_external_mappings", "freight_rpa_onhand_external_mappings"), + ("shipping_inventory_mappings", "freight_rpa_onhand_mappings"), + ("shipping_task_inventory_rpa_attempts", "freight_rpa_onhand_task_rpa_attempts"), + ("shipping_receipt_report_configs", "freight_rpa_inbound_report_configs"), + ("shipping_receipt_rpa_unit_runs", "freight_rpa_inbound_rpa_unit_runs"), + ("shipping_receipt_report_files", "freight_rpa_inbound_report_files"), + ("shipping_receipt_notification_deliveries", "freight_rpa_inbound_notification_deliveries"), + ("shipping_inventory_files", "shipping_onhand_files"), + ("shipping_inventory_candidate_sets", "shipping_onhand_candidate_sets"), + ("shipping_inventory_candidate_sources", "shipping_onhand_candidate_sources"), + ("shipping_inventory_candidate_lines", "shipping_onhand_candidate_lines"), + ("shipping_inventory_preparation_attempts", "shipping_onhand_preparation_attempts"), + ("shipping_inventory_preparation_source_attempts", "shipping_onhand_preparation_source_attempts"), + ("shipping_task_inventory_links", "shipping_task_onhand_links"), + ("shipping_temporary_inventory_sessions", "shipping_temporary_onhand_sessions"), + ("shipping_notice_line_inventory_matches", "shipping_notice_line_onhand_matches"), + ("shipping_notice_inventory_verifications", "shipping_notice_onhand_verifications"), + ("shipping_notice_inventory_verification_lines", "shipping_notice_onhand_verification_lines"), +] + +# 显式列对照优先于「名字里的 inventory 换成 onhand」。 +_EXPLICIT_COLUMNS = { + "inventory_source_id": "source_id", + "inventory_snapshot_id": "onhand_snapshot_id", + "inventory_file_id": "onhand_file_id", + "inventory_source_code": "source_code", + "active_inventory_candidate_set_id": "active_onhand_candidate_set_id", +} + +_RECEIPT_TABLES = frozenset({ + "shipping_receipt_report_configs", + "shipping_receipt_rpa_unit_runs", + "shipping_receipt_report_files", + "shipping_receipt_notification_deliveries", +}) + +# 替换后超过 63 字节、降级必须回到原名的对象。其余名称不截断。 +_EXACT_ORIGINS = ( + "shipping_receipt_notification_deliveries_recipient_user_id_fkey", +) + +# 只映射历史迁移真正建过的索引。aa1 的验证批次索引一对一换成模型短名。 +# 不收录 SQLAlchemy index=True 的自动名:库里没有那条 65 字节索引。 +_EXPLICIT_INDEX_NAMES = { + "ix_inventory_test_run_validation_batch": "ix_fr_onhand_cfg_test_runs_validation_batch_id", +} + +# hi3 只建了复合索引 ix_shipping_receipt_delivery_file_recipient,没有单列 recipient 索引。 +# 升级在已改名的表上补建模型短名;降级删除,不假装有旧名可还原。 +_CREATED_RECIPIENT_INDEX = "ix_fr_inbound_notif_deliveries_recipient_user_id" +_CREATED_RECIPIENT_TABLE = "freight_rpa_inbound_notification_deliveries" +_CREATED_RECIPIENT_COLUMNS = ["recipient_user_id"] + + +def _quote_ident(name: str) -> str: + """给 SQL 标识符加双引号,内部引号按标准加倍。 + + Args: + name: 表、索引或约束名。 + + Returns: + 可拼进 DDL 的引用标识符。 + """ + return '"' + name.replace('"', '""') + '"' + + +def _substitute(name: str, pairs: list[tuple[str, str]]) -> str: + """把对象名中的表名 token 换成对照表里的另一个名字。 + + 核心逻辑:按源 token 长度降序替换,避免短表名吃掉更长表名的前缀。 + 调用方保证这 29 个旧名彼此不是子串,新名同理。 + + Args: + name: 当前索引或约束名。 + pairs: (被替换的表名, 替换后的表名)。升级用旧→新,降级用新→旧。 + + Returns: + 替换后的对象名(尚未按 63 字节截断)。 + """ + updated = name + for source, destination in sorted(pairs, key=lambda item: len(item[0]), reverse=True): + updated = updated.replace(source, destination) + return updated + + +def _clip(name: str) -> str: + """把标识符限制在 PostgreSQL 的 63 字节以内。 + + Args: + name: 已完成表名替换的对象名。 + + Returns: + 长度不超过 63 的名字。未超长时原样返回。 + """ + if len(name) <= _MAX_IDENTIFIER_LENGTH: + return name + return name[:_MAX_IDENTIFIER_LENGTH] + + +def _target_name(current: str, pairs: list[tuple[str, str]], *, reverse: bool) -> str: + """计算对象改名的目标。 + + 核心逻辑:_EXPLICIT_INDEX_NAMES 一对一改名,降级回到唯一的旧名。 + 其余正向是表名替换再截断。反向时,若当前名正是某个已知超长原名的截断结果, + 则回到那个原名,避免降级丢掉被切掉的后缀。 + + Args: + current: 库里现在的对象名。 + pairs: 本方向的表名替换对。 + reverse: True 表示 downgrade。 + + Returns: + 应改成的对象名。与 current 相同表示不用改。 + """ + if reverse: + for origin, short in _EXPLICIT_INDEX_NAMES.items(): + if current == short: + return origin + for origin in _EXACT_ORIGINS: + if _clip(_substitute(origin, _TABLE_RENAMES)) == current: + return origin + elif current in _EXPLICIT_INDEX_NAMES: + return _EXPLICIT_INDEX_NAMES[current] + return _clip(_substitute(current, pairs)) + + +def _forward_column_name(table: str, column: str) -> str: + """按批次 S 列规则计算升级后的列名。 + + 核心逻辑:五条显式对照优先;其余列名中的 inventory 换成 onhand; + 仅四张原 shipping_receipt_* 表再把 receipt 换成 inbound。 + + Args: + table: 仍是旧表名的表。 + column: 当前列名。 + + Returns: + 新列名。无需改名时与 column 相同。 + """ + renamed = _EXPLICIT_COLUMNS.get(column) + if renamed is None: + renamed = column.replace("inventory", "onhand") if "inventory" in column else column + if table in _RECEIPT_TABLES and "receipt" in renamed: + renamed = renamed.replace("receipt", "inbound") + return renamed + + +def _reverse_column_name(table: str, column: str) -> str: + """按升级规则的逆运算还原列名。 + + 核心逻辑:先在四张 receipt 表上把 inbound 换回 receipt,再还原显式对照。 + source_code 只有 shipping_notice_line_inventory_matches 来自 inventory_source_code; + 其他表上本来就有的 source_code 必须留下。其余 onhand 换回 inventory。 + + Args: + table: 已经改回旧表名的表。 + column: 升级后的列名。 + + Returns: + 升级前的列名。 + """ + name = column + if table in _RECEIPT_TABLES and "inbound" in name: + name = name.replace("inbound", "receipt") + if name == "source_id": + return "inventory_source_id" + if name == "source_code" and table == "shipping_notice_line_inventory_matches": + return "inventory_source_code" + if "onhand" in name: + return name.replace("onhand", "inventory") + return name + + +def _rename_columns(table: str, renamer) -> None: + """把一张表上需要改名的列一次改完,目标名冲突则中止。 + + 核心逻辑:先根据反射列算出对照,目标名彼此重复或撞上保留列就抛错, + 避免 ALTER 中途把两列收成同名。SQLite 与 PostgreSQL 都走 op.alter_column。 + + Args: + table: 当前表名。 + renamer: 接受列名、返回新列名的函数。 + + Raises: + RuntimeError: 目标列名已存在或两条列改到同一个名字。 + """ + columns = sa.inspect(op.get_bind()).get_columns(table) + planned: list[tuple[dict, str]] = [] + for column in columns: + target = renamer(column["name"]) + if target != column["name"]: + planned.append((column, target)) + staying = {column["name"] for column in columns} - {column["name"] for column, _target in planned} + targets = [target for _column, target in planned] + duplicates = sorted({name for name in targets if targets.count(name) > 1}) + occupied = sorted(target for target in targets if target in staying) + if duplicates or occupied: + raise RuntimeError( + f"column rename collision on {table}: duplicates={duplicates} occupied={occupied}" + ) + for column, target in planned: + op.alter_column( + table, + column["name"], + new_column_name=target, + existing_type=column["type"], + existing_nullable=column["nullable"], + ) + + +def _iter_constraints(inspector, table: str): + """列出一张表上带名字的外键、唯一、检查和主键约束。 + + Args: + inspector: 当前连接的 SQLAlchemy Inspector。 + table: 表名。 + + Yields: + (kind, name, payload)。kind 使用 alembic batch 的 type_ 取值。 + 外键 payload 是反射字典,唯一/主键 payload 是列名列表,检查 payload 是表达式。 + """ + for foreign_key in inspector.get_foreign_keys(table) or []: + yield "foreignkey", foreign_key.get("name"), foreign_key + for unique in inspector.get_unique_constraints(table) or []: + yield "unique", unique.get("name"), list(unique.get("column_names") or []) + for check in inspector.get_check_constraints(table) or []: + yield "check", check.get("name"), check.get("sqltext") + primary = inspector.get_pk_constraint(table) or {} + yield "primary", primary.get("name"), list(primary.get("constrained_columns") or []) + + +def _collect_renames(bind, pairs: list[tuple[str, str]], *, reverse: bool) -> dict: + """扫描全库,收集名称中含表名 token、因而需要改名的索引和约束。 + + 核心逻辑:PostgreSQL 上唯一/主键约束与其支撑索引同名,只改约束 + (RENAME CONSTRAINT 会带走索引)。SQLite 上独立索引用重建, + 表内约束才进 batch;同名时以索引为准,避免拆掉已经改过的索引。 + + Args: + bind: 当前迁移连接。 + pairs: 本方向的表名替换对。 + reverse: True 表示 downgrade。 + + Returns: + {表名: (索引列表[(旧, 新)], 约束列表[(kind, 旧, 新, payload)])}。 + """ + inspector = sa.inspect(bind) + dialect = bind.dialect.name + planned: dict[str, tuple[list, list]] = {} + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + raw_indexes = [] + for index in inspector.get_indexes(table) or []: + name = index.get("name") + if name and not str(name).startswith("sqlite_"): + raw_indexes.append(name) + raw_constraints = [] + for kind, name, payload in _iter_constraints(inspector, table): + if name and not str(name).startswith("sqlite_"): + raw_constraints.append((kind, name, payload)) + + index_rows: list[tuple[str, str]] = [] + constraint_rows: list[tuple[str, str, str, object]] = [] + if dialect == "postgresql": + constraint_names = {name for _kind, name, _payload in raw_constraints} + for kind, name, payload in raw_constraints: + target = _target_name(name, pairs, reverse=reverse) + if target != name: + constraint_rows.append((kind, name, target, payload)) + for name in raw_indexes: + if name in constraint_names: + continue + target = _target_name(name, pairs, reverse=reverse) + if target != name: + index_rows.append((name, target)) + else: + index_names = set(raw_indexes) + for name in raw_indexes: + target = _target_name(name, pairs, reverse=reverse) + if target != name: + index_rows.append((name, target)) + for kind, name, payload in raw_constraints: + if name in index_names: + continue + target = _target_name(name, pairs, reverse=reverse) + if target != name: + constraint_rows.append((kind, name, target, payload)) + if index_rows or constraint_rows: + planned[table] = (index_rows, constraint_rows) + _reject_collisions(planned, _existing_object_names(inspector)) + return planned + + +def _existing_object_names(inspector) -> set[str]: + """收集当前库里全部索引名和约束名,供目标名冲突检查。 + + Args: + inspector: 当前连接的 Inspector。 + + Returns: + 已占用的对象名集合。 + """ + found: set[str] = set() + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + for index in inspector.get_indexes(table) or []: + if index.get("name"): + found.add(index["name"]) + for _kind, name, _payload in _iter_constraints(inspector, table): + if name: + found.add(name) + return found + + +def _reject_collisions(planned: dict, existing: set[str]) -> None: + """目标对象名不能互相重复,也不能盖住一个本次不改名的既有对象。 + + Args: + planned: _collect_renames 的结果。 + existing: 当前已占用的对象名。 + + Raises: + RuntimeError: 两个对象要改成同一个名字,或目标名已被占用。 + """ + sources: list[str] = [] + targets: list[str] = [] + for index_rows, constraint_rows in planned.values(): + for old, new in index_rows: + sources.append(old) + targets.append(new) + for _kind, old, new, _payload in constraint_rows: + sources.append(old) + targets.append(new) + if len(targets) != len(set(targets)): + raise RuntimeError(f"object rename target collision: {targets}") + source_set = set(sources) + occupied = sorted(target for target in targets if target in existing and target not in source_set) + if occupied: + raise RuntimeError(f"object rename would overwrite existing names: {occupied}") + + +def _rename_index(bind, old_name: str, new_name: str) -> None: + """改索引名。PostgreSQL 用 ALTER INDEX;SQLite 按 sqlite_master 重建。 + + Args: + bind: 当前迁移连接。 + old_name: 现名。 + new_name: 新名。 + + Raises: + RuntimeError: SQLite 找不到可重建的 CREATE INDEX 语句。 + """ + if bind.dialect.name == "postgresql": + op.execute(sa.text( + f"ALTER INDEX {_quote_ident(old_name)} RENAME TO {_quote_ident(new_name)}" + )) + return + row = bind.execute( + sa.text("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :name"), + {"name": old_name}, + ).fetchone() + if row is None or not row[0]: + raise RuntimeError(f"sqlite index {old_name} has no SQL to rebuild") + sql = row[0] + quoted = f'"{old_name}"' + if quoted in sql: + rebuilt = sql.replace(quoted, _quote_ident(new_name), 1) + elif old_name in sql: + rebuilt = sql.replace(old_name, new_name, 1) + else: + raise RuntimeError(f"index SQL does not contain {old_name}: {sql}") + op.execute(sa.text(f"DROP INDEX {_quote_ident(old_name)}")) + op.execute(sa.text(rebuilt)) + + +def _rename_constraints(bind, table: str, constraints: list) -> None: + """改一张表上的约束名。 + + 核心逻辑:PostgreSQL 只 RENAME CONSTRAINT,不重建表。SQLite 没有 + RENAME CONSTRAINT,用一次 batch 先删后建,保留列、删除动作和外键目标。 + + Args: + bind: 当前迁移连接。 + table: 约束所在表(已经是本阶段的表名)。 + constraints: (kind, 旧名, 新名, payload) 列表。 + """ + if not constraints: + return + if bind.dialect.name == "postgresql": + for _kind, old_name, new_name, _payload in constraints: + op.execute(sa.text( + f"ALTER TABLE {_quote_ident(table)} " + f"RENAME CONSTRAINT {_quote_ident(old_name)} TO {_quote_ident(new_name)}" + )) + return + with op.batch_alter_table(table) as batch: + for kind, old_name, _new_name, _payload in constraints: + batch.drop_constraint(old_name, type_=kind) + for kind, _old_name, new_name, payload in constraints: + if kind == "foreignkey": + options = payload.get("options") or {} + batch.create_foreign_key( + new_name, + payload["referred_table"], + payload["constrained_columns"], + payload["referred_columns"], + ondelete=options.get("ondelete"), + onupdate=options.get("onupdate"), + deferrable=options.get("deferrable"), + initially=options.get("initially"), + match=options.get("match"), + referent_schema=payload.get("referred_schema"), + ) + elif kind == "unique": + batch.create_unique_constraint(new_name, payload) + elif kind == "check": + batch.create_check_constraint(new_name, payload) + elif kind == "primary": + batch.create_primary_key(new_name, payload) + else: + raise RuntimeError(f"unsupported constraint kind {kind}") + + +def _rewrite_object_names(pairs: list[tuple[str, str]], *, reverse: bool) -> None: + """改写全库里名称包含旧/新表名的索引和约束。 + + 核心逻辑:SQLite 先改索引再 batch 约束,这样 batch 反射到的是新索引名。 + PostgreSQL 先改约束(连带支撑索引),再改剩余普通索引。 + + Args: + pairs: 本方向的表名替换对。 + reverse: True 表示 downgrade。 + """ + bind = op.get_bind() + planned = _collect_renames(bind, pairs, reverse=reverse) + if bind.dialect.name == "postgresql": + for table, (_indexes, constraints) in planned.items(): + _rename_constraints(bind, table, constraints) + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + return + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + refreshed = _collect_renames(bind, pairs, reverse=reverse) + for table, (_indexes, constraints) in refreshed.items(): + _rename_constraints(bind, table, constraints) + + +def _index_names(table: str) -> set[str]: + """列出一张表上当前的索引名。 + + Args: + table: 当前表名。 + + Returns: + 非空索引名集合。表不存在时返回空集。 + """ + bind = op.get_bind() + inspector = sa.inspect(bind) + if table not in set(inspector.get_table_names()): + return set() + return {index["name"] for index in inspector.get_indexes(table) or [] if index.get("name")} + + +def _ensure_recipient_index() -> None: + """补建入站投递单列索引,名字与模型一致。 + + 核心逻辑:历史迁移没有这条索引。表已经改成新名之后,短名不存在才创建, + 避免重复升级再插一条同名索引。 + """ + if _CREATED_RECIPIENT_INDEX not in _index_names(_CREATED_RECIPIENT_TABLE): + op.create_index( + _CREATED_RECIPIENT_INDEX, + _CREATED_RECIPIENT_TABLE, + _CREATED_RECIPIENT_COLUMNS, + ) + + +def _drop_recipient_index() -> None: + """删掉升级补建的入站投递单列索引。 + + 核心逻辑:这条索引没有旧名。降级开始时表仍是新名,按短名删除;不存在则跳过。 + """ + if _CREATED_RECIPIENT_INDEX in _index_names(_CREATED_RECIPIENT_TABLE): + op.drop_index(_CREATED_RECIPIENT_INDEX, table_name=_CREATED_RECIPIENT_TABLE) + + +def upgrade() -> None: + """29 表升级:改列、改表名、再改索引与约束名。 + + 核心逻辑:列改名发生在旧表名上,这样 receipt 表仍能被识别。 + rename_table 之后外键指向的表已经是新名,对象名扫描只改名字不改指向。 + 最后补建历史迁移里不存在的单列 recipient 索引。 + """ + for old, _new in _TABLE_RENAMES: + _rename_columns(old, lambda column, table=old: _forward_column_name(table, column)) + for old, new in _TABLE_RENAMES: + op.rename_table(old, new) + _rewrite_object_names(_TABLE_RENAMES, reverse=False) + _ensure_recipient_index() + + +def downgrade() -> None: + """按升级的相反顺序还原对象名、表名和列名。 + + 核心逻辑:先删掉升级补建的单列索引,再还原其余对象名。验证批次索引 + 经 _EXPLICIT_INDEX_NAMES 回到 ix_inventory_test_run_validation_batch。 + """ + _drop_recipient_index() + reverse_pairs = [(new, old) for old, new in _TABLE_RENAMES] + _rewrite_object_names(reverse_pairs, reverse=True) + for old, new in reversed(_TABLE_RENAMES): + op.rename_table(new, old) + for old, _new in reversed(_TABLE_RENAMES): + _rename_columns(old, lambda column, table=old: _reverse_column_name(table, column)) diff --git a/backend/migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py b/backend/migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py new file mode 100644 index 00000000..62f927c8 --- /dev/null +++ b/backend/migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py @@ -0,0 +1,481 @@ +""" +migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py + +用途:批次 S 第二段,只改存量字符串,不改 s17b 的表结构。 + 把 job_type、options_source、权限模块键、审计/任务事件名、 + step/stage/action 契约码从 inventory/receipt 词根改成 onhand/inbound。 +依赖:alembic.op、SQLAlchemy;down_revision 为 s17b1c2d3e4f5a。 +逻辑:按词边界替换已知列里的文本(JSON 先转成文本再写回,避免改格式)。 + 权限模块键只替换 JSON 键 "shipping_inventory",并写入私有标记 + __s17c_perm_module;降级只回滚带该标记的行。 + PostgreSQL 上 shipping_audit_events 的 UPDATE 触发器在本迁移语句内临时关闭。 + 改写审计字段后用 audit_snapshot_service 的同一套哈希重算 event_hash。 + 不改 shipment_* / freight_upload*,也不改 s17b。 + schedule_tasks.data_source_type 的历史整值改成现行 job key freight-rpa-onhand。 +""" + +from __future__ import annotations + +import json +import re + +import sqlalchemy as sa +from alembic import op + + +revision = "s17c2d3e4f5a6" +down_revision = "s17b1c2d3e4f5a" +branch_labels = None +depends_on = None + +# 升级方向。更长的旧词必须排在前面,避免短词先吃掉长词的一部分。 +_EXACT_PAIRS: tuple[tuple[str, str], ...] = ( + ("retry_inventory_from_field_mapping", "retry_onhand_from_field_mapping"), + ("retry_inventory_from_preparation", "retry_onhand_from_preparation"), + ("retry_inventory_from_matching", "retry_onhand_from_matching"), + ("refresh_inventory_candidate_projection", "refresh_onhand_candidate_projection"), + ("override_line_inventory_source", "override_line_onhand_source"), + ("recheck_inventory_sufficiency", "recheck_onhand_sufficiency"), + ("retry_inventory_field_mapping", "retry_onhand_field_mapping"), + ("retry_inventory_preparation", "retry_onhand_preparation"), + ("poll_inventory_preparation", "poll_onhand_preparation"), + ("open_inventory_match_review", "open_onhand_match_review"), + ("retry_inventory_matching", "retry_onhand_matching"), + ("reload_inventory_result", "reload_onhand_result"), + ("download_inventory_file", "download_onhand_file"), + ("release_inventory_shortage", "release_onhand_shortage"), + ("upload_inventory_file", "upload_onhand_file"), + ("inventory_source_resolving", "onhand_source_resolving"), + ("inventory_source_routing", "onhand_source_routing"), + ("inventory_field_mapping", "onhand_field_mapping"), + ("inventory_preparation", "onhand_preparation"), + ("inventory_sufficiency", "onhand_sufficiency"), + ("shipping_inventory_callback_process", "freight_rpa_onhand_callback_process"), + ("shipping_inventory_callback_ignored", "freight_rpa_onhand_callback_ignored"), + ("shipping_inventory_sources", "freight_rpa_sources"), + ("shipping_receipt_sources", "freight_rpa_inbound_sources"), + ("shipping_receipt_rpa_callback_received", "shipping_inbound_rpa_callback_received"), + ("shipping_receipt_rpa_callback_timeout", "shipping_inbound_rpa_callback_timeout"), + ("shipping_receipt_rpa_units_listed", "shipping_inbound_rpa_units_listed"), + ("shipping_receipt_rpa_unit_retried", "shipping_inbound_rpa_unit_retried"), + ("rpa_report_inventory", "rpa_report_onhand"), + ("step3_inventory_prepare", "step3_onhand_prepare"), + ("step5_match_inventory", "step5_match_onhand"), + ("inventory_fetching", "onhand_fetching"), + ("inventory_matching", "onhand_matching"), + ("wait_inventory", "wait_onhand"), + ("ensure_inventory", "ensure_onhand"), +) + +# 权限模块 JSON 键。降级只认本迁移写入的标记,避免把 Task 5 已有的 freight_rpa 改回去。 +_PERMISSION_MARKER = "__s17c_perm_module" + +# (表, 列, 是否 JSON)。缺表或缺列则跳过。 +_COLUMNS: tuple[tuple[str, str, bool], ...] = ( + ("jobs", "job_type", False), + ("jobs", "payload_json", True), + ("jobs", "result_json", True), + ("jobs", "message", False), + ("jobs", "error_message", False), + ("kb_jobs", "job_type", False), + ("schedule_tasks", "job_params", True), + ("shipping_order_tasks", "stage", False), + ("shipping_order_tasks", "current_step", False), + ("shipping_order_tasks", "pending_human_reason", False), + ("shipping_order_tasks", "error_code", False), + ("shipping_order_tasks", "step_payload_json", True), + ("shipping_order_processing_runs", "current_stage_code", False), + ("shipping_order_processing_runs", "progress_summary_json", True), + ("shipping_task_events", "event_type", False), + ("shipping_task_events", "source", False), + ("shipping_task_events", "detail_json", True), + ("shipping_task_events", "before_json", True), + ("shipping_task_events", "after_json", True), + ("shipping_audit_events", "event_type", False), + ("shipping_audit_events", "source", False), + ("shipping_audit_events", "action", False), + ("shipping_audit_events", "reason_code", False), + ("shipping_audit_events", "error_code", False), + ("shipping_audit_events", "before_snapshot_json", True), + ("shipping_audit_events", "after_snapshot_json", True), + ("shipping_audit_events", "diff_json", True), + ("shipping_audit_events", "metadata_json", True), + ("shipping_audit_events", "context_refs_json", True), + ("shipping_process_executions", "current_gate_code", False), + ("shipping_process_executions", "last_passed_gate_code", False), + ("shipping_process_executions", "primary_next_action_code", False), + ("shipping_process_gates", "gate_code", False), + ("shipping_process_gates", "next_action_code", False), + ("shipping_process_gates", "blocking_reason_code", False), + ("shipping_process_gates", "blocking_reason_json", True), + ("shipping_process_gates", "recommendation_json", True), + ("shipping_process_gates", "effective_result_json", True), + ("shipping_process_gate_attempts", "input_snapshot_json", True), + ("shipping_process_gate_attempts", "output_snapshot_json", True), + ("shipping_process_gate_attempts", "rule_snapshot_json", True), + ("shipping_process_gate_attempts", "error_code", False), + ("shipping_process_recovery_plans", "current_gate", False), + ("shipping_process_recovery_plans", "action_code", False), + ("shipping_process_recovery_plans", "target_gate", False), + ("shipping_process_recovery_plans", "resume_after_gate", False), + ("shipping_process_recovery_plans", "failure_code", False), + ("shipping_process_recovery_plans", "invalidation_plan_json", True), + ("shipping_process_recovery_plans", "failure_detail_json", True), + ("shipping_onhand_preparation_attempts", "input_snapshot_json", True), + ("shipping_onhand_preparation_attempts", "output_snapshot_json", True), + ("shipping_onhand_preparation_source_attempts", "skip_reason", False), + ("freight_rpa_onhand_task_rpa_attempts", "error_code", False), + ("freight_rpa_onhand_task_rpa_attempts", "error_message", False), + ("freight_rpa_onhand_task_rpa_attempts", "callback_payload_json", True), + ("freight_rpa_onhand_task_rpa_attempts", "extra_json", True), +) + +_PERMISSION_COLUMNS: tuple[tuple[str, str, bool], ...] = ( + ("users", "feature_permissions", True), + ("permission_roles", "feature_permissions", True), + ("app_settings", "value", False), +) + +_AUDIT_TRIGGER = "trg_shipping_audit_events_no_update" + +# 排程 data_source_type 的整列等值。不是子串替换,避免把现行 platform_api_path 改回去。 +_LEGACY_ONHAND_DATA_SOURCE = "shipping_inventory_rpa" +_ONHAND_PLATFORM_JOB_KEY = "freight-rpa-onhand" + + +def _pairs(direction: str) -> tuple[tuple[str, str], ...]: + """返回某一方向的整词对照,按旧词长度降序。""" + pairs = _EXACT_PAIRS if direction == "upgrade" else tuple((new, old) for old, new in _EXACT_PAIRS) + return tuple(sorted(pairs, key=lambda item: len(item[0]), reverse=True)) + + +def _apply_permission_module(value: str, direction: str) -> str: + """ + 只改权限模块 JSON 键 "shipping_inventory" ↔ "freight_rpa"。 + + 核心逻辑:升级替换带引号且后接冒号的键,并写入 __s17c_perm_module。 + 降级仅当标记还在时把该键改回并删掉标记。不改 freight_rpa_sources 等更长标识, + 也不改升级之前就已经是 "freight_rpa" 的行。 + """ + if direction == "upgrade": + pattern = re.compile(r'"shipping_inventory"(\s*:)') + if pattern.search(value) is None: + return value + updated = pattern.sub(r'"freight_rpa"\1', value) + if f'"{_PERMISSION_MARKER}"' in updated: + return updated + stripped = updated.rstrip() + if not stripped.endswith("}"): + return updated + body = stripped[:-1].rstrip() + comma = "" if body.endswith("{") else "," + return f'{body}{comma}"{_PERMISSION_MARKER}":true}}' + if f'"{_PERMISSION_MARKER}"' not in value: + return value + updated = re.sub(r'"freight_rpa"(\s*:)', r'"shipping_inventory"\1', value) + updated = re.sub( + rf',?\s*"{re.escape(_PERMISSION_MARKER)}"\s*:\s*true', + "", + updated, + ) + updated = re.sub(r"\{\s*,", "{", updated) + updated = re.sub(r",\s*\}", "}", updated) + return updated + + +def _prefix_pattern(direction: str) -> re.Pattern[str]: + """inventory_rpa_* / onhand_rpa_* 前缀。不吃模块名 inventory_rpa_workflow。""" + if direction == "upgrade": + return re.compile(r"(? str | None: + """ + 按词边界把存量契约字符串换成目标词根。 + + 核心逻辑:整词优先(长词在前),再替换 inventory_rpa_ / onhand_rpa_ 前缀。 + 路径片段(前有 / 或 \\,或后接 .py)和 ensure_inventory_via_rpa 这类更长标识不改。 + permission=True 时只改带引号的权限模块 JSON 键,降级依赖 __s17c_perm_module 标记。 + + Args: + value: 列的原始文本。None 原样返回。 + direction: upgrade 或 downgrade。 + permission: 是否对本列应用权限模块键。 + + Returns: + 替换后的文本;无变化时与输入相同。 + """ + if value is None: + return None + updated = str(value) + for old, new in _pairs(direction): + updated = re.sub( + rf"(? str: + """给表名或列名加双引号,避免 key 这类保留字。""" + return '"' + name.replace('"', "") + '"' + + +def _set_audit_update_trigger(connection, enabled: bool) -> None: + """PostgreSQL 上临时开关审计表的禁更新触发器。其它方言无此触发器。""" + if connection.dialect.name != "postgresql": + return + if not connection.execute( + sa.text("SELECT 1 FROM pg_trigger WHERE tgname = :name"), + {"name": _AUDIT_TRIGGER}, + ).scalar(): + return + verb = "ENABLE" if enabled else "DISABLE" + connection.execute(sa.text( + f"ALTER TABLE shipping_audit_events {verb} TRIGGER {_AUDIT_TRIGGER}" + )) + + +def _rewrite_column(connection, table: str, column: str, is_json: bool, *, permission: bool, direction: str) -> None: + """ + 重写一张表的一列。表或列不存在则跳过。 + + 核心逻辑:只选出文本里带 inventory、receipt RPA、receipt options_source 或降级新词的行, + 词边界替换后按主键写回。JSON 列在 PostgreSQL 上 CAST 回 JSON。 + """ + inspector = sa.inspect(connection) + if table not in inspector.get_table_names(): + return + column_names = {item["name"] for item in inspector.get_columns(table)} + if column not in column_names: + return + pk_cols = inspector.get_pk_constraint(table).get("constrained_columns") or [] + if len(pk_cols) != 1: + return + pk = pk_cols[0] + if direction == "upgrade": + needles = ("%inventory%", "%shipping_receipt_rpa_%", "%shipping_receipt_sources%") + else: + needles = ("%onhand%", "%shipping_inbound_rpa_%", "%freight_rpa%") + rows = connection.execute(sa.text( + f"SELECT {_quote(pk)}, CAST({_quote(column)} AS TEXT) " + f"FROM {_quote(table)} " + f"WHERE CAST({_quote(column)} AS TEXT) LIKE :needle " + f"OR CAST({_quote(column)} AS TEXT) LIKE :receipt " + f"OR CAST({_quote(column)} AS TEXT) LIKE :perm" + ), {"needle": needles[0], "receipt": needles[1], "perm": needles[2]}).fetchall() + dialect = connection.dialect.name + for row_id, raw in rows: + rewritten = rewrite_persisted_text(raw, direction=direction, permission=permission) + if rewritten is None or rewritten == raw: + continue + if dialect == "postgresql" and is_json: + statement = ( + f"UPDATE {_quote(table)} SET {_quote(column)} = CAST(:value AS JSON) " + f"WHERE {_quote(pk)} = :row_id" + ) + else: + statement = ( + f"UPDATE {_quote(table)} SET {_quote(column)} = :value " + f"WHERE {_quote(pk)} = :row_id" + ) + connection.execute(sa.text(statement), {"value": rewritten, "row_id": row_id}) + + +_AUDIT_HASH_FIELDS = ( + "id", + "event_type", + "aggregate_type", + "aggregate_id", + "action", + "result", + "reason_code", + "workflow_id", + "workflow_item_id", + "workflow_item_version_id", + "version_no", + "run_no", + "document_id", + "review_case_no", + "task_no", + "operation_id", + "request_id", + "actor_type", + "actor_id", + "before_snapshot_json", + "after_snapshot_json", + "diff_json", + "previous_event_hash", + "event_hash", + "sensitivity_level", +) + + +def _json_object(raw: object) -> dict | None: + """把审计快照列还原成 dict;空值或非对象返回 None。""" + if raw is None or raw == "": + return None + if isinstance(raw, dict): + return raw + try: + parsed = json.loads(str(raw)) + except (TypeError, ValueError): + return None + return parsed if isinstance(parsed, dict) else None + + +def _rehash_shipping_audit_events(connection) -> None: + """ + 用生产同一套 build_event_hash_payload / compute_event_hash 重算审计哈希。 + + 核心逻辑:按聚合 id 升序走链。本行内容变了就重算 event_hash; + 前一行哈希变了就把本行 previous_event_hash 接上再重算,避免链断裂。 + 缺 event_hash 列则跳过。 + """ + inspector = sa.inspect(connection) + if "shipping_audit_events" not in inspector.get_table_names(): + return + present = {item["name"] for item in inspector.get_columns("shipping_audit_events")} + if "id" not in present or "event_hash" not in present or "event_type" not in present: + return + from app.services.shipping_notice.audit_snapshot_service import ( + build_event_hash_payload, + compute_event_hash, + ) + + selected = [name for name in _AUDIT_HASH_FIELDS if name in present] + rows = connection.execute(sa.text( + "SELECT " + ", ".join(_quote(name) for name in selected) + " FROM shipping_audit_events ORDER BY " + + ("aggregate_type, aggregate_id, " if "aggregate_type" in present and "aggregate_id" in present else "") + + "id" + )).mappings().all() + running_hash: str | None = None + current_group: tuple[str, str] | None = None + for row in rows: + group = ( + str(row.get("aggregate_type") or ""), + str(row.get("aggregate_id") or ""), + ) + if group != current_group: + current_group = group + running_hash = None + previous_for_hash = row.get("previous_event_hash") + else: + previous_for_hash = running_hash + payload = build_event_hash_payload( + event_type=str(row.get("event_type") or ""), + aggregate_type=str(row.get("aggregate_type") or ""), + aggregate_id=str(row.get("aggregate_id") or ""), + action=row.get("action"), + result=row.get("result"), + reason_code=row.get("reason_code"), + workflow_id=row.get("workflow_id"), + workflow_item_id=row.get("workflow_item_id"), + workflow_item_version_id=row.get("workflow_item_version_id"), + version_no=row.get("version_no"), + run_no=row.get("run_no"), + document_id=row.get("document_id"), + review_case_no=row.get("review_case_no"), + task_no=row.get("task_no"), + operation_id=row.get("operation_id"), + request_id=row.get("request_id"), + actor_type=str(row.get("actor_type") or "system"), + actor_id=row.get("actor_id"), + before_snapshot=_json_object(row.get("before_snapshot_json")), + after_snapshot=_json_object(row.get("after_snapshot_json")), + diff_json=_json_object(row.get("diff_json")), + previous_event_hash=previous_for_hash, + sensitivity_level=row.get("sensitivity_level"), + ) + new_hash = compute_event_hash(payload) + if new_hash != row.get("event_hash") or previous_for_hash != row.get("previous_event_hash"): + if "previous_event_hash" in present: + connection.execute(sa.text( + "UPDATE shipping_audit_events SET event_hash = :event_hash, " + "previous_event_hash = :previous_event_hash WHERE id = :row_id" + ), { + "event_hash": new_hash, + "previous_event_hash": previous_for_hash, + "row_id": row["id"], + }) + else: + connection.execute(sa.text( + "UPDATE shipping_audit_events SET event_hash = :event_hash WHERE id = :row_id" + ), {"event_hash": new_hash, "row_id": row["id"]}) + running_hash = new_hash + + +def _rewrite_legacy_onhand_data_source(connection, direction: str) -> None: + """ + 把 schedule_tasks.data_source_type 的历史整值改成现行 platform job key。 + + 核心逻辑:只匹配整列相等,不扫描其它列里的 freight-rpa-onhand。 + 升级同时把 schedule_type / platform_api_path 拨到 platform_job。 + 降级只把 data_source_type 从现行 job key 改回历史整值。 + + Args: + connection: Alembic 绑定的连接。 + direction: upgrade 或 downgrade。 + """ + inspector = sa.inspect(connection) + if "schedule_tasks" not in inspector.get_table_names(): + return + columns = {item["name"] for item in inspector.get_columns("schedule_tasks")} + if "data_source_type" not in columns: + return + if direction == "upgrade": + assignments = [f"{_quote('data_source_type')} = :new_source"] + params: dict[str, str] = { + "old_source": _LEGACY_ONHAND_DATA_SOURCE, + "new_source": _ONHAND_PLATFORM_JOB_KEY, + } + if "schedule_type" in columns: + assignments.append(f"{_quote('schedule_type')} = 'platform_job'") + if "platform_api_path" in columns: + assignments.append(f"{_quote('platform_api_path')} = :new_source") + connection.execute(sa.text( + f"UPDATE {_quote('schedule_tasks')} SET {', '.join(assignments)} " + f"WHERE {_quote('data_source_type')} = :old_source" + ), params) + return + connection.execute(sa.text( + f"UPDATE {_quote('schedule_tasks')} SET {_quote('data_source_type')} = :old_source " + f"WHERE {_quote('data_source_type')} = :new_source" + ), { + "old_source": _LEGACY_ONHAND_DATA_SOURCE, + "new_source": _ONHAND_PLATFORM_JOB_KEY, + }) + + +def _rewrite_all(connection, direction: str) -> None: + """按列清单重写契约字符串。审计表在 PostgreSQL 上先关禁更新触发器。""" + _set_audit_update_trigger(connection, enabled=False) + try: + _rewrite_legacy_onhand_data_source(connection, direction) + for table, column, is_json in _COLUMNS: + _rewrite_column( + connection, table, column, is_json, permission=False, direction=direction, + ) + for table, column, is_json in _PERMISSION_COLUMNS: + _rewrite_column( + connection, table, column, is_json, permission=True, direction=direction, + ) + _rehash_shipping_audit_events(connection) + finally: + _set_audit_update_trigger(connection, enabled=True) + + +def upgrade() -> None: + """把存量枚举、事件名、job_type、options_source 和权限模块键改成新词。""" + _rewrite_all(op.get_bind(), "upgrade") + + +def downgrade() -> None: + """按同一对照表把新词改回旧词。""" + _rewrite_all(op.get_bind(), "downgrade") diff --git a/backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py b/backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py new file mode 100644 index 00000000..e6e65aa3 --- /dev/null +++ b/backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py @@ -0,0 +1,563 @@ +""" +migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py + +用途:货代 RPA 阶段 B 第一段——新建在手报表配置表 freight_rpa_onhand_report_configs, + 把站点表 freight_rpa_sources 上的 report_path_json / query_parameters_json / + parsing_profile_id 三列搬进该表,把启用检查约束换成只看 excel_template_id 的 + 模板版本(CHECK 不能跨表),再把 shipping_onhand_files 改名为 + freight_rpa_onhand_report_files,并按 s17b 的手法重写名字含旧表名的 + 索引 / 约束对象名(列名一概不改)。 +依赖:alembic.op、SQLAlchemy 反射;down_revision 为批次 S 第二段 s17c2d3e4f5a6。 + 解析方案表已在 s17b 落到 freight_rpa_parsing_profiles,本迁移不再出现 + 解析方案表的第二条改名,禁止出现 freight_rpa_onhand_parsing_profiles。 +逻辑:先建配置表(外键到 freight_rpa_sources / freight_rpa_parsing_profiles / users, + source_id 唯一),再把三列数据 INSERT 过去;然后用 batch_alter_table + (PostgreSQL 直发 ALTER,SQLite 走重建)删旧启用约束、删三列、建模板约束; + rename_table 之后扫全库对象名,把 shipping_onhand_files token 替换为 + freight_rpa_onhand_report_files,超过 PostgreSQL 63 字节的沿用 s17b 的截断。 + downgrade 按相反顺序还原:文件表改回旧名并回滚对象名,三列加回站点行, + 从配置表 UPDATE 回数据(无配置行的站点两列 JSON 用 COALESCE 回填 '{}' / '[]', + 避免 NULL 写入 NOT NULL 列),删掉配置表,最后恢复 + ck_freight_rpa_sources_enabled_bindings 原文(双绑定表达式)。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = "s18d1e2f3a4b5" +down_revision = "s17c2d3e4f5a6" +branch_labels = None +depends_on = None + +# PostgreSQL 标识符上限(NAMEDATALEN-1),与 s17b 一致。 +_MAX_IDENTIFIER_LENGTH = 63 + +_SOURCES_TABLE = "freight_rpa_sources" +_CONFIG_TABLE = "freight_rpa_onhand_report_configs" +_FILES_TABLE_OLD = "shipping_onhand_files" +_FILES_TABLE_NEW = "freight_rpa_onhand_report_files" + +# c27e 创建、s17b 改到新表名词根的启用约束,及其双绑定原文与模板版替代。 +_ENABLED_BINDINGS_CHECK = "ck_freight_rpa_sources_enabled_bindings" +_ENABLED_TEMPLATE_CHECK = "ck_freight_rpa_sources_enabled_template" +_ENABLED_BINDINGS_SQL = ( + "enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)" +) +_ENABLED_TEMPLATE_SQL = "enabled = false OR excel_template_id IS NOT NULL" +# b17 建出的站点→解析方案外键名(不含旧表名词根,s17b 未改名),降级按原名还原。 +_SOURCES_PARSING_FK = "fk_inventory_sources_parsing_profile" +# 站点→解析方案列的自动索引名(模型 index=True;s17b 换到新表名词根),降级补回。 +_SOURCES_PARSING_INDEX = "ix_freight_rpa_sources_parsing_profile_id" +# 本期搬离站点行的三列。 +_MOVED_COLUMNS = ("report_path_json", "query_parameters_json", "parsing_profile_id") + + +def _quote_ident(name: str) -> str: + """给 SQL 标识符加双引号,内部引号按标准加倍。 + + Args: + name: 表、索引或约束名。 + + Returns: + 可拼进 DDL 的引用标识符。 + """ + return '"' + name.replace('"', '""') + '"' + + +def _substitute(name: str, pairs: list[tuple[str, str]]) -> str: + """把对象名中的表名 token 换成对照表里的另一个名字。 + + 核心逻辑:按源 token 长度降序替换,避免短表名吃掉更长表名的前缀。 + 本迁移只有一对 token(文件表新旧名),直接替换。 + + Args: + name: 当前索引或约束名。 + pairs: (被替换的表名, 替换后的表名)。升级用旧→新,降级用新→旧。 + + Returns: + 替换后的对象名(尚未按 63 字节截断)。 + """ + updated = name + for source, destination in sorted(pairs, key=lambda item: len(item[0]), reverse=True): + updated = updated.replace(source, destination) + return updated + + +def _clip(name: str) -> str: + """把标识符限制在 PostgreSQL 的 63 字节以内(沿用 s17b 的截断函数)。 + + Args: + name: 已完成表名替换的对象名。 + + Returns: + 长度不超过 63 的名字。未超长时原样返回。 + """ + if len(name) <= _MAX_IDENTIFIER_LENGTH: + return name + return name[:_MAX_IDENTIFIER_LENGTH] + + +def _iter_constraints(inspector, table: str): + """列出一张表上带名字的外键、唯一、检查和主键约束。 + + Args: + inspector: 当前连接的 SQLAlchemy Inspector。 + table: 表名。 + + Yields: + (kind, name, payload)。kind 使用 alembic batch 的 type_ 取值。 + 外键 payload 是反射字典,唯一/主键 payload 是列名列表,检查 payload 是表达式。 + """ + for foreign_key in inspector.get_foreign_keys(table) or []: + yield "foreignkey", foreign_key.get("name"), foreign_key + for unique in inspector.get_unique_constraints(table) or []: + yield "unique", unique.get("name"), list(unique.get("column_names") or []) + for check in inspector.get_check_constraints(table) or []: + yield "check", check.get("name"), check.get("sqltext") + primary = inspector.get_pk_constraint(table) or {} + yield "primary", primary.get("name"), list(primary.get("constrained_columns") or []) + + +def _target_name(current: str, pairs: list[tuple[str, str]]) -> str: + """计算对象改名的目标:表名替换再截断。 + + Args: + current: 库里现在的对象名。 + pairs: 本方向的表名替换对。 + + Returns: + 应改成的对象名。与 current 相同表示不用改。 + """ + return _clip(_substitute(current, pairs)) + + +def _existing_object_names(inspector) -> set[str]: + """收集当前库里全部索引名和约束名,供目标名冲突检查。 + + Args: + inspector: 当前连接的 Inspector。 + + Returns: + 已占用的对象名集合。 + """ + found: set[str] = set() + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + for index in inspector.get_indexes(table) or []: + if index.get("name"): + found.add(index["name"]) + for _kind, name, _payload in _iter_constraints(inspector, table): + if name: + found.add(name) + return found + + +def _reject_collisions(planned: dict, existing: set[str]) -> None: + """目标对象名不能互相重复,也不能盖住一个本次不改名的既有对象。 + + Args: + planned: {表名: (索引列表, 约束列表)} 形态的改名计划。 + existing: 当前已占用的对象名。 + + Raises: + RuntimeError: 两个对象要改成同一个名字,或目标名已被占用。 + """ + sources: list[str] = [] + targets: list[str] = [] + for index_rows, constraint_rows in planned.values(): + for old_name, new_name in index_rows: + sources.append(old_name) + targets.append(new_name) + for _kind, old_name, new_name, _payload in constraint_rows: + sources.append(old_name) + targets.append(new_name) + if len(targets) != len(set(targets)): + raise RuntimeError(f"object rename target collision: {targets}") + source_set = set(sources) + occupied = sorted(target for target in targets if target in existing and target not in source_set) + if occupied: + raise RuntimeError(f"object rename would overwrite existing names: {occupied}") + + +def _collect_renames(bind, pairs: list[tuple[str, str]]) -> dict: + """扫描全库,收集名称中含表名 token、因而需要改名的索引和约束。 + + 核心逻辑(沿用 s17b):PostgreSQL 上唯一/主键约束与其支撑索引同名, + 只走约束(RENAME CONSTRAINT 会带走索引);SQLite 上独立索引用重建, + 表内约束才进 batch,同名时以索引为准,避免拆掉已改过的索引。 + + Args: + bind: 当前迁移连接。 + pairs: 本方向的表名替换对。 + + Returns: + {表名: (索引列表[(旧, 新)], 约束列表[(kind, 旧, 新, payload)])}。 + """ + inspector = sa.inspect(bind) + dialect = bind.dialect.name + planned: dict[str, tuple[list, list]] = {} + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + raw_indexes: list[str] = [] + for index in inspector.get_indexes(table) or []: + name = index.get("name") + if name and not str(name).startswith("sqlite_"): + raw_indexes.append(name) + raw_constraints = [] + for kind, name, payload in _iter_constraints(inspector, table): + if name and not str(name).startswith("sqlite_"): + raw_constraints.append((kind, name, payload)) + + index_rows: list[tuple[str, str]] = [] + constraint_rows: list[tuple[str, str, str, object]] = [] + if dialect == "postgresql": + constraint_names = {name for _kind, name, _payload in raw_constraints} + for kind, name, payload in raw_constraints: + target = _target_name(name, pairs) + if target != name: + constraint_rows.append((kind, name, target, payload)) + for name in raw_indexes: + if name in constraint_names: + continue + target = _target_name(name, pairs) + if target != name: + index_rows.append((name, target)) + else: + index_names = set(raw_indexes) + for name in raw_indexes: + target = _target_name(name, pairs) + if target != name: + index_rows.append((name, target)) + for kind, name, payload in raw_constraints: + if name in index_names: + continue + target = _target_name(name, pairs) + if target != name: + constraint_rows.append((kind, name, target, payload)) + if index_rows or constraint_rows: + planned[table] = (index_rows, constraint_rows) + _reject_collisions(planned, _existing_object_names(inspector)) + return planned + + +def _rename_index(bind, old_name: str, new_name: str) -> None: + """改索引名。PostgreSQL 用 ALTER INDEX;SQLite 按 sqlite_master 重建。 + + Args: + bind: 当前迁移连接。 + old_name: 现名。 + new_name: 新名。 + + Raises: + RuntimeError: SQLite 找不到可重建的 CREATE INDEX 语句。 + """ + if bind.dialect.name == "postgresql": + op.execute(sa.text( + f"ALTER INDEX {_quote_ident(old_name)} RENAME TO {_quote_ident(new_name)}" + )) + return + row = bind.execute( + sa.text("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :name"), + {"name": old_name}, + ).fetchone() + if row is None or not row[0]: + raise RuntimeError(f"sqlite index {old_name} has no SQL to rebuild") + sql = row[0] + quoted = f'"{old_name}"' + if quoted in sql: + rebuilt = sql.replace(quoted, _quote_ident(new_name), 1) + elif old_name in sql: + rebuilt = sql.replace(old_name, new_name, 1) + else: + raise RuntimeError(f"index SQL does not contain {old_name}: {sql}") + op.execute(sa.text(f"DROP INDEX {_quote_ident(old_name)}")) + op.execute(sa.text(rebuilt)) + + +def _rename_constraints(bind, table: str, constraints: list) -> None: + """改一张表上的约束名。 + + 核心逻辑(沿用 s17b):PostgreSQL 只 RENAME CONSTRAINT,不重建表; + SQLite 没有 RENAME CONSTRAINT,用一次 batch 先删后建, + 保留列、外键目标与删除动作。 + + Args: + bind: 当前迁移连接。 + table: 约束所在表(已经是本阶段的表名)。 + constraints: (kind, 旧名, 新名, payload) 列表。 + """ + if not constraints: + return + if bind.dialect.name == "postgresql": + for _kind, old_name, new_name, _payload in constraints: + op.execute(sa.text( + f"ALTER TABLE {_quote_ident(table)} " + f"RENAME CONSTRAINT {_quote_ident(old_name)} TO {_quote_ident(new_name)}" + )) + return + with op.batch_alter_table(table) as batch: + for kind, old_name, _new_name, _payload in constraints: + batch.drop_constraint(old_name, type_=kind) + for kind, _old_name, new_name, payload in constraints: + if kind == "foreignkey": + options = payload.get("options") or {} + batch.create_foreign_key( + new_name, + payload["referred_table"], + payload["constrained_columns"], + payload["referred_columns"], + ondelete=options.get("ondelete"), + onupdate=options.get("onupdate"), + deferrable=options.get("deferrable"), + initially=options.get("initially"), + match=options.get("match"), + referent_schema=payload.get("referred_schema"), + ) + elif kind == "unique": + batch.create_unique_constraint(new_name, payload) + elif kind == "check": + batch.create_check_constraint(new_name, payload) + elif kind == "primary": + batch.create_primary_key(new_name, payload) + else: + raise RuntimeError(f"unsupported constraint kind {kind}") + + +def _rewrite_object_names(pairs: list[tuple[str, str]]) -> None: + """改写全库里名称包含旧/新文件表名的索引和约束。 + + 核心逻辑(沿用 s17b):SQLite 先改索引再 batch 约束,这样 batch + 反射到的是新索引名;PostgreSQL 先改约束(连带支撑索引), + 再改剩余普通索引。 + + Args: + pairs: 本方向的表名替换对。 + """ + bind = op.get_bind() + planned = _collect_renames(bind, pairs) + if bind.dialect.name == "postgresql": + for table, (_indexes, constraints) in planned.items(): + _rename_constraints(bind, table, constraints) + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + return + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + refreshed = _collect_renames(op.get_bind(), pairs) + for table, (_indexes, constraints) in refreshed.items(): + _rename_constraints(op.get_bind(), table, constraints) + + +def _enabled_bindings_constraint_name(bind) -> str | None: + """找到站点表上现存的旧启用检查约束名。 + + 核心逻辑:优先按 s17b 之后的既定名 ck_freight_rpa_sources_enabled_bindings + 命中;若历史库上的名字仍是改名前的其它拼写,则按「定义里同时含 + parsing_profile_id 与 excel_template_id」反射定位那一条再删。 + + Args: + bind: 当前迁移连接。 + + Returns: + 约束名;站点上没有该约束时返回 None。 + """ + checks = sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or [] + for item in checks: + if item.get("name") == _ENABLED_BINDINGS_CHECK: + return item["name"] + for item in checks: + sqltext = str(item.get("sqltext") or "") + if "parsing_profile_id" in sqltext and "excel_template_id" in sqltext: + return item.get("name") + return None + + +def _create_config_table() -> None: + """新建在手报表配置表,形状与 ShippingOnhandReportConfig 模型一致。 + + 核心逻辑:source_id 唯一且指向站点(级联删除);parsing_profile_id + 可空,指向 s17b 落定的 freight_rpa_parsing_profiles;created_by / + updated_by 指向 users。JSON 两列与 config_version 同入站配置表风格。 + """ + op.create_table( + _CONFIG_TABLE, + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("source_id", sa.Integer(), nullable=False), + sa.Column("parsing_profile_id", sa.Integer(), nullable=True), + sa.Column("report_path_json", sa.JSON(), nullable=False, server_default=sa.text("'{}'")), + sa.Column("query_parameters_json", sa.JSON(), nullable=False, server_default=sa.text("'[]'")), + sa.Column("config_version", sa.Integer(), nullable=False, server_default=sa.text("1")), + sa.Column("created_by", sa.Integer(), nullable=True), + sa.Column("updated_by", sa.Integer(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint( + ["source_id"], ["freight_rpa_sources.id"], + name="fk_freight_rpa_onhand_report_configs_source", ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"], + name="fk_freight_rpa_onhand_report_configs_parsing_profile", + ), + sa.ForeignKeyConstraint(["created_by"], ["users.id"]), + sa.ForeignKeyConstraint(["updated_by"], ["users.id"]), + sa.UniqueConstraint("source_id", name="uq_freight_rpa_onhand_report_configs_source"), + ) + op.create_index( + "ix_freight_rpa_onhand_report_configs_source_id", _CONFIG_TABLE, ["source_id"], + ) + op.create_index( + "ix_freight_rpa_onhand_report_configs_parsing_profile_id", + _CONFIG_TABLE, + ["parsing_profile_id"], + ) + + +def _moved_column_dependents(bind) -> tuple[list[str], list[str]]: + """列出站点表上直接依赖三列中任一列的索引与外键名。 + + 核心逻辑:SQLite batch 重建不会自动放弃被删列上的索引(alembic 会按原样重建), + PostgreSQL 虽随列自动删除,但先显式 DROP 也不冲突;故两侧统一先删。 + 只有约束列与被删列相交的对象算依赖,excel_template 等其余外键不动。 + + Args: + bind: 当前迁移连接。 + + Returns: + (索引名列表, 外键名列表)。无名的内部对象反射不出名字,本就不在重建范围。 + """ + inspector = sa.inspect(bind) + dropped = set(_MOVED_COLUMNS) + index_names = [ + str(item["name"]) + for item in inspector.get_indexes(_SOURCES_TABLE) or [] + if item.get("name") + and set(item.get("column_names") or []) & dropped + ] + foreign_key_names = [ + str(item["name"]) + for item in inspector.get_foreign_keys(_SOURCES_TABLE) or [] + if item.get("name") + and set(item.get("constrained_columns") or []) & dropped + ] + return index_names, foreign_key_names + + +def _move_columns_off_source() -> None: + """删站点上三列,替换启用约束为模板版。 + + 核心逻辑:数据已 INSERT 到配置表后才执行。batch_alter_table 在 + PostgreSQL 直发 ALTER,在 SQLite 走重建;解析方案外键与其索引随 + parsing_profile_id 列一并消失。 + """ + bind = op.get_bind() + old_check = _enabled_bindings_constraint_name(bind) + moved_indexes, moved_keys = _moved_column_dependents(bind) + checks = { + item.get("name") + for item in sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or [] + } + with op.batch_alter_table(_SOURCES_TABLE) as batch: + # 被删列上的索引/外键先显式退场,SQLite 重建才不会引用已不存在的列。 + for index_name in moved_indexes: + batch.drop_index(index_name) + for foreign_key_name in moved_keys: + batch.drop_constraint(foreign_key_name, type_="foreignkey") + if old_check: + batch.drop_constraint(old_check, type_="check") + batch.drop_column("report_path_json") + batch.drop_column("query_parameters_json") + batch.drop_column("parsing_profile_id") + if _ENABLED_TEMPLATE_CHECK not in checks: + batch.create_check_constraint(_ENABLED_TEMPLATE_CHECK, _ENABLED_TEMPLATE_SQL) + + +def _restore_columns_on_source() -> None: + """把三列按原可空性与默认值加回站点行,并去掉模板版启用约束。 + + 核心逻辑:downgrade 专用。parsing_profile_id 外键按 b17 的原名 + fk_inventory_sources_parsing_profile 还原(s17b 未改过该名)。 + """ + bind = op.get_bind() + checks = { + item.get("name") + for item in sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or [] + } + with op.batch_alter_table(_SOURCES_TABLE) as batch: + if _ENABLED_TEMPLATE_CHECK in checks: + batch.drop_constraint(_ENABLED_TEMPLATE_CHECK, type_="check") + batch.add_column(sa.Column( + "report_path_json", sa.JSON(), nullable=False, server_default=sa.text("'{}'"), + )) + batch.add_column(sa.Column( + "query_parameters_json", sa.JSON(), nullable=False, server_default=sa.text("'[]'"), + )) + batch.add_column(sa.Column("parsing_profile_id", sa.Integer(), nullable=True)) + batch.create_foreign_key( + _SOURCES_PARSING_FK, "freight_rpa_parsing_profiles", + ["parsing_profile_id"], ["id"], + ) + batch.create_index(_SOURCES_PARSING_INDEX, ["parsing_profile_id"]) + + +def upgrade() -> None: + """建在手报表配置表、搬三列、换启用约束、改文件表名并重写对象名。 + + 核心逻辑:顺序不可颠倒——配置表必须先于数据搬移存在;三列必须先搬 + 数据再删;文件表改名后 object 名扫描才能扫到旧 token 的索引/约束。 + """ + # [STEP 1] 配置表就位并把站点三列数据搬到新表(created_by/updated_by 留空)。 + _create_config_table() + op.execute(sa.text( + "INSERT INTO freight_rpa_onhand_report_configs " + "(source_id, report_path_json, query_parameters_json, parsing_profile_id, " + "config_version, created_at, updated_at) " + "SELECT id, report_path_json, query_parameters_json, parsing_profile_id, " + "config_version, created_at, updated_at FROM freight_rpa_sources" + )) + # [STEP 2] 站点行删三列,启用约束换成只看 excel_template_id 的模板版。 + _move_columns_off_source() + # [STEP 3] 在手文件表归 RPA:改表名并重写名字含旧表名的索引/约束对象名。 + op.rename_table(_FILES_TABLE_OLD, _FILES_TABLE_NEW) + _rewrite_object_names([(_FILES_TABLE_OLD, _FILES_TABLE_NEW)]) + + +def downgrade() -> None: + """按升级相反顺序还原:文件表名、三列、数据、配置表与旧启用约束。 + + 核心逻辑:先改回文件表并回滚对象名;再在站点上恢复三列与外键, + 从配置表 UPDATE 回数据后删表;最后重建 ck_freight_rpa_sources_enabled_bindings + 原文(parsing_profile + excel_template 双绑定)。 + """ + # [STEP 1] 在手文件表名与对象名回滚。 + op.rename_table(_FILES_TABLE_NEW, _FILES_TABLE_OLD) + _rewrite_object_names([(_FILES_TABLE_NEW, _FILES_TABLE_OLD)]) + # [STEP 2] 站点行加回三列与解析方案外键,模板版启用约束退场。 + _restore_columns_on_source() + # [STEP 3] 把配置行数据 UPDATE 回站点行。站点没有配置行时子查询返回 NULL, + # 两列 JSON 在站点行上是 NOT NULL,必须 COALESCE 回 server_default 形态; + # parsing_profile_id 可空,允许保持 NULL。 + op.execute(sa.text( + "UPDATE freight_rpa_sources SET " + "report_path_json = COALESCE((" + "SELECT c.report_path_json FROM freight_rpa_onhand_report_configs c " + "WHERE c.source_id = freight_rpa_sources.id), '{}'), " + "query_parameters_json = COALESCE((" + "SELECT c.query_parameters_json FROM freight_rpa_onhand_report_configs c " + "WHERE c.source_id = freight_rpa_sources.id), '[]'), " + "parsing_profile_id = (" + "SELECT c.parsing_profile_id FROM freight_rpa_onhand_report_configs c " + "WHERE c.source_id = freight_rpa_sources.id)" + )) + # [STEP 4] 配置表退役。 + op.drop_table(_CONFIG_TABLE) + # [STEP 5] 恢复双绑定的原启用约束。 + with op.batch_alter_table(_SOURCES_TABLE) as batch: + batch.create_check_constraint(_ENABLED_BINDINGS_CHECK, _ENABLED_BINDINGS_SQL) \ No newline at end of file diff --git a/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py b/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py index 8f53a27e..dff99daa 100644 --- a/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py +++ b/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py @@ -8,7 +8,7 @@ Create Date: 2026-10-16 shipping-inventory-rpa→freight-rpa-onhand(在手/库存)、 freight-receipt-rpa→freight-rpa-inbound(入站/收料)、 freight-receipt-rpa-retention→freight-rpa-inbound-retention(入站归档保留期清理), - 与 job_registry.py / freight_onhand_rpa_*、freight_inbound_rpa_* 排程壳改名同窗口发布。 + 与 job_registry.py / freight_rpa_onhand_*、freight_rpa_inbound_* 排程壳改名同窗口发布。 依赖:实施时 flask db heads 的单 head 为 tt16a7b8c9d0e1f2(调拨域迁移,其上游即 tt15b6a7b8c9d0);本迁移若直挂 tt15 会产生双 head,故按单 head 纪律链在其上。 逻辑:列为 platform_api_path(String(500),承载归一化 job key——自 b9c0d1e2f3a4 起 diff --git a/backend/scripts/import_shipping_inventory_sources.py b/backend/scripts/import_freight_rpa_sources.py similarity index 71% rename from backend/scripts/import_shipping_inventory_sources.py rename to backend/scripts/import_freight_rpa_sources.py index 27f4343c..4529d2dd 100644 --- a/backend/scripts/import_shipping_inventory_sources.py +++ b/backend/scripts/import_freight_rpa_sources.py @@ -1,10 +1,12 @@ -"""Import legacy YAML inventory sources into the shipping configuration database. +""" +scripts/import_freight_rpa_sources.py -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. +用途:把期初 YAML 库存源导入 freight_rpa_sources / freight_rpa_profiles 主数据。 +依赖:Flask app、SQLAlchemy、PyYAML、models.FreightRpaSource、models.FreightRpaProfile、 + models.FreightRpaOnhandReportConfig(s18 起报表路径/查询条件归配置行)。 +逻辑:由运维手工执行;读取 config/freight_rpa_sources.yaml,按平台与登录地址复用连接, + 导入行一律保持停用,不导入 selector 与凭据;YAML 的报表路径与查询条件写入 + FreightRpaOnhandReportConfig 配置行,解析方案绑定留空。运行时不再读这份 YAML。 """ from __future__ import annotations @@ -17,7 +19,7 @@ import yaml from app import create_app from app.extensions import db -from app.models import ShippingInventorySource, ShippingRpaProfile +from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile CONNECTOR_TYPES = {"dsv360": "dbs", "crane_footprint": "crane"} @@ -30,7 +32,9 @@ def _source_payload(raw: dict[str, Any]) -> dict[str, Any]: raw: A source item from the legacy YAML document. Returns: - Normalized source fields suitable for ``ShippingInventorySource``. + Normalized source fields for ``FreightRpaSource`` plus the + ``report_path_json`` / ``query_parameters_json`` carried by + ``FreightRpaOnhandReportConfig`` since s18. """ connector_type = CONNECTOR_TYPES.get(str(raw.get("connector_type") or "").strip().lower()) if connector_type is None: @@ -64,32 +68,32 @@ def _source_payload(raw: dict[str, Any]) -> dict[str, Any]: } -def _connection_for(source: dict[str, Any]) -> ShippingRpaProfile: +def _connection_for(source: dict[str, Any]) -> FreightRpaProfile: """Return a compatible connection, reusing configured credentials whenever possible.""" - profile = ShippingRpaProfile.query.filter_by( + profile = FreightRpaProfile.query.filter_by( connector_type=source["connector_type"], login_url=source["login_url"], - ).order_by(ShippingRpaProfile.id).first() + ).order_by(FreightRpaProfile.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() + profile = FreightRpaProfile.query.filter_by(connector_type="dbs").filter( + (FreightRpaProfile.username_ciphertext.is_not(None)) | (FreightRpaProfile.password_ciphertext.is_not(None)) + ).order_by(FreightRpaProfile.credential_updated_at.desc(), FreightRpaProfile.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() + profile = FreightRpaProfile.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 = FreightRpaProfile( profile_code=code, display_name="DBS 平台" if source["connector_type"] == "dbs" else "Crane 平台", connector_type=source["connector_type"], @@ -118,9 +122,9 @@ def import_sources(path: Path) -> tuple[int, int]: continue data = _source_payload(raw) profile = _connection_for(data) - source = ShippingInventorySource.query.filter_by(source_code=data["source_code"]).first() + source = FreightRpaSource.query.filter_by(source_code=data["source_code"]).first() if source is None: - source = ShippingInventorySource( + source = FreightRpaSource( 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, @@ -132,18 +136,24 @@ def import_sources(path: Path) -> tuple[int, int]: 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"] + # s18 起报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行(无则插入); + # 解析方案绑定保持 None,与今日导入语义一致(启用前由管理员绑定)。 + config = source.onhand_report_config + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + db.session.add(config) + config.parsing_profile_id = None + config.report_path_json = data["report_path_json"] + config.query_parameters_json = data["query_parameters_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() + placeholder = FreightRpaProfile.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() @@ -152,13 +162,13 @@ def import_sources(path: Path) -> tuple[int, int]: 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")) + parser = argparse.ArgumentParser(description="Import legacy freight RPA sources") + parser.add_argument("--file", type=Path, default=Path("config/freight_rpa_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}") + print(f"Imported freight RPA sources: created={created}, updated={updated}") if __name__ == "__main__": diff --git a/backend/tests/api/test_freight_rpa_api.py b/backend/tests/api/test_freight_rpa_api.py index 2ca627df..bba3ccef 100644 --- a/backend/tests/api/test_freight_rpa_api.py +++ b/backend/tests/api/test_freight_rpa_api.py @@ -35,17 +35,17 @@ def terminal_configuration_test_run(app): """预置一个已终态的配置测试运行 + 批次,供 configuration-test 三端点走 OK envelope 路径。""" from app import db from app.models import ( - ShippingInventoryConfigurationTestRun, - ShippingInventorySource, - ShippingInventoryValidationBatch, + FreightRpaOnhandConfigurationTestRun, + FreightRpaSource, + FreightRpaOnhandValidationBatch, ) - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - batch = ShippingInventoryValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1) + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + batch = FreightRpaOnhandValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1) db.session.add(batch) db.session.flush() - run = ShippingInventoryConfigurationTestRun( - run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, inventory_source_id=source.id, + run = FreightRpaOnhandConfigurationTestRun( + run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version, status='completed', stage='current_profile_verified', result_json={}, diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py index 041e0311..96e22206 100644 --- a/backend/tests/api/test_in_transit_transfer_api.py +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -664,21 +664,21 @@ def _seed_parse_failed_inbound_file(source_code: str): from uuid import uuid4 from app.models import ( - ShippingInventorySource, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + FreightRpaSource, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - source = ShippingInventorySource.query.filter_by(source_code=source_code).one() - unit = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source.source_code, + source = FreightRpaSource.query.filter_by(source_code=source_code).one() + unit = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type=source.connector_type, warehouse_id=source.fixed_warehouse_id, callback_id=f"receipt-retry-{uuid4().hex[:12]}", status="success", config_snapshot_json={}, ) db.session.add(unit) db.session.flush() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", storage_key=f"shipping/receipt/retry-{unit.id}.xlsx", original_filename="retry.xlsx", file_size=16, @@ -699,14 +699,14 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header def fake_sync(*, source_code, business_date, now): # 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回 # ready(请求会话内重查后清除并 commit,保证端点再解析可见)。 - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile from app.services.in_transit_transfer.source_file_status import clear_inbound_parse_failure called["sync"] += 1 file = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter(ShippingReceiptReportFile.unit_run.has(source_code=source_code)) + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter(FreightRpaInboundReportFile.unit_run.has(source_code=source_code)) .first() ) if file is not None: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index f9039013..6980893d 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -90,7 +90,7 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers" ) if request.node.get_closest_marker("auto_rpa"): - app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False monkeypatch.setattr( @@ -102,7 +102,7 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): lambda: None, ) return - app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False + app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False # 货代自动上传默认 fail-closed;单测与产品默认一致关闭。 app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False @@ -123,9 +123,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): def _shipping_test_default_destination(monkeypatch, request): """ 为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。 - 标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。 + 标记 onhand_source_gate 的用例跳过,避免干扰库存源门禁专项测试。 """ - if request.node.get_closest_marker("inventory_source_gate"): + if request.node.get_closest_marker("onhand_source_gate"): return from app.services.shipping_notice import extract as extract_mod @@ -170,9 +170,9 @@ def seed_task_inventory_source( owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None)) if owner is None: raise ValueError('test task must be linked to ShippingOrderTask') - from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task - from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_candidates_for_task + from app.services.shipping_notice.onhand_source_rules import InventorySourceAdjudication + from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) @@ -391,7 +391,7 @@ def seed_rpa_inventory_trigger( run_no: str = "RUN-TEST-001", trigger_path: str | None = None, ) -> None: - """测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。""" + """测试辅助:写入 onhand_rpa_triggered 事件,供单任务回调 run_no 校验。""" from app import db from app.services.shipping_notice.tool_common import log_task_event @@ -401,7 +401,7 @@ def seed_rpa_inventory_trigger( trigger = trigger_path or f"inventory_export_batch_{run_no}.json" log_task_event( task, - "inventory_rpa_triggered", + "onhand_rpa_triggered", {"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False}, ) @@ -448,10 +448,10 @@ def inventory_csv_with_warehouse( def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]: """构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。""" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source_code = next(iter(task_frozen_onhand_source_codes(task)), '') source = get_database_inventory_source(source_code) or {} return { "source_code": str(source_code or ""), @@ -461,7 +461,7 @@ def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]: def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]: """构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。""" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(source_code) if not source: @@ -492,10 +492,10 @@ def rpa_callback_payload( status: str = "success", ) -> dict: """构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。""" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source_code = next(iter(task_frozen_onhand_source_codes(task)), '') source = get_database_inventory_source(source_code) or {} return { "schema_version": "freight_rpa.onhand.v1", @@ -528,7 +528,7 @@ def pytest_configure(config): ) config.addinivalue_line( "markers", - "inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入", + "onhand_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入", ) config.addinivalue_line( "markers", @@ -572,13 +572,17 @@ def app(): def _seed_test_inventory_configuration() -> None: - """为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。""" + """为发货测试创建数据库库存源、在手报表配置与发布路由规则,测试运行期不读取 YAML。 + + s18 起:报表路径/查询条件/解析方案挂在 FreightRpaOnhandReportConfig 上, + 站点行只剩连接、模板绑定与启停。 + """ from app import db from app.models import ( - ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource, - ShippingRpaProfile, + ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, FreightRpaSource, FreightRpaProfile, ) - from app.services.shipping_notice.inventory_structure_fingerprint import ( + from app.services.shipping_notice.onhand_structure_fingerprint import ( FINGERPRINT_VERSION, compatibility_fingerprint, exact_fingerprint, @@ -586,24 +590,24 @@ def _seed_test_inventory_configuration() -> None: ) # 各测试显式创建所需用户字段;生产目录本身保持零预置。 - if not ShippingInventoryField.query.filter_by(field_code='part_number').first(): + if not FreightRpaOnhandField.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), + FreightRpaOnhandField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10), + FreightRpaOnhandField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20), + FreightRpaOnhandField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30), + FreightRpaOnhandField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40), + FreightRpaOnhandField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100), + FreightRpaOnhandField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110), + FreightRpaOnhandField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120), + FreightRpaOnhandField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130), + FreightRpaOnhandField(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_([ + for item in FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.field_code.in_([ 'part_number', 'reservation_id', 'available_qty', 'warehouse_id', ]) ).all() @@ -641,7 +645,7 @@ def _seed_test_inventory_configuration() -> None: checksum = hashlib.sha256( json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() ).hexdigest() - parsing_profile = ShippingInventoryParsingProfile( + parsing_profile = FreightRpaParsingProfile( profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published', file_format='xlsx', definition_json=definition, checksum=checksum, structure_definition_json=structure, @@ -658,14 +662,20 @@ def _seed_test_inventory_configuration() -> None: file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64, ) - profile = ShippingRpaProfile( + profile = FreightRpaProfile( 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 = FreightRpaSource( source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs', - rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template, + rpa_profile=profile, excel_template=excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU', + enabled=True, + ) + # s18 起报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig,站点行不再承载。 + report_config = FreightRpaOnhandReportConfig( + source=source, + parsing_profile=parsing_profile, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv', @@ -673,9 +683,8 @@ def _seed_test_inventory_configuration() -> None: query_parameters_json=[ {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False}, ], - enabled=True, ) - db.session.add_all([profile, parsing_profile, excel_template, source]) + db.session.add_all([profile, parsing_profile, excel_template, source, report_config]) db.session.commit() diff --git a/backend/tests/jobs/test_store.py b/backend/tests/jobs/test_store.py index 3bad89f2..746e87db 100644 --- a/backend/tests/jobs/test_store.py +++ b/backend/tests/jobs/test_store.py @@ -68,7 +68,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app): with app.app_context(): job = Job( domain='shipping_notice', - job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value, + job_type=JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS.value, status='queued', payload_json={'callback_id': 'callback-test'}, ) @@ -79,7 +79,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app): assert claimed is not None assert claimed['id'] == job.id - assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS + assert claimed['job_type'] == JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS def test_claim_next_transfer_claims_run_job(app): diff --git a/backend/tests/services/admin/test_shipping_inventory_service.py b/backend/tests/services/admin/test_shipping_onhand_service.py similarity index 66% rename from backend/tests/services/admin/test_shipping_inventory_service.py rename to backend/tests/services/admin/test_shipping_onhand_service.py index e9cc5dcb..1d37f15b 100644 --- a/backend/tests/services/admin/test_shipping_inventory_service.py +++ b/backend/tests/services/admin/test_shipping_onhand_service.py @@ -2,7 +2,7 @@ tests/services/admin/test_shipping_inventory_service.py 用途:验证库存主数据管理服务的安全性和关键业务约束。 -依赖:Flask app/db、shipping_inventory_service、库存配置模型。 +依赖:Flask app/db、shipping_onhand_admin_service、库存配置模型。 逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。 """ @@ -12,16 +12,16 @@ 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.admin import shipping_onhand_admin_service +from app.services.shipping_notice import onhand_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, - ShippingInventorySource, - ShippingInventorySourceParsingBindingAudit, - ShippingInventoryStructureAnalysis, + FreightRpaOnhandField, + FreightRpaSource, + FreightRpaSourceParsingBindingAudit, + FreightRpaOnhandStructureAnalysis, ) @@ -35,7 +35,7 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict: def _sample_evidence() -> int: """创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。""" - item = ShippingInventoryStructureAnalysis( + item = FreightRpaOnhandStructureAnalysis( source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None, file_checksum='b' * 64, file_format='xlsx', analysis_status='ready', structure_json={'candidates': [{ @@ -88,13 +88,13 @@ def _parsing_profile() -> dict: ) 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', + for item in FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + FreightRpaOnhandField.status == 'active', ).all() } assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'} - draft = inventory_parsing_profile.save_draft({ + draft = onhand_parsing_profile.save_draft({ 'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(), 'definition': { @@ -110,7 +110,7 @@ def _parsing_profile() -> dict: }], }, }, actor_id=None) - return inventory_parsing_profile.publish(draft['id'], actor_id=None) + return onhand_parsing_profile.publish(draft['id'], actor_id=None) def _excel_template_id() -> int: @@ -133,17 +133,21 @@ def _excel_template_id() -> int: 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'], + 'rpa_profile_id': 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', + # s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。 + 'onhand_report_config': { + 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'], + '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}, + ], }, - 'query_parameters_json': [ - {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, - ], } @@ -160,7 +164,7 @@ def test_profile_credentials_are_not_returned(app): """Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + payload = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) assert payload['password_configured'] is True assert payload['username_masked'] == 'configured' assert 'password' not in payload @@ -174,7 +178,7 @@ def test_profile_rejects_page_operation_configuration(app): 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) + shipping_onhand_admin_service.save_profile(payload, actor_id=None) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID' @@ -182,10 +186,10 @@ def test_multiple_dbs_profiles_bind_independent_sources(app): """同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。""" app.config['FREIGHT_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) + first = shipping_onhand_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) + second = shipping_onhand_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None) + first_source = shipping_onhand_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None) + second_source = shipping_onhand_admin_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'] @@ -194,34 +198,36 @@ def test_source_rejects_profile_connector_mismatch(app): """库存源不能绑定不同 Driver 的 Profile。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_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' + shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH' def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): """禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。""" app.config['FREIGHT_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) + login = shipping_onhand_admin_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) + payload.update({'enabled': False, 'excel_template_id': None}) + payload['onhand_report_config']['parsing_profile_id'] = None + draft = shipping_onhand_admin_service.save_source(payload, actor_id=None) assert draft['enabled'] is False - assert draft['parsing_profile_id'] is None + assert draft['onhand_report_config']['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' + shipping_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id']) + assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED' + # 拒绝后回滚脏会话(等价于请求边界回滚):s18 服务在赋值后才触发启用门禁, + # 不回滚会让后续查询的 autoflush 把 enabled=True + 空模板撞 CHECK。 + db.session.rollback() - 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']) + payload['onhand_report_config']['parsing_profile_id'] = _parsing_profile()['id'] + payload['excel_template_id'] = _excel_template_id() + enabled = shipping_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id']) assert enabled['enabled'] is True @@ -229,22 +235,23 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): """普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。""" app.config['FREIGHT_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) + login = shipping_onhand_admin_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) + payload.update({'enabled': False, 'excel_template_id': None}) + payload['onhand_report_config']['parsing_profile_id'] = None + draft = shipping_onhand_admin_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'] payload['enabled'] = True - saved = shipping_inventory_service.save_source( + saved = shipping_onhand_admin_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' + shipping_onhand_admin_service.activate_source(draft['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED' assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template'] @@ -252,18 +259,23 @@ def test_activation_status_exposes_only_hard_gate_checks(app): """启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) + login = shipping_onhand_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) payload = { 'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs', - 'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None, + 'rpa_profile_id': login['id'], 'excel_template_id': None, 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600, - 'report_path_json': { - 'program_group': 'Bison', 'program_label': 'AWSBI', - 'report_group': 'Inventory', 'report_name': 'On Hand', + # s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行。 + 'onhand_report_config': { + 'parsing_profile_id': None, + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand', + }, + 'query_parameters_json': [], }, - 'query_parameters_json': [], 'enabled': False, + 'enabled': False, } - draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) + draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) checks = {item['code']: item for item in draft['activation']['checks']} @@ -280,11 +292,11 @@ def test_enabled_source_rejects_disabled_rpa_profile(app): """启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile( + profile = shipping_onhand_admin_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) + shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED' @@ -292,10 +304,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app): """数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。""" app.config['FREIGHT_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'] == [ + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + # s18 起报表路径/查询条件挂在响应的 onhand_report_config 嵌套对象上。 + assert source['onhand_report_config']['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv' + assert source['onhand_report_config']['query_parameters_json'] == [ {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, ] @@ -304,52 +317,54 @@ def test_source_rejects_driver_selector_in_business_parameters(app): """业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) payload = _source_data(profile['id']) - payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' + payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_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' + shipping_onhand_admin_service.save_source(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID' def test_crane_source_rejects_dbs_report_path(app): """动态仓 Crane 库存源不得误填 DBS 四级报表路径。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_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' + shipping_onhand_admin_service.save_source(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID' def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app): """停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) + login = shipping_onhand_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE') - payload.update({'enabled': False, 'parsing_profile_id': None}) - source = shipping_inventory_service.save_source(payload, actor_id=7, allow_enable_transition=False) + payload.update({'enabled': False}) + payload['onhand_report_config']['parsing_profile_id'] = None + source = shipping_onhand_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False) profile = _parsing_profile() - bound = shipping_inventory_service.bind_source_parsing_profile( + bound = shipping_onhand_admin_service.bind_source_parsing_profile( [source['id']], profile['id'], actor_id=7, operation='direct', ) # 关键断言:直接绑定只配置解析定义,绝不绕过独立启用门禁。 assert bound[0]['enabled'] is False - assert bound[0]['parsing_profile_id'] == profile['id'] + # s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。 + assert bound[0]['onhand_report_config']['parsing_profile_id'] == profile['id'] assert bound[0]['config_version'] == source['config_version'] + 1 - audit = ShippingInventorySourceParsingBindingAudit.query.one() + audit = FreightRpaSourceParsingBindingAudit.query.one() assert audit.operation == 'direct' # 关键断言:审计保留系统动作说明,不要求管理员额外填写“绑定原因”。 assert audit.reason == '管理员直接绑定已发布解析方案' assert audit.before_snapshot_json['parsing_profile_id'] is None assert audit.after_snapshot_json['parsing_profile_id'] == profile['id'] - history = shipping_inventory_service.get_source_parsing_binding_audits(source['id']) + history = shipping_onhand_admin_service.get_source_parsing_binding_audits(source['id']) assert history[0]['actor_id'] == 7 assert history[0]['source_config_version_after'] == bound[0]['config_version'] @@ -358,33 +373,36 @@ def test_bulk_parsing_profile_binding_allows_enabled_sites(app): """批量绑定允许包含已启用站点;全部预检通过后原子写入。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) + login = shipping_onhand_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED') - disabled_payload.update({'enabled': False, 'parsing_profile_id': None}) - disabled = shipping_inventory_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False) - enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None) + disabled_payload.update({'enabled': False}) + disabled_payload['onhand_report_config']['parsing_profile_id'] = None + disabled = shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False) + enabled = shipping_onhand_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None) profile = _parsing_profile() - bound = shipping_inventory_service.bind_source_parsing_profile( + bound = shipping_onhand_admin_service.bind_source_parsing_profile( [disabled['id'], enabled['id']], profile['id'], actor_id=None, reason='批量迁移同类报表', operation='bulk', ) # 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。 assert {row['id'] for row in bound} == {disabled['id'], enabled['id']} - assert all(row['parsing_profile_id'] == profile['id'] for row in bound) - assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True - assert ShippingInventorySourceParsingBindingAudit.query.count() == 2 + # s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。 + assert all(row['onhand_report_config']['parsing_profile_id'] == profile['id'] for row in bound) + assert db.session.get(FreightRpaSource, enabled['id']).enabled is True + assert FreightRpaSourceParsingBindingAudit.query.count() == 2 def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app): """直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) + login = shipping_onhand_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE') - payload.update({'enabled': False, 'parsing_profile_id': None}) - source = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) + payload.update({'enabled': False}) + payload['onhand_report_config']['parsing_profile_id'] = None + source = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) template = db.session.get(ShippingExcelTemplate, source['excel_template_id']) template.definition_json = { 'filename_pattern': '{business_no}.xlsx', @@ -393,50 +411,51 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app db.session.commit() with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.bind_source_parsing_profile( + shipping_onhand_admin_service.bind_source_parsing_profile( [source['id']], _parsing_profile()['id'], actor_id=None, reason='模板字段契约预检', operation='direct', ) # 关键断言:模板依赖缺失必须在绑定时拒绝,不能产生半成品站点绑定。 - assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID' - assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None - assert ShippingInventorySourceParsingBindingAudit.query.count() == 0 + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID' + # s18 起解析绑定归 onhand_report_config 配置行;被拒后配置行必须保持未绑定。 + assert db.session.get(FreightRpaSource, source['id']).onhand_report_config.parsing_profile_id is None + assert FreightRpaSourceParsingBindingAudit.query.count() == 0 def test_published_rule_cannot_be_mutated_in_place(app): """发布规则必须依靠新版本演进,避免改写历史任务依据。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None) reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_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': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None) - shipping_inventory_service.publish_rule(rule['id'], actor_id=None) + shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None) with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.save_rule({ + shipping_onhand_admin_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': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None, rule_id=rule['id']) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE' + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_IMMUTABLE' def test_draft_rule_update_keeps_the_same_draft(app): """草稿更新应原地替换条件,不能偷偷新增同版本规则记录。""" with app.app_context(): reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'DUB'}], }, actor_id=None) - updated = shipping_inventory_service.save_rule({ + updated = shipping_onhand_admin_service.save_rule({ 'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'FRA'}], @@ -450,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app): """列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。""" with app.app_context(): reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_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': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': ['1001', '1002']}], @@ -458,106 +477,107 @@ def test_rule_condition_value_type_follows_the_selected_operator(app): assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002'] with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_rule({ + shipping_onhand_admin_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': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': '1001'}], }, actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID' + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_CONDITION_INVALID' def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app): """未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。""" app.config['FREIGHT_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()) + unused = shipping_onhand_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) + shipping_onhand_admin_service.delete_profile(unused['id']) + assert all(item['profile_code'] != 'UNUSED' for item in shipping_onhand_admin_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) + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.delete_profile(profile['id']) + shipping_onhand_admin_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']) + shipping_onhand_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id']) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED' reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_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': 'order_field', 'order_field_id': reservation_field_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) + shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None) + retired = shipping_onhand_admin_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' + shipping_onhand_admin_service.delete_draft_rule(rule['id']) + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_DELETE_BLOCKED' def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app): """发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) + source = shipping_onhand_admin_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) + disabled_payload.update({'enabled': False, 'excel_template_id': None}) + disabled_payload['onhand_report_config']['parsing_profile_id'] = None + shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None) reservation_field_id = _published_route_field_id() - missing_rule = shipping_inventory_service.save_rule({ + missing_rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None) with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID' + shipping_onhand_admin_service.publish_rule(missing_rule['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_SOURCE_INVALID' - disabled_rule = shipping_inventory_service.save_rule({ + disabled_rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}], }, actor_id=None) - assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published' + assert shipping_onhand_admin_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published' - valid_rule = shipping_inventory_service.save_rule({ + valid_rule = shipping_onhand_admin_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': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '9'}], }, actor_id=None) - assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published' + assert shipping_onhand_admin_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published' def test_active_default_external_mapping_is_unique_per_source(app): """同一库存源同一货代仓库身份只能有一条启用的映射。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) payload = { - 'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', + 'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', 'external_organization_code': None, 'external_site_code': 'EU01', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True, } - shipping_inventory_service.save_external_mapping(payload, actor_id=None) + shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None) with pytest.raises(ConflictError): - shipping_inventory_service.save_external_mapping(payload, actor_id=None) + shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None) def test_external_mapping_allows_empty_freight_warehouse(app): """货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) # [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。 - mapping = shipping_inventory_service.save_external_mapping({ - 'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP', + mapping = shipping_onhand_admin_service.save_external_mapping({ + 'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'tzr2', 'enabled': True, }, actor_id=None) @@ -569,12 +589,12 @@ def test_external_mapping_requires_in_transit_warehouse_code(app): """在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。""" app.config['FREIGHT_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) + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) # [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。 with pytest.raises(ValidationError): - shipping_inventory_service.save_external_mapping({ - 'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', + shipping_onhand_admin_service.save_external_mapping({ + '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) @@ -583,10 +603,10 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app): """配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。""" app.config['FREIGHT_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', + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + mapping = shipping_onhand_admin_service.save_external_mapping({ + 'source_id': source['id'], 'freight_warehouse_id': 'dub', 'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True, }, actor_id=None) @@ -597,32 +617,32 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app): """连接级上传配置(upload_config_json)变更不递增 config_version。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + profile = shipping_onhand_admin_service.save_profile(_profile_data(), actor_id=None) base_version = profile['config_version'] upload_cfg = { 'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2', 'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None, 'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120, } - updated = shipping_inventory_service.save_profile( + updated = shipping_onhand_admin_service.save_profile( {**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'], ) assert updated['config_version'] == base_version assert updated['upload_config_json']['enabled'] is True # 仅修改运行期连接配置(login_url)仍应递增 config_version。 - bumped = shipping_inventory_service.save_profile( + bumped = shipping_onhand_admin_service.save_profile( {**_profile_data(), 'login_url': 'https://example.invalid/login-v2'}, actor_id=None, profile_id=profile['id'], ) assert bumped['config_version'] == base_version + 1 # 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。 with pytest.raises(ValidationError): - shipping_inventory_service.save_profile( + shipping_onhand_admin_service.save_profile( {**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}}, actor_id=None, profile_id=profile['id'], ) with pytest.raises(ValidationError): - shipping_inventory_service.save_profile( + shipping_onhand_admin_service.save_profile( {**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}}, actor_id=None, profile_id=profile['id'], ) diff --git a/backend/tests/services/freight_rpa/test_import_boundary.py b/backend/tests/services/freight_rpa/test_import_boundary.py index ee7159dc..f081a633 100644 --- a/backend/tests/services/freight_rpa/test_import_boundary.py +++ b/backend/tests/services/freight_rpa/test_import_boundary.py @@ -1,9 +1,12 @@ """freight_rpa 包 import 边界适应度测试。 -用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。 +用途:锁死阶段 B 验收标准——freight_rpa 不寄生业务编排。 依赖:app/services/freight_rpa 包、ast。 逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败; - 白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。 + 白名单为空集(批次 B Task 6 起审计写入已下沉本包 + common/report_audit,包内不再引用任何 shipping_notice 业务模块; + 历史 file_assets 白名单条目随迁移一并删除——包内只引用 + app.services.file_assets,不属 shipping_notice 命名空间)。 """ from __future__ import annotations @@ -12,10 +15,9 @@ from pathlib import Path PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" -ALLOWED_SHIPPING_NOTICE = { - "app.services.shipping_notice.audit_service", - "app.services.shipping_notice.file_assets", -} +# 空集:freight_rpa 禁止 import 任何 app.services.shipping_notice.* 模块 +# (审计写入走本包 common/report_audit;模型 import 走 app.models,不在此列)。 +ALLOWED_SHIPPING_NOTICE: set[str] = set() def _imported_modules(path: Path) -> set[str]: @@ -28,7 +30,6 @@ def _imported_modules(path: Path) -> set[str]: mods.add(node.module) return mods - def test_freight_rpa_import_boundary(): assert PKG.exists(), "freight_rpa 包不存在" violations: list[str] = [] diff --git a/backend/tests/services/freight_rpa/test_report_fact_dispatch.py b/backend/tests/services/freight_rpa/test_report_fact_dispatch.py new file mode 100644 index 00000000..5bfa0c1e --- /dev/null +++ b/backend/tests/services/freight_rpa/test_report_fact_dispatch.py @@ -0,0 +1,196 @@ +"""tests/services/freight_rpa/test_report_fact_dispatch.py + +用途:锁定阶段 B Task 6——inbound 回调「先提交文件/终态,再投递事实」的顺序契约。 +依赖:pytest、tests/conftest 的 app 夹具(种子站点 DSV360_AWSDU)、 + app.core.errors.AppError、app.services.freight_rpa.reports.facts.ReportFact、 + freight_rpa.reports.dispatch.register_report_handler(Task 6 新增)、 + freight_rpa.inbound.report_archive.ingest_inbound_callback。 +逻辑:(1)处理函数抛异常时已 commit 的归档文件行仍在(不回滚)且异常原样外抛; + (2)同一 unit_run_id + sha256 重复回调不插第二行,事实仍重复投递 ok=True + (供处理函数重试);(3)kind 未注册处理函数时 404 + FREIGHT_RPA.SINK_NOT_REGISTERED,已提交文件行不受影响; + (4)empty 终态同样先 commit 再投递 ok=False 事实。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + +from app.services.freight_rpa.reports.facts import ReportFact + +SEED_SOURCE_CODE = "DSV360_AWSDU" + +# 归档 IO 替身的注入字节:_fake_archive_io 夹具把它喂给 +# _read_inbound_callback_file,_success_payload 按需覆写。 +_FAKE_FILE_BYTES: dict[str, bytes] = {"data": b"abc"} + +# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。 +_CALLBACK_SEQ: dict[str, int] = {"n": 0} + + +@pytest.fixture +def db_session(app): + """复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +@pytest.fixture(autouse=True) +def _reset_report_handlers(): + """每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。 + + [断言意图] 缺处理器用例必须跑在"干净注册表"上——否则前序用例注册的 + inbound 处理函数会让 404 用例假绿。 + """ + from app.services.freight_rpa.reports import dispatch as dispatch_module + + saved = dict(dispatch_module._REPORT_HANDLERS) + dispatch_module._REPORT_HANDLERS.clear() + yield + dispatch_module._REPORT_HANDLERS.clear() + dispatch_module._REPORT_HANDLERS.update(saved) + + +@pytest.fixture(autouse=True) +def _fake_archive_io(monkeypatch): + """替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。 + + 核心逻辑:与旧回调测试同一 monkeypatch 姿态(patch report_archive 模块属性), + 使 ingest 的 success 分支可脱离真实文件系统与对象存储走完全程。 + """ + from app.services.freight_rpa.inbound import report_archive + + monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: _FAKE_FILE_BYTES["data"]) + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + + +def _next_callback_id(prefix: str) -> str: + """生成跨用例唯一的 callback_id(满足 unit run 唯一约束)。""" + _CALLBACK_SEQ["n"] += 1 + return f"{prefix}-{_CALLBACK_SEQ['n']}" + + +def _awaiting_unit(*, source_code: str = "DSV"): + """构造一个处于 awaiting_rpa 的 inbound 执行单元(挂种子站点满足外键)。 + + 核心逻辑:source_code 列允许测试值(如 "DSV"),source_id 外键挂种子站点 + DSV360_AWSDU——与 test_report_queries.py 的 _inbound_file 同构。 + """ + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + return FreightRpaInboundUnitRun( + source_id=source.id, + source_code=source_code, + connector_type="dbs", + callback_id=_next_callback_id("report-fact-dispatch"), + status="awaiting_rpa", + config_snapshot_json={}, + ) + + +def _success_payload(unit, *, sha256_file: bytes = b"abc") -> dict: + """构造通过 schema 校验的 success 回调载荷;sha256_file 即被模拟读取的 xlsx 字节。""" + _FAKE_FILE_BYTES["data"] = sha256_file + return { + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit.callback_id, + "status": "success", + "file_path": f"receipt_{unit.id or 'x'}.xlsx", + "original_filename": "receipt.xlsx", + "sha256": hashlib.sha256(sha256_file).hexdigest(), + } + + +def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch): + """处理函数失败绝不回滚已 commit 的归档文件行,异常原样外抛(不吞)。""" + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + + def boom(fact: ReportFact) -> None: + raise RuntimeError("handler down") + + register_report_handler("inbound", boom) + with pytest.raises(RuntimeError, match="handler down"): + ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc")) + # [断言意图] 异常外抛但文件行已提交:count==1 锁死「先 commit 再投递」顺序。 + assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + + +def test_second_delivery_does_not_insert_another_file(app, db_session): + """同一回调重放不插第二行文件,事实仍重复投递(同一 file_id、ok=True)。""" + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + + seen: list[ReportFact] = [] + register_report_handler("inbound", seen.append) + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + payload = _success_payload(unit, sha256_file=b"abc") + ingest_inbound_callback(payload) + ingest_inbound_callback(payload) + assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + # [断言意图] 幂等重放仍两次投递 ok=True 事实(同一 file_id),供处理函数重试。 + assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id] + assert all(fact.ok is True for fact in seen) + + +def test_missing_handler_raises_sink_not_registered(app, db_session): + """kind 未注册处理函数 → 404 FREIGHT_RPA.SINK_NOT_REGISTERED,文件行已提交。""" + from app.core.errors import AppError + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + with pytest.raises(AppError) as exc: + ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc")) + assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED" + # [断言意图] 分发失败不回滚归档:文件行保留,Worker 重试整笔回调即可补投递。 + assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + + +def test_empty_callback_dispatches_failure_fact(app, db_session): + """empty 终态同样先 commit 再投递 ok=False 事实(error_code 随载荷落库值)。""" + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + + seen: list[ReportFact] = [] + register_report_handler("inbound", seen.append) + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + result = ingest_inbound_callback( + { + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit.callback_id, + "status": "empty", + "error_code": "no_receipt_data", + "error_message": "no_receipt_data", + } + ) + assert result["status"] == "empty" + assert len(seen) == 1 + fact = seen[0] + # [断言意图] empty 是合法业务结果 → ok=False + error_code=no_receipt_data 的事实。 + assert fact.report_kind == "inbound" + assert fact.source_code == "DSV" + assert fact.ok is False + assert fact.file_id is None + assert fact.sha256 is None + assert fact.error_code == "no_receipt_data" + assert fact.error_message == "no_receipt_data" diff --git a/backend/tests/services/freight_rpa/test_report_queries.py b/backend/tests/services/freight_rpa/test_report_queries.py new file mode 100644 index 00000000..e337a274 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_report_queries.py @@ -0,0 +1,282 @@ +"""tests/services/freight_rpa/test_report_queries.py + +用途:锁定阶段 B Task 3——freight_rpa.reports 只读查询模块的行为契约。 +依赖:pytest、app fixture(tests/conftest)、app.core.errors、 + app.services.freight_rpa.reports(待实现模块)。 +逻辑:覆盖(1)latest_usable_inbound_file 的可用门禁——未删除、当天 + (Asia/Shanghai 业务日)抓取、未过期、最新优先;(2)require_report_kind 的 + 白名单校验;(3)站点/在手/入站配置只读视图;(4)按 storage_key 读文件 + 字节 + 缺文件 NotFoundError;(5)解析失败三列的标记与清除(仅 flush + 不 commit)。(6)业务日窗口内外的定向拒收/放行。 + 时间口径:查询的 now 参数显式传 naive UTC;文件 created_at 也按 naive UTC + 存入,两者用同一业务日窗口锚点(now=2026-10-05 12:00 UTC → 上海业务日 + 10-05,UTC 窗口 [10-04 16:00, 10-05 16:00))。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app.core.errors import NotFoundError, ValidationError +from app.services.freight_rpa.reports import ( + clear_inbound_parse_failure, + get_inbound_config, + get_onhand_config, + get_site, + latest_usable_inbound_file, + mark_inbound_parse_failure, + read_inbound_file_bytes, + require_report_kind, +) + +SEED_SOURCE_CODE = "DSV360_AWSDU" + +# 业务日窗口锚点(naive UTC):2026-10-05 12:00 UTC = 上海 10-05 20:00, +# 对应业务日 2026-10-05 的 UTC 存储窗口 [10-04 16:00, 10-05 16:00)。 +FROZEN_NOW = datetime(2026, 10, 5, 12, 0, 0) + + +@pytest.fixture +def db_session(app): + """复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +def _inbound_file(*, source_code: str, sha256: str, created_at: datetime, **overrides): + """构造一条挂在指定 source_code 执行单元下的入站归档文件(含 unit run)。 + + 核心逻辑:外键要求文件必须挂在 FreightRpaInboundUnitRun 下,unit run 再挂 + 种子站点(DSV360_AWSDU);source_code 写进 unit run 列(非外键,允许 "DSV" + 等测试值),便于验证查询按 unit run 的 source_code 过滤。 + """ + from app import db + from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + unit = FreightRpaInboundUnitRun( + source_id=source.id, + source_code=source_code, + connector_type="dbs", + callback_id=f"test-callback:{source_code}:{sha256[:8]}", + status="success", + config_snapshot_json={}, + **overrides, + ) + db.session.add(unit) + db.session.flush() + report_file = FreightRpaInboundReportFile( + unit_run_id=unit.id, + storage_provider="minio", + storage_bucket="test", + storage_key=f"freight_rpa/inbound/{source_code}/{sha256[:12]}.xlsx", + original_filename=f"{sha256[:8]}.xlsx", + file_size=16, + sha256=sha256, + created_at=created_at, + ) + db.session.add(report_file) + return report_file + + +def test_latest_usable_inbound_file_returns_newest(app, db_session): + """同一业务日窗口内的两份可用文件 → 按 created_at 倒序取最新一份。 + + [断言意图] 两份文件的 created_at 均落在 FROZEN_NOW 的业务日 UTC 窗口 + ([10-04 16:00, 10-05 16:00))内,证明「最新优先」在当天门禁内生效, + 而不是因为当天新鲜度被丢掉才命中。 + """ + older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 4, 18, 0, 0)) + newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0)) + db_session.add_all([older, newer]) + db_session.commit() + view = latest_usable_inbound_file("DSV", now=FROZEN_NOW) + assert view is not None + assert view.file_id == newer.id + assert view.sha256 == "b" * 64 + + +def test_latest_usable_inbound_file_rejects_out_of_business_day(app, db_session): + """「当天(Asia/Shanghai 业务日)抓取」是可用门禁的一部分:隔日文件不可用。 + + [断言意图] 同一份文件(expries 为空、未删除)在非当天业务日查 → None; + 把判定时刻推回文件被抓取的那个业务日 → 又可用;差异只能来自当天窗口, + 锁死修复轮补回的新鲜度条件。 + """ + report = _inbound_file(source_code="STL", sha256="0" * 64, created_at=datetime(2026, 10, 3, 10, 0, 0)) + db_session.commit() + + # FROZEN_NOW(业务日 10-05)下,10-03 抓取的文件是隔日旧文件 → 不可用。 + assert latest_usable_inbound_file("STL", now=FROZEN_NOW) is None + # 业务日 10-03 的窗口为 UTC [10-02 16:00, 10-03 16:00):10-03 10:00 UTC 在窗口内 → 可用。 + in_day_now = datetime(2026, 10, 3, 12, 0, 0) + view = latest_usable_inbound_file("STL", now=in_day_now) + assert view is not None + assert view.file_id == report.id + + +def test_latest_usable_inbound_file_skips_deleted_and_expired(app, db_session): + """已删除/已过期的文件不得被当作可用文件返回;同来源保留最新可用一份。""" + # [断言意图] 三份文件都在 FROZEN_NOW 的业务日窗口内,且已删除/已过期两份 + # 更新——若门禁失效,“最新优先”会先命中它们;断言只能命中唯一的可用文件。 + usable = _inbound_file(source_code="CRN", sha256="c" * 64, created_at=datetime(2026, 10, 4, 20, 0, 0)) + deleted = _inbound_file(source_code="CRN", sha256="d" * 64, created_at=datetime(2026, 10, 5, 1, 0, 0)) + deleted.archive_deleted_at = datetime(2026, 10, 5, 5, 0, 0) + expired = _inbound_file(source_code="CRN", sha256="e" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0)) + # 保留期早于判定时刻(仍未被清理任务删除)→ 过期不可用。 + expired.archive_expires_at = FROZEN_NOW - timedelta(hours=1) + db_session.add_all([usable, deleted, expired]) + db_session.commit() + + view = latest_usable_inbound_file("CRN", now=FROZEN_NOW) + assert view is not None + assert view.sha256 == "c" * 64 + assert view.source_code == "CRN" + assert view.storage_key.endswith(f"{'c' * 12}.xlsx") + assert view.original_filename == f"{'c' * 8}.xlsx" + assert view.created_at == datetime(2026, 10, 4, 20, 0, 0) + + +def test_latest_usable_inbound_file_no_match_returns_none(app, db_session): + """来源无任何归档文件(或全部不可用)时返回 None,不抛异常。""" + assert latest_usable_inbound_file("NOPE") is None + + +def test_report_kind_rejects_shipment(): + with pytest.raises(ValidationError): + require_report_kind("shipment") + assert require_report_kind("outbound") == "outbound" + + +def test_get_site_returns_view_of_seeded_source(app): + """get_site 返回站点连接与模板绑定的只读视图;未知来源返回 None。""" + view = get_site(SEED_SOURCE_CODE) + assert view is not None + assert view.source_code == SEED_SOURCE_CODE + assert view.display_name == "DBS Dublin AWSDU" + assert view.connector_type == "dbs" + assert view.excel_template_id is not None + assert view.enabled is True + assert get_site("NOPE") is None + + +def test_get_onhand_config_returns_report_definition(app): + """get_onhand_config 返回 s18 起挂在配置行上的报表路径/查询条件/解析方案。""" + config = get_onhand_config(SEED_SOURCE_CODE) + assert config is not None + assert config.report_path_json.get("program_group") == "Bison" + assert config.query_parameters_json == [ + {"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "required": True, "select_all": False}, + ] + assert config.parsing_profile_id is not None + # [断言意图] 未知来源与存在但未配置报表的来源都必须返回 None(fail-closed)。 + assert get_onhand_config("NOPE") is None + + +def test_get_inbound_config_returns_none_without_config_row(app): + """种子站点没有入站报表配置行 → get_inbound_config 返回 None。""" + from app import db + from app.models import FreightRpaInboundReportConfig, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + assert get_inbound_config(SEED_SOURCE_CODE) is None + # [断言意图] 补一条配置行后即可读出三个字段(与在手配置视图同构)。 + db.session.add(FreightRpaInboundReportConfig( + source=source, + report_path_json={"program_group": "Bison", "report_name": "Receipt"}, + query_parameters_json=[{"name": "Date", "mode": "range"}], + parsing_profile_id=None, + )) + db.session.commit() + config = get_inbound_config(SEED_SOURCE_CODE) + assert config is not None + assert config.report_path_json["report_name"] == "Receipt" + assert config.query_parameters_json == [{"name": "Date", "mode": "range"}] + assert config.parsing_profile_id is None + + +def test_read_inbound_file_bytes_reads_by_storage_key(app, db_session, monkeypatch): + """read_inbound_file_bytes 按文件的 storage_key 调 file_asset_storage 读取。""" + from app.services.freight_rpa.reports import queries as queries_module + + report_file = _inbound_file(source_code="DSV", sha256="f" * 64, created_at=datetime(2026, 10, 6)) + db_session.commit() + + captured: dict[str, bytes] = {} + + def fake_get_bytes(storage_key): + captured["key"] = storage_key + return b"xlsx-bytes" + + monkeypatch.setattr(queries_module.file_asset_storage, "get_bytes", fake_get_bytes) + + assert read_inbound_file_bytes(report_file.id) == b"xlsx-bytes" + assert captured["key"] == report_file.storage_key + + +def test_read_inbound_file_bytes_missing_file_raises(app): + """文件 id 不存在 → NotFoundError(fail-closed,不吞 404)。""" + with pytest.raises(NotFoundError): + read_inbound_file_bytes(999999) + + +def test_mark_and_clear_inbound_parse_failure_roundtrip(app, db_session): + """mark 写入三列并 flush(不 commit 由调用方决定);clear 清空恢复。""" + from datetime import timedelta + + report_file = _inbound_file(source_code="DSV", sha256="9" * 64, created_at=datetime(2026, 10, 7)) + db_session.commit() + file_id = report_file.id + + mark_inbound_parse_failure( + file_id, + error_code="X" * 80, + error_message="m" * 2500, + ) + # [断言意图] 只 flush 不 commit——新开的同一事务查询立即可见,且列宽截断生效。 + from app import db + from app.models import FreightRpaInboundReportFile + + marked = db.session.get(FreightRpaInboundReportFile, file_id) + assert marked.parse_failed_at is not None + assert marked.parse_failed_at > datetime.utcnow() - timedelta(minutes=1) + assert marked.parse_error_code == "X" * 64 + assert marked.parse_error_message == "m" * 2000 + db_session.commit() + + clear_inbound_parse_failure(file_id) + cleared = db.session.get(FreightRpaInboundReportFile, file_id) + assert cleared.parse_failed_at is None + assert cleared.parse_error_code is None + assert cleared.parse_error_message is None + db_session.commit() + + +def test_mark_inbound_parse_failure_missing_file_raises(app): + """文件 id 不存在 → NotFoundError,与其他按 id 操作一致。""" + with pytest.raises(NotFoundError): + mark_inbound_parse_failure(999999, error_code="E", error_message="m") + + +def test_import_boundary_no_business_module_imports(): + """本模块(发货与调拨读报表唯一入口)不得 import shipping_notice / in_transit_transfer。""" + import ast + from pathlib import Path + + pkg = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" / "reports" + assert pkg.exists() + for py in pkg.rglob("*.py"): + tree = ast.parse(py.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + mods = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom) and node.module: + mods = [node.module] + else: + continue + for mod in mods: + assert not mod.startswith("app.services.shipping_notice"), f"{py.name}: {mod}" + assert not mod.startswith("app.services.in_transit_transfer"), f"{py.name}: {mod}" \ No newline at end of file diff --git a/backend/tests/services/freight_rpa/test_upload_trigger_contract.py b/backend/tests/services/freight_rpa/test_upload_trigger_contract.py new file mode 100644 index 00000000..cf6fc2f6 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_upload_trigger_contract.py @@ -0,0 +1,59 @@ +""" +backend/tests/services/freight_rpa/test_upload_trigger_contract.py + +用途:锁死 upload trigger 写入契约——action 与心跳能力 freight_rpa_upload 对齐,schema 为 freight_rpa.upload.v1。 +依赖:app.services.freight_rpa.upload.trigger_io、Flask app fixture。 +逻辑:断言模块常量;write_upload_trigger 落盘后 JSON 的 action/schema_version 与常量一致。 +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY +from app.services.freight_rpa.upload import trigger_io + + +def test_upload_trigger_constants_align_with_heartbeat_capability(): + """upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。""" + assert trigger_io.SCHEMA == "freight_rpa.upload.v1" + assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload" + assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY + assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD + assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD + + +def test_write_upload_trigger_persists_freight_upload_action(app, tmp_path): + """落盘 trigger JSON 的 action/schema_version 须与模块常量一致。""" + export_file = tmp_path / "queue_src" / "SN-001.xlsx" + export_file.parent.mkdir(parents=True) + export_file.write_bytes(b"fake-xlsx") + + upload_queue = tmp_path / "upload_queue" + upload_trigger = tmp_path / "upload_triggers" + upload_queue.mkdir() + upload_trigger.mkdir() + + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue) + app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger) + queue_path, trigger_path, callback_id = trigger_io.write_upload_trigger( + "TASK-UP-1", + str(export_file), + attempt_id=10, + artifact_id=20, + connector_type="dbs", + callback_id="upload-cb-1", + ) + + assert queue_path + assert trigger_path + assert callback_id == "upload-cb-1" + + payload = json.loads(Path(trigger_path).read_text(encoding="utf-8")) + # [断言意图] Worker 侧不校验 action 字面量,但双侧契约文档须与心跳能力 freight_rpa_upload 对齐。 + assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD + assert payload["schema_version"] == trigger_io.SCHEMA + assert payload["action"] == "freight_rpa_upload" + assert payload["schema_version"] == "freight_rpa.upload.v1" diff --git a/backend/tests/services/freight_rpa/test_worker_heartbeat.py b/backend/tests/services/freight_rpa/test_worker_heartbeat.py index de7e76c3..f8bcf49e 100644 --- a/backend/tests/services/freight_rpa/test_worker_heartbeat.py +++ b/backend/tests/services/freight_rpa/test_worker_heartbeat.py @@ -15,7 +15,7 @@ import pytest from app.core.errors import ServiceUnavailableError from app.services.freight_rpa.common.worker_heartbeat import ( - FREIGHT_UPLOAD_CAPABILITY, + FREIGHT_RPA_UPLOAD_CAPABILITY, ONHAND_EXPORT_CAPABILITY, INBOUND_EXPORT_CAPABILITY, RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE, @@ -306,7 +306,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp """排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。""" from app import db from app.models import ScheduleRun, ScheduleTask, User - from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule + from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module from app.services.freight_rpa.common.worker_heartbeat import ( reset_rpa_worker_heartbeat_state_for_tests, @@ -337,7 +337,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp db.session.add(run) db.session.commit() - total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run) + total, success, failed, skipped, _details, errors, logs = run_freight_rpa_onhand_schedule(task, run) assert total >= 1 assert success == 0 assert failed >= 1 @@ -461,20 +461,20 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app, ) ) result = check_freight_upload_rpa_ready() - # 关键断言:缺少 freight_upload 能力必须阻断自动上传。 + # 关键断言:缺少 freight_rpa_upload 能力必须阻断自动上传。 assert result.ready is False - assert any("missing_freight_upload_capability" in reason for reason in result.reasons) + assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons) def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path): - """Worker 声明 freight_upload 且目录/凭据齐全时应 ready。""" + """Worker 声明 freight_rpa_upload 且目录/凭据齐全时应 ready。""" upload_trigger = _enable_freight_upload_checks(app, tmp_path) with app.app_context(): record_rpa_worker_heartbeat( _heartbeat_payload( trigger_dir=str(upload_trigger), shared_scope_id="hxops-rpa-test-data", - capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY], + capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY], ) ) result = check_freight_upload_rpa_ready() diff --git a/backend/tests/services/in_transit_transfer/factories.py b/backend/tests/services/in_transit_transfer/factories.py index e89037e8..913ba00e 100644 --- a/backend/tests/services/in_transit_transfer/factories.py +++ b/backend/tests/services/in_transit_transfer/factories.py @@ -129,8 +129,9 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = """建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。 用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身 - parsing_profile(在手口径)按约束置最小占位行,真实重建规则挂 - ShippingReceiptReportConfig.parsing_profile_id(与运行期口径一致)。 + 在手解析绑定(在手口径)按约束置最小占位配置行(s18 起归 + FreightRpaOnhandReportConfig),真实重建规则挂 + FreightRpaInboundReportConfig.parsing_profile_id(与运行期口径一致)。 Args: source_code: 来源实例编码。 @@ -140,29 +141,30 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = sheet_name / header_row_index: definition_json 结构参数。 status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。 Returns: - (ShippingInventorySource, ShippingInventoryParsingProfile) 元组。 + (FreightRpaSource, FreightRpaParsingProfile) 元组。 """ from app import db from app.models import ( ShippingExcelTemplate, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingRpaProfile, - ShippingReceiptReportConfig, + FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, + FreightRpaProfile, + FreightRpaInboundReportConfig, ) - source = ShippingInventorySource.query.filter_by(source_code=source_code).first() + source = FreightRpaSource.query.filter_by(source_code=source_code).first() if source is not None: - config = source.receipt_report_config + config = source.inbound_report_config return source, (config.parsing_profile if config else None) resolved_code = profile_code or f"MV_{source_code}" - onhand = ShippingInventoryParsingProfile( + onhand = FreightRpaParsingProfile( purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code, version=1, status="published", file_format="xlsx", definition_json={}, structure_definition_json={}, ) - profile = ShippingInventoryParsingProfile( + profile = FreightRpaParsingProfile( purpose="inbound", profile_code=resolved_code, display_name=resolved_code, version=version, status=status, file_format="xlsx", definition_json={ @@ -172,7 +174,7 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = }, structure_definition_json={}, ) - rpa = ShippingRpaProfile( + rpa = FreightRpaProfile( profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs", login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"}, ) @@ -182,15 +184,20 @@ def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx", file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64, ) - source = ShippingInventorySource( + source = FreightRpaSource( source_code=source_code, display_name=source_code, connector_type="dbs", - rpa_profile=rpa, parsing_profile=onhand, excel_template=template, + rpa_profile=rpa, excel_template=template, warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True, ) db.session.add_all([onhand, profile, rpa, template, source]) db.session.flush() - db.session.add(ShippingReceiptReportConfig( - inventory_source_id=source.id, parsing_profile_id=profile.id)) + # s18 起在手解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。 + db.session.add(FreightRpaOnhandReportConfig( + source_id=source.id, parsing_profile_id=onhand.id, + report_path_json={}, query_parameters_json=[], + )) + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, parsing_profile_id=profile.id)) db.session.commit() return source, profile @@ -213,20 +220,20 @@ def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at: archive_deleted_at: 清理时间;None=未清理。 callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。 Returns: - 已入库的 ShippingReceiptReportFile。 + 已入库的 FreightRpaInboundReportFile。 """ from app import db - from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun - unit = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source.source_code, + unit = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type=source.connector_type, callback_id=callback_id or f"cb-{sha[:12]}", status="success", config_snapshot_json={}, ) db.session.add(unit) db.session.flush() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx", file_size=16, sha256=sha, created_at=created_at, diff --git a/backend/tests/services/in_transit_transfer/test_evidence_sync.py b/backend/tests/services/in_transit_transfer/test_evidence_sync.py index 3cbb89fa..0e71c1f6 100644 --- a/backend/tests/services/in_transit_transfer/test_evidence_sync.py +++ b/backend/tests/services/in_transit_transfer/test_evidence_sync.py @@ -57,24 +57,24 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str): sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。 callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。 Returns: - 已入库的 ShippingReceiptReportFile。 + 已入库的 FreightRpaInboundReportFile。 """ from app import db from app.models import ( - ShippingInventorySource, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + FreightRpaSource, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one() - unit = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source_code, + source = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source_code, connector_type="dbs", callback_id=callback_id, status="success", config_snapshot_json={}, ) db.session.add(unit) db.session.flush() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", storage_key=f"shipping/receipt/{callback_id}.xlsx", original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha, @@ -262,7 +262,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m # 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed; # 同步数据已回滚(桥隔离保持)。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile from app.services.in_transit_transfer import evidence_sync from app.services.in_transit_transfer.source_file_status import resolve_source_file_status @@ -282,7 +282,7 @@ def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m assert ok is False # [断言意图] 同步失败被吞(桥隔离) assert TransferMovementLedger.query.count() == 0 # [断言意图] 坏行未落档(同步数据已回滚) db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读 - row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one() + row = db.session.query(FreightRpaInboundReportFile).filter_by(id=report.id).one() assert row.parse_failed_at is not None # [断言意图] 失败事实已落库 assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID" assert row.parse_error_message diff --git a/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py b/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py new file mode 100644 index 00000000..0c447916 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py @@ -0,0 +1,320 @@ +"""tests/services/in_transit_transfer/test_inbound_report_handler.py + +用途:阶段 B Task 7——inbound 报表事实处理函数(handle_inbound_report)的契约测试: + 未注册不推进、处理函数先失败后成功只推进一次且文件只留一行、无等待任务时回调成功、 + 同来源两单元分属两排程 run 时收口只打「本次回调收尾的单元」的 run(修复轮)。 +依赖:app(SQLite)fixture、freight_rpa.reports.dispatch(注册表)、 + freight_rpa.inbound.report_archive.ingest_inbound_callback(归档+投递入口)、 + in_transit_transfer.inbound_callback_bridge / TransferSourceJob(调拨侧事实)。 +逻辑:复刻 test_report_fact_dispatch 的注册表隔离与归档 IO 替身——组合根 + (create_app→register_inbound_sinks)启动即注册 handle_inbound_report, + 未注册用例必须先清空注册表,否则 404 断言假绿;success 归档走替身 IO + (drop 根读取返回注入字节、MinIO 上传 no-op),不依赖真实文件系统; + 收口定位用例构造两个 awaiting 排程 run(各挂一个同来源单元), + 对旧单元回调后断言只有旧 run 被收口、新 run 保持等待。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + + +@pytest.fixture +def db_session(app): + """复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +@pytest.fixture(autouse=True) +def _reset_report_handlers(): + """每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。 + + [断言意图] 未注册用例必须跑在"干净注册表"上——组合根启动已注册 + handle_inbound_report,不清空会让 FREIGHT_RPA.SINK_NOT_REGISTERED 断言假绿。 + """ + from app.services.freight_rpa.reports import dispatch as dispatch_module + + saved = dict(dispatch_module._REPORT_HANDLERS) + dispatch_module._REPORT_HANDLERS.clear() + yield + dispatch_module._REPORT_HANDLERS.clear() + dispatch_module._REPORT_HANDLERS.update(saved) + + +@pytest.fixture(autouse=True) +def _fake_archive_io(monkeypatch): + """替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。 + + 核心逻辑:与 test_report_fact_dispatch 同一 monkeypatch 姿态(patch + report_archive 模块属性),使 success 归档分支脱离真实文件系统与对象存储。 + """ + from app.services.freight_rpa.inbound import report_archive + + monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: b"handler-bytes") + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + + +# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。 +_CALLBACK_SEQ: dict[str, int] = {"n": 0} + + +def _next_callback_id() -> str: + """生成跨用例唯一的 callback_id(unit run 唯一约束)。""" + _CALLBACK_SEQ["n"] += 1 + return f"inbound-handler-{_CALLBACK_SEQ['n']}" + + +def _waiting_job(source_code: str): + """构造一个未落库的 waiting_rpa_callback 来源任务(先建 TransferRun 满足外键)。 + + 核心逻辑:TransferRun 只 add+flush(拿 run_id);TransferSourceJob 由调用方 + add+commit——与用例体里的 db_session.add(job) 契约一致。 + """ + from app import db + from app.models import TransferRun, TransferSourceJob + + run = TransferRun( + run_no=f"RUN-HANDLER-{_next_callback_id()}", + business_date="2026-09-17", + status="preparing_files", + trigger_type="manual", + ) + db.session.add(run) + db.session.flush() + return TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback") + + +def _success_payload_for(source_code: str) -> dict: + """构造一个挂种子站点的 awaiting 单元及其 success 回调载荷(可通过 schema 校验)。 + + 核心逻辑:source_code 列允许测试值(如 "DSV",与调拨任务匹配),source_id + 外键挂 conftest 种子站点 DSV360_AWSDU;替身 IO 注入字节与 sha256 对齐。 + """ + from app import db + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + + anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = FreightRpaInboundUnitRun( + source_id=anchor.id, + source_code=source_code, + connector_type="dbs", + callback_id=_next_callback_id(), + status="awaiting_rpa", + config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + data = b"handler-bytes" + return { + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit.callback_id, + "status": "success", + "file_path": f"receipt_{unit.id}.xlsx", + "original_filename": "receipt.xlsx", + "sha256": hashlib.sha256(data).hexdigest(), + } + + +def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session): + """未注册处理函数:归档 404 后调拨任务必须原地保持 waiting_rpa_callback。""" + from app.core.errors import AppError + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + + job = _waiting_job(source_code="DSV") + db_session.add(job) + db_session.commit() + # 不注册 handle_inbound_report + with pytest.raises(AppError) as exc: + ingest_inbound_callback(_success_payload_for("DSV")) + assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED" + db_session.refresh(job) + assert job.status == "waiting_rpa_callback" + + +def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch): + """处理函数先失败后成功:文件只留一行,调拨任务只推进一次到 file_ready。""" + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + job = _waiting_job(source_code="DSV") + db_session.add(job) + db_session.commit() + calls = {"n": 0} + + def flaky(fact: ReportFact) -> None: + calls["n"] += 1 + if calls["n"] == 1: + raise RuntimeError("once") + handle_inbound_report(fact) + + register_report_handler("inbound", flaky) + payload = _success_payload_for("DSV") + with pytest.raises(RuntimeError): + ingest_inbound_callback(payload) + ingest_inbound_callback(payload) + db_session.refresh(job) + assert job.status == "file_ready" + assert FreightRpaInboundReportFile.query.count() == 1 + + +def test_no_waiting_job_is_success(app, db_session): + """无等待中的调拨任务:处理函数照常成功返回,且不产生任何调拨来源任务行。""" + from app.models import TransferSourceJob + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + register_report_handler("inbound", handle_inbound_report) + ingest_inbound_callback(_success_payload_for("DSV")) + assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0 + + +def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True): + """构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。""" + from app.models import ScheduleRun, ScheduleTask + + task = ScheduleTask( + schedule_no=schedule_no, name=f'Receipt {schedule_no}', schedule_type='platform_job', + platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', + ) + db_session.add(task) + db_session.flush() + run = ScheduleRun( + run_no=run_no, schedule_task_id=task.id, status='running', total_count=1, + success_count=0, failed_count=0, skipped_count=0, + response_summary_json={'awaiting_receipt_rpa': awaiting}, + ) + db_session.add(run) + db_session.commit() + return run + + +def _unit_on_run(db_session, run, *, callback_id: str): + """在指定排程 run 下造一个挂种子站点的 awaiting 收料单元(source_code=DSV)。""" + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + + anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=anchor.id, source_code="DSV", + connector_type="dbs", callback_id=callback_id, + status="awaiting_rpa", config_snapshot_json={}, + ) + db_session.add(unit) + db_session.commit() + return unit + + +def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch): + """同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。 + + [断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run, + 本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。 + """ + from app.models import ScheduleRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file", + lambda _path: b"handler-bytes", + ) + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + register_report_handler("inbound", handle_inbound_report) + + run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-OLD", run_no="RUN-ONHAND-OLD") + run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-NEW", run_no="RUN-ONHAND-NEW") + unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-old") + _unit_on_run(db_session, run_new, callback_id="inbound-handler-new") + + ingest_inbound_callback({ + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit_old.callback_id, + "status": "success", + "file_path": "receipt_old.xlsx", + "original_filename": "receipt.xlsx", + "sha256": hashlib.sha256(b"handler-bytes").hexdigest(), + }) + + db_session.rollback() + db_session.expire_all() + # [断言意图] 本回调收尾的是旧单元:只有旧 run 被收口(全终态 → success)。 + refreshed_old = db_session.get(ScheduleRun, run_old.id) + assert refreshed_old.status == "success" + assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa") + # 新单元的 run 原样保持等待态——未被本次回调误收口。 + refreshed_new = db_session.get(ScheduleRun, run_new.id) + assert refreshed_new.status == "running" + assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True + + +def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch): + """同来源两单元、同失败错误文本、分属两 run:失败回调只收口本单元(unit_run_id)的 run。 + + [断言意图] 修复「按来源+终态+错误文本取最新单元」的错位:错误文本碰撞时旧回调 + 会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_receipt_rpa。 + """ + from datetime import datetime + + from app.models import ScheduleRun, FreightRpaInboundUnitRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file", + lambda _path: b"handler-bytes", + ) + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + register_report_handler("inbound", handle_inbound_report) + + run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-OLD", run_no="RUN-FAIL-OLD") + run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-NEW", run_no="RUN-FAIL-NEW") + unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-fail-old") + unit_new = _unit_on_run(db_session, run_new, callback_id="inbound-handler-fail-new") + # [RED 场景] 新单元已先以同错误文本终态失败落库——旧逻辑按 (来源, 终态, 错误文本) + # 取最新单元会命中新单元,把收口打到新 run。 + unit_new.status = "failed" + unit_new.error_code = "RPA_TEST_FAIL" + unit_new.error_message = "boom" + unit_new.finished_at = datetime.utcnow() + db_session.commit() + + result = ingest_inbound_callback({ + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit_old.callback_id, + "status": "failed", + "error_code": "RPA_TEST_FAIL", + "error_message": "boom", + }) + assert result["status"] == "failed" + + db_session.rollback() + db_session.expire_all() + # [断言意图] 只有旧单元的 run 被收口(唯一单元终态失败 → failed、awaiting 清除)。 + refreshed_old = db_session.get(ScheduleRun, run_old.id) + assert refreshed_old.status == "failed" + assert not (refreshed_old.response_summary_json or {}).get("awaiting_receipt_rpa") + refreshed_saved_old = db_session.get(FreightRpaInboundUnitRun, unit_old.id) + assert refreshed_saved_old.status == "failed" + assert refreshed_saved_old.error_code == "RPA_TEST_FAIL" + # 新单元的 run 原样保持等待态——未被本次回调误收口(新单元自身终态由其回调收口)。 + refreshed_new = db_session.get(ScheduleRun, run_new.id) + assert refreshed_new.status == "running" + assert (refreshed_new.response_summary_json or {}).get("awaiting_receipt_rpa") is True diff --git a/backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py b/backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py new file mode 100644 index 00000000..fd16c84a --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py @@ -0,0 +1,36 @@ +"""tests/services/in_transit_transfer/test_inbound_report_read_boundary.py + +用途:锁定阶段 B Task 4——in_transit_transfer 包不得引用 freight_rpa 报表模型 + (站点与报表文件/配置的读取一律改走 app.services.freight_rpa.reports + 只读入口,业务方只按 source_code / file_id 消费)。 +依赖:pathlib(纯文本扫描;无 app/DB fixture,秒级运行)。 +逻辑:对包内全部 .py 逐文件做 banned 字符串扫描(含注释/docstring——模型名 + 出现在任何位置都算引用面),命中即 fail 并按「文件名: 模型名」逐条列出, + 防止调拨域绕过只读入口直接 import 报表模型造成域间漂移。 +""" + +from __future__ import annotations + +from pathlib import Path + + +def test_in_transit_does_not_import_rpa_report_models(): + """in_transit_transfer 包内任何 .py 不得出现 freight_rpa 报表模型名。 + + banned 集合与计划 Task 4 冻结一致:入站归档文件、入站报表配置、库存站点、 + 在手报表配置四类模型自本任务起归 freight_rpa 域读写;调拨域(含注释与 + docstring)不得再引用其类名——命中即边界破坏,须收敛到 + freight_rpa.reports.queries 的只读函数。 + """ + root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer" + banned = ("FreightRpaInboundReportFile", "FreightRpaInboundReportConfig", + "FreightRpaSource", "FreightRpaOnhandReportConfig") + hits = [] + for path in root.rglob("*.py"): + text = path.read_text(encoding="utf-8") + for name in banned: + if name in text: + hits.append(f"{path.name}: {name}") + # [断言意图] hits 必须为空:任一命中都意味着调拨域仍在直接引用 + # freight_rpa 报表模型(import、类型标注或文档残句),边界未闭合。 + assert hits == [] \ No newline at end of file diff --git a/backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py b/backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py index 0a85c69a..99698cc6 100644 --- a/backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py @@ -1,10 +1,10 @@ """真实收料 RPA 触发服务测试。 用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit - 并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷); + 并调用写者;触发先落 FreightRpaInboundUnitRun(awaiting_rpa、真实 unit_run_id 进载荷); 配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。 依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、 - 既有测试种子(ShippingRpaProfile/ShippingInventorySource)。 + 既有测试种子(FreightRpaProfile/FreightRpaSource)。 逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False; 批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批, parse_failed 先本地重解析不触发 RPA)。 @@ -14,7 +14,7 @@ from __future__ import annotations import pytest -from app.models import ShippingInventorySource, ShippingReceiptReportConfig +from app.models import FreightRpaSource, FreightRpaInboundReportConfig from app.services.in_transit_transfer.inbound_trigger_service import ( trigger_inbound_rpa, trigger_inbound_rpa_batch, @@ -24,10 +24,10 @@ from app.services.in_transit_transfer.inbound_trigger_service import ( @pytest.fixture def receipt_source(): """复用种子来源并为其创建收料配置。""" - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() assert source is not None - config = ShippingReceiptReportConfig( - inventory_source_id=source.id, + config = FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}], ) @@ -67,7 +67,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source): def test_trigger_inbound_rpa_disabled_source_fails_closed(app): """来源停用 → ok=False,不写 trigger。""" - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() source.enabled = False from app import db @@ -84,9 +84,9 @@ def test_trigger_inbound_rpa_missing_config_fails_closed(app): def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source): - """触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。""" + """触发必须先落 FreightRpaInboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。""" from app import db - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun captured: dict = {} @@ -101,22 +101,22 @@ def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receip reason="transfer_retry_inbound", writer=fake_writer, ) assert outcome["ok"] is True - unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one() + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one() assert unit.status == "awaiting_rpa" # [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL—— # PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。 assert unit.schedule_run_id is None - assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True + assert FreightRpaInboundUnitRun.__table__.columns['schedule_run_id'].nullable is True assert captured["units"][0]["unit_run_id"] == unit.id assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id -def _bind_published_inbound_profile(config: ShippingReceiptReportConfig) -> None: +def _bind_published_inbound_profile(config: FreightRpaInboundReportConfig) -> None: """给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。""" from app import db - from app.models import ShippingInventoryParsingProfile + from app.models import FreightRpaParsingProfile - profile = ShippingInventoryParsingProfile( + profile = FreightRpaParsingProfile( purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则', version=1, status='published', file_format='xlsx', definition_json={'sheet_name': None, 'header_row_index': 1, @@ -135,8 +135,8 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p from app.services.in_transit_transfer.deps import _DefaultRpaTrigger with app.app_context(): - config = ShippingReceiptReportConfig.query.filter_by( - inventory_source_id=receipt_source.id).one() + config = FreightRpaInboundReportConfig.query.filter_by( + source_id=receipt_source.id).one() _bind_published_inbound_profile(config) monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path)) @@ -165,15 +165,15 @@ def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_ def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source): """trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun outcome = trigger_inbound_rpa( source_code=receipt_source.source_code, business_date="2026-09-17", reason="transfer_retry_inbound", writer=lambda *a, **k: None, ) assert outcome["ok"] is False - unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by( - ShippingReceiptRpaUnitRun.id.desc()).first() + unit = FreightRpaInboundUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by( + FreightRpaInboundUnitRun.id.desc()).first() assert unit.status == "failed" assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE" @@ -185,28 +185,35 @@ def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, rec @pytest.fixture def second_receipt_source(app): - """再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定 - 解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。""" + """再造一个启用来源 + 收料配置(批量用例需要多来源);s18 起启用态要求 + Excel 模板绑定(ck_freight_rpa_sources_enabled_template),解析绑定复用种子源配置行。""" from app import db - from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig + from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaInboundReportConfig - seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() - profile = ShippingRpaProfile( + seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + profile = FreightRpaProfile( profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs', login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'}, ) - source = ShippingInventorySource( + source = FreightRpaSource( source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs', rpa_profile=profile, - parsing_profile=seed.parsing_profile, excel_template=seed.excel_template, + excel_template=seed.excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG', - report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, enabled=True, ) + # s18 起在手解析绑定/报表路径归配置行,复用种子源绑定形态。 + seed_config = seed.onhand_report_config + FreightRpaOnhandReportConfig( + source=source, + parsing_profile=seed_config.parsing_profile if seed_config is not None else None, + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + query_parameters_json=[], + ) db.session.add_all([profile, source]) db.session.flush() # 先取 source.id(新建对象 flush 前无主键) - config = ShippingReceiptReportConfig( - inventory_source_id=source.id, + config = FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, query_parameters_json=[], ) @@ -217,7 +224,7 @@ def second_receipt_source(app): def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source): """多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun calls: list = [] @@ -238,7 +245,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt # 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。 callback_ids = {u['callback_id'] for u in calls[0]['units']} assert len(callback_ids) == 2 - rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_( + rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_( ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() assert {row.status for row in rows} == {'awaiting_rpa'} assert all(row.schedule_run_id is None for row in rows) @@ -278,7 +285,7 @@ def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app): def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source): """trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun outcome = trigger_inbound_rpa_batch( source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09', @@ -286,7 +293,7 @@ def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, rece ) assert outcome['ok'] is False and outcome['triggered'] is False assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE' - rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_( + rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_( ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() assert {row.status for row in rows} == {'failed'} assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'} diff --git a/backend/tests/services/in_transit_transfer/test_route_resolver.py b/backend/tests/services/in_transit_transfer/test_route_resolver.py index 7f19d6ea..b0d99fd0 100644 --- a/backend/tests/services/in_transit_transfer/test_route_resolver.py +++ b/backend/tests/services/in_transit_transfer/test_route_resolver.py @@ -4,7 +4,7 @@ 拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码; inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配, 匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。 -依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。 +依赖:app fixture 种子站点、FreightRpaOnhandExternalMapping、DefaultRouteResolver。 逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。 """ @@ -13,18 +13,18 @@ from __future__ import annotations import pytest from app.extensions import db -from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource from app.services.in_transit_transfer.deps import DefaultRouteResolver from app.services.in_transit_transfer.matching_service import RouteNotResolvedError def _seed_mapping( - source: ShippingInventorySource, *, freight_warehouse_id: str | None, + source: FreightRpaSource, *, freight_warehouse_id: str | None, in_transit_warehouse_code: str = 'TZT-01', -) -> ShippingInventoryExternalMapping: +) -> FreightRpaOnhandExternalMapping: """在既有种子来源上挂一条启用映射。""" - mapping = ShippingInventoryExternalMapping( - inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id, + mapping = FreightRpaOnhandExternalMapping( + source_id=source.id, freight_warehouse_id=freight_warehouse_id, external_system_code='TOPGP', external_organization_code='TGHX', external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓', in_transit_warehouse_code=in_transit_warehouse_code, enabled=True, @@ -34,12 +34,13 @@ def _seed_mapping( return mapping -def _seed_inventory_match_source() -> ShippingInventorySource: +def _seed_inventory_match_source() -> FreightRpaSource: """以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。""" - template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - source = ShippingInventorySource( + template = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + # s18 起站点行不再承载 parsing_profile_id;路由解析只读外部映射,无需在手配置行。 + source = FreightRpaSource( source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane', - rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id, + rpa_profile_id=template.rpa_profile_id, excel_template_id=template.excel_template_id, warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True, ) @@ -51,7 +52,7 @@ def _seed_inventory_match_source() -> ShippingInventorySource: def test_fixed_source_uses_single_mapping_in_transit_code(app): """fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。""" with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() # 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。 _seed_mapping(source, freight_warehouse_id='TZR2') @@ -118,7 +119,7 @@ def test_inventory_match_fails_closed_without_any_match(app): def test_route_resolver_fails_closed_without_in_transit_code(app): """映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。""" with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() _seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='') with pytest.raises(RouteNotResolvedError): diff --git a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py index 4d6992e2..65018ff9 100644 --- a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py +++ b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py @@ -46,12 +46,12 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool): """创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。""" from app.models import ( ShippingExcelTemplate, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingRpaProfile, + FreightRpaParsingProfile, + FreightRpaSource, + FreightRpaProfile, ) - profile = ShippingRpaProfile( + profile = FreightRpaProfile( profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane", login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"}, ) @@ -62,7 +62,7 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool): "rpa_profile_id": profile.id, "enabled": enabled, } if enabled: - parsing = ShippingInventoryParsingProfile( + parsing = FreightRpaParsingProfile( profile_code=f"PARSE_{source_code}", display_name=source_code, version=1, status="published", file_format="xlsx", definition_json={"field_mapping": {}, "match_keys": []}, @@ -79,27 +79,35 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool): db.session.add_all([parsing, template]) db.session.flush() source_kwargs.update( - parsing_profile_id=parsing.id, excel_template_id=template.id, + excel_template_id=template.id, warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1", ) else: source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None) - source = ShippingInventorySource(**source_kwargs) + source = FreightRpaSource(**source_kwargs) db.session.add(source) + if enabled: + # s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行; + # 经关系级联随站点一并入库。 + from app.models import FreightRpaOnhandReportConfig + FreightRpaOnhandReportConfig( + source=source, parsing_profile=parsing, + report_path_json={}, query_parameters_json=[], + ) return source def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db): """缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。""" - from app.models import ShippingReceiptReportConfig + from app.models import FreightRpaInboundReportConfig from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True) _make_receipt_source(transfer_db, "DBS_OFF", enabled=False) _make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True) transfer_db.session.flush() - transfer_db.session.add(ShippingReceiptReportConfig( - inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[], + transfer_db.session.add(FreightRpaInboundReportConfig( + source_id=enabled.id, report_path_json={}, query_parameters_json=[], )) transfer_db.session.commit() diff --git a/backend/tests/services/in_transit_transfer/test_source_file_status.py b/backend/tests/services/in_transit_transfer/test_source_file_status.py index 817961ba..c72c8a5b 100644 --- a/backend/tests/services/in_transit_transfer/test_source_file_status.py +++ b/backend/tests/services/in_transit_transfer/test_source_file_status.py @@ -3,7 +3,7 @@ 用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile), 按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败 标记 record/clear 的往返语义。调拨不维护独立抓取状态表。 -依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。 +依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。 逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed); 有进行中单元→fetching;最新单元失败终态→failed; 保留期已到或隔日旧文件(未清理)→expired;否则→none。 @@ -25,9 +25,9 @@ SOURCE_CODE = 'DSV360_AWSDU' def receipt_unit_run(): """构造一条收料执行单元(含排程/来源上下文)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun - source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one() + source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one() task = ScheduleTask( schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job', owner_user_id=1, cron_expr='0 8 * * *', job_params={}, @@ -37,8 +37,8 @@ def receipt_unit_run(): run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback') db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( - schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001', status='awaiting_rpa', config_snapshot_json={}, ) @@ -64,7 +64,7 @@ def test_running_unit_is_fetching(app, receipt_unit_run): def test_failed_latest_unit_is_failed(app, receipt_unit_run): """最新单元为失败终态且无文件 → failed。""" from app import db - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun receipt_unit_run.status = 'failed' db.session.commit() @@ -75,11 +75,11 @@ def test_failed_latest_unit_is_failed(app, receipt_unit_run): def test_report_file_is_ready(app, receipt_unit_run): """有收料归档文件 → ready,且带 file_no/sha256。""" from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' digest = hashlib.sha256(b'receipt workbook').hexdigest() - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx', file_size=16, sha256=digest, @@ -96,10 +96,10 @@ def test_expired_report_is_expired(app, receipt_unit_run): """保留期已到但清理任务未删 → expired,不得误报 ready。""" # [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx', file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(), @@ -115,17 +115,17 @@ def test_newer_valid_report_wins_over_expired(app, receipt_unit_run): """过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。""" # [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' digest = hashlib.sha256(b'fresh workbook').hexdigest() - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx', file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(), archive_expires_at=datetime.utcnow() - timedelta(days=1), )) - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx', file_size=16, sha256=digest, @@ -143,10 +143,10 @@ def test_stale_report_is_expired(app, receipt_unit_run): # [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算): # 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx', file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(), @@ -161,11 +161,11 @@ def test_stale_report_is_expired(app, receipt_unit_run): def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run): """可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。""" from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' digest = hashlib.sha256(b'bad workbook').hexdigest() - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx', file_size=16, sha256=digest, @@ -183,7 +183,7 @@ def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_uni def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run): """record 写入三列;clear 清空后投影回 ready。""" from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile from app.services.in_transit_transfer.source_file_status import ( clear_inbound_parse_failure, record_inbound_parse_failure, @@ -192,7 +192,7 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run): receipt_unit_run.status = 'success' digest = hashlib.sha256(b'roundtrip').hexdigest() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx', file_size=16, sha256=digest, @@ -228,14 +228,14 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app): 门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。 """ from app import db - from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units + from app.models import FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one() - db.session.add(ShippingReceiptRpaUnitRun( - schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code, + source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one() + db.session.add(FreightRpaInboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=source.source_code, connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa', config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5), )) diff --git a/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py b/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py index 88af2e54..e04f5618 100644 --- a/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py +++ b/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py @@ -4,7 +4,7 @@ 可空成分 NOT NULL + default ''/transfer_executed 默认 false/ source_file_id FK ON DELETE SET NULL(文件清理后档事实留存)。 依赖:app_ctx(根 conftest app fixture 上下文别名)、transfer_db(SQLite 内存库)、 - models/in_transit_transfer、models/shipping_receipt_report。 + models/in_transit_transfer、models/shipping_inbound_report。 逻辑:纯元数据断言(不落库)+ 真库往返(默认值/唯一约束/FK SET NULL 行为)。 """ @@ -15,7 +15,7 @@ from sqlalchemy import inspect, text from sqlalchemy.exc import IntegrityError from app import db -from app.models import ShippingReceiptReportFile +from app.models import FreightRpaInboundReportFile from app.models.in_transit_transfer import TransferMovementLedger # 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维):8 成分全部 NOT NULL, @@ -106,13 +106,13 @@ def test_scope_indexes_declared(app_ctx): def test_source_file_fk_on_delete_set_null(app_ctx): - """source_file_id FK 指向 shipping_receipt_report_files 且 ON DELETE SET NULL(档事实留存)。""" + """source_file_id FK 指向 freight_rpa_inbound_report_files 且 ON DELETE SET NULL(档事实留存)。""" cols = _column_map() fk = next( fk for fk in TransferMovementLedger.__table__.foreign_keys if fk.parent.name == 'source_file_id' ) - assert fk.target_fullname == 'shipping_receipt_report_files.id' + assert fk.target_fullname == 'freight_rpa_inbound_report_files.id' assert fk.ondelete == 'SET NULL' assert cols['source_file_id'].nullable is True @@ -164,17 +164,17 @@ def test_duplicate_natural_key_rejected(transfer_db): def test_source_file_relationship_and_delete_sets_null(app, transfer_db): """source_file relationship 可导航;来源文件删除后档记录留存且 source_file_id 置 NULL。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun - unit_run = ShippingReceiptRpaUnitRun( - inventory_source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行 + unit_run = FreightRpaInboundUnitRun( + source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行 source_code='DBS-AWSBI', connector_type='rpa', callback_id='CB-LEDGER-001', ) db.session.add(unit_run) db.session.flush() - report_file = ShippingReceiptReportFile( + report_file = FreightRpaInboundReportFile( unit_run_id=unit_run.id, storage_provider='minio', storage_bucket='receipts', @@ -198,7 +198,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db): db.session.commit() loaded = db.session.get(TransferMovementLedger, ledger.id) - assert loaded.source_file.id == report_file.id # relationship 目标 ShippingReceiptReportFile + assert loaded.source_file.id == report_file.id # relationship 目标 FreightRpaInboundReportFile # ON DELETE SET NULL 行为:开启 SQLite FK 强制后原样删文件(文件资产保留策略)。 # PRAGMA 是连接级开关且事务内为 no-op:必须走 AUTOCOMMIT 连接执行,归还连接池 @@ -208,7 +208,7 @@ def test_source_file_relationship_and_delete_sets_null(app, transfer_db): with db.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn: conn.execute(text('PRAGMA foreign_keys=ON')) conn.execute( - text('DELETE FROM shipping_receipt_report_files WHERE id = :id'), + text('DELETE FROM freight_rpa_inbound_report_files WHERE id = :id'), {'id': file_id}, ) conn.execute(text('PRAGMA foreign_keys=OFF')) diff --git a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py b/backend/tests/services/shipping_notice/test_onhand_candidate_projection.py similarity index 80% rename from backend/tests/services/shipping_notice/test_inventory_candidate_projection.py rename to backend/tests/services/shipping_notice/test_onhand_candidate_projection.py index f63675e6..aac31346 100644 --- a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py +++ b/backend/tests/services/shipping_notice/test_onhand_candidate_projection.py @@ -1,5 +1,5 @@ """ -tests/services/shipping_notice/test_inventory_candidate_projection.py +tests/services/shipping_notice/test_onhand_candidate_projection.py 用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。 依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。 @@ -10,19 +10,19 @@ from __future__ import annotations from app import db from app.models import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, ShippingOrderTask, ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingNoticeLineInventoryMatch, - ShippingInventoryFile, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandReportFile, ) -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_facts, ) -from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines +from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines def _task(task_no: str) -> ShippingOrderTask: @@ -36,8 +36,8 @@ def _task(task_no: str) -> ShippingOrderTask: return task -def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet: - row = ShippingInventoryCandidateSet( +def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingOnhandCandidateSet: + row = ShippingOnhandCandidateSet( task_id=int(task.id), set_version=version, lifecycle_status='frozen', @@ -50,12 +50,12 @@ def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInvento return row -def test_prepare_candidate_inventory_lines_blocks_without_active_set(app): +def test_prepare_candidate_onhand_lines_blocks_without_active_set(app): with app.app_context(): task = _task('SN-CAND-001') db.session.commit() - result = prepare_candidate_inventory_lines(task) + result = prepare_candidate_onhand_lines(task) assert result['status'] == 'blocked' assert result['error_code'] == 'inventory_candidates_missing' @@ -66,13 +66,13 @@ def test_project_inventory_candidate_facts_reads_current_structured_set(app): with app.app_context(): task = _task('SN-CAND-002') candidate_set = _candidate_set(task, version=2) - source = ShippingInventoryCandidateSource( + source = ShippingOnhandCandidateSource( candidate_set_id=int(candidate_set.id), source_code='DBS_DUB', candidate_order=1, candidate_origin='rule', ) - line = ShippingInventoryCandidateLine( + line = ShippingOnhandCandidateLine( candidate_set_id=int(candidate_set.id), line_no=1, source_line_no='00010', @@ -99,14 +99,14 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): with app.app_context(): task = _task('SN-CAND-003') old_set = _candidate_set(task, version=1) - old_line = ShippingInventoryCandidateLine( + old_line = ShippingOnhandCandidateLine( candidate_set_id=int(old_set.id), line_no=1, source_codes_json=['DBS_OLD'], ) db.session.add(old_line) db.session.flush() - new_set = ShippingInventoryCandidateSet( + new_set = ShippingOnhandCandidateSet( task_id=int(task.id), set_version=2, lifecycle_status='frozen', @@ -116,7 +116,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): db.session.flush() task.active_inventory_candidate_set_id = int(new_set.id) db.session.flush() - new_line = ShippingInventoryCandidateLine( + new_line = ShippingOnhandCandidateLine( candidate_set_id=int(new_set.id), line_no=1, source_codes_json=['DBS_NEW'], @@ -132,7 +132,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0) db.session.add(snapshot_line) db.session.flush() - db.session.add(ShippingNoticeLineInventoryMatch( + db.session.add(ShippingNoticeLineOnhandMatch( task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1, @@ -141,8 +141,8 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): candidate_set_version=1, candidate_line_id=int(old_line.id), match_result='matched', - inventory_status='ready', - inventory_source_code='DBS_OLD', + onhand_status='ready', + source_code='DBS_OLD', is_current=True, allowed_source_codes_snapshot=['DBS_OLD'], detail_json={'disposition': 'ok'}, @@ -161,12 +161,12 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app with app.app_context(): task = _task('SN-CAND-EVIDENCE') candidate_set = _candidate_set(task) - db.session.add(ShippingInventoryCandidateLine( + db.session.add(ShippingOnhandCandidateLine( candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'], )) db.session.flush() - inventory_file = ShippingInventoryFile( - inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx', + inventory_file = FreightRpaOnhandReportFile( + onhand_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx', source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64, ) db.session.add(inventory_file) @@ -180,11 +180,11 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0) db.session.add(snapshot_line) db.session.flush() - db.session.add(ShippingNoticeLineInventoryMatch( + db.session.add(ShippingNoticeLineOnhandMatch( task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1, candidate_set_id=int(candidate_set.id), - candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched', - inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no, + candidate_set_version=1, onhand_snapshot_id=int(inventory_file.id), match_result='matched', + onhand_status='ready', source_code='DBS_DUB', matched_file_no=inventory_file.onhand_file_no, matched_row_index=9, is_current=True, detail_json={}, )) db.session.commit() diff --git a/backend/tests/services/shipping_notice/test_onhand_report_handler.py b/backend/tests/services/shipping_notice/test_onhand_report_handler.py new file mode 100644 index 00000000..81c2e965 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_onhand_report_handler.py @@ -0,0 +1,791 @@ +"""tests/services/shipping_notice/test_onhand_report_handler.py + +用途:阶段 B Task 7 修复轮——onhand 报表事实投递接线与处理函数契约测试: + 单回调/批量 worker 在文件行 commit 后投递事实(先 commit 再投递、处理函数 + 失败外抛且文件行保留)、success 事实 settle 等待中的候选准备并同步门禁 + (处理函数自行 commit、重放不重复候选行)、失败事实不发明候选行; + 修复轮 2 补批量契约:单文件处理函数失败不跳过其余文件投递与排程收口、 + Job 意外异常 requeue 可重试;修复轮 3 补:失败点回滚半途写(不被后续 + commit 持久化)、drop 文件清理先于错误外抛、Job 重试「只重投失败文件」 + 通道(callback_id 已消费拦不住重投、未完成绝不返回 ok)。 +依赖:app(SQLite)fixture、freight_rpa.reports.dispatch / facts、 + freight_rpa.onhand.report_store(候选 settle 所绑文件行的唯一插入入口)、 + onhand_rpa_workflow(回调入口 + 重试通道/专用异常)、onhand_recovery_service + (候选准备表)、jobs.handlers.freight_rpa_onhand_callback_process(Job 收口)。 +逻辑:直接处理函数用例以 monkeypatch 替身 gate 同步记录调用(不断言 Gate 全链); + e2e 投递用例复用 test_shipping_notice_inventory_rpa_workflow 的动态订单/ + 客户确认/库存源种子 harness,跑通 rpa_report_inventory / + process_rpa_report_inventory_batch 全程后在注册表注入记录器断言事实字段; + 批量失败用例以替身 finalize 记录收口调用(内部预存在 NameError 与本契约无关)。 +""" + +from __future__ import annotations + +import pytest + +from tests.conftest import inventory_xlsx_with_warehouse + + +@pytest.fixture +def db_session(app): + """复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +@pytest.fixture(autouse=True) +def _fake_gate_sync(monkeypatch): + """替身门禁同步:记录 (execution_id) 调用序列,不跑 Gate 全链(聚焦候选/提交契约)。""" + calls: list[int] = [] + + def _record(**kwargs): + calls.append(int(kwargs['execution'].id)) + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + _record, + ) + return calls + + +def _seed_waiting_preparation(db_session, *, task_no: str, execution_no: str): + """构造「任务 + 活动执行 + 等待中候选准备轮次(waiting SourceAttempt)」。 + + Returns: + (task, execution, preparation, source_row) 四元组。 + """ + from app.models import ( + ShippingOnhandPreparationAttempt, + ShippingOnhandPreparationSourceAttempt, + ShippingOrderTask, + ShippingProcessExecution, + ) + + task = ShippingOrderTask( + task_no=task_no, user_id=1, source_type='direct_pdf', status='ready', + ) + db_session.add(task) + db_session.flush() + execution = ShippingProcessExecution( + execution_no=execution_no, task_id=task.id, status='active', + ) + db_session.add(execution) + db_session.flush() + task.active_process_execution_id = execution.id + preparation = ShippingOnhandPreparationAttempt( + task_id=task.id, attempt_no=1, status='waiting_external', + ) + db_session.add(preparation) + db_session.flush() + source_row = ShippingOnhandPreparationSourceAttempt( + preparation_attempt_id=preparation.id, source_code='DSV360_AWSDU', status='waiting', + ) + db_session.add(source_row) + db_session.commit() + return task, execution, preparation, source_row + + +def _onhand_file_id(*, source_code: str = 'DSV360_AWSDU') -> int: + """经唯一插入入口 report_store 落一行 ready onhand 报表文件并 commit,返回 file_id。""" + from app import db + from app.services.freight_rpa.onhand.report_store import insert_onhand_report + from app.services.shipping_notice.onhand_file_store import generate_inventory_file_no + + file_id = insert_onhand_report( + onhand_file_no=generate_inventory_file_no(), + storage_path='handler://onhand-report-fact.xlsx', + source_code=source_code, + snapshot_status='ready', + file_sha256='a' * 64, + ) + db.session.commit() + return file_id + + +def test_onhand_fact_settles_waiting_candidates_and_syncs_gates(app, db_session, _fake_gate_sync): + """success 事实:settle 等待候选(ready + 绑文件)→ 聚合准备轮次 → 门禁同步 → 自行 commit。""" + from app.models import ShippingOnhandPreparationAttempt, ShippingOnhandPreparationSourceAttempt + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + + task, execution, preparation, source_row = _seed_waiting_preparation( + db_session, task_no='OT-ONHAND-FACT-SETTLE', execution_no='EX-ONHAND-FACT-SETTLE', + ) + file_id = _onhand_file_id() + + handle_onhand_report(ReportFact( + report_kind='onhand', source_code='DSV360_AWSDU', + file_id=file_id, sha256='a' * 64, ok=True, + )) + + # [断言意图] 处理函数必须自行 commit:rollback + expire_all 后 settle 仍可见。 + db_session.rollback() + db_session.expire_all() + refreshed_source = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id) + assert refreshed_source.status == 'ready' + assert refreshed_source.onhand_file_id == file_id + refreshed_prep = db_session.get(ShippingOnhandPreparationAttempt, preparation.id) + assert refreshed_prep.status == 'succeeded' + assert refreshed_prep.completed_at is not None + # [断言意图] 门禁同步覆盖 settle 受影响的准备轮次任务(execution 绑定同任务)。 + assert _fake_gate_sync == [execution.id] + + # [重放] 同一事实重复投递:等待集已空——不重复 settle、不重复候选行(幂等)。 + handle_onhand_report(ReportFact( + report_kind='onhand', source_code='DSV360_AWSDU', + file_id=file_id, sha256='a' * 64, ok=True, + )) + db_session.rollback() + db_session.expire_all() + assert ShippingOnhandPreparationSourceAttempt.query.count() == 1 + assert db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id).onhand_file_id == file_id + assert db_session.get(ShippingOnhandPreparationAttempt, preparation.id).status == 'succeeded' + + +def test_onhand_failure_fact_invents_no_candidate_rows(app, db_session, _fake_gate_sync): + """失败/空事实:无文件可挂——不发明候选行(SourceAttempt 保持 waiting、不绑文件),仅重投影门禁。""" + from app.models import ShippingOnhandPreparationSourceAttempt + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + + task, execution, preparation, source_row = _seed_waiting_preparation( + db_session, task_no='OT-ONHAND-FACT-FAIL', execution_no='EX-ONHAND-FACT-FAIL', + ) + + handle_onhand_report(ReportFact( + report_kind='onhand', source_code='DSV360_AWSDU', + file_id=None, sha256=None, ok=False, + error_code='rpa_export_failed', error_message='boom', + )) + + db_session.rollback() + db_session.expire_all() + # [断言意图] 失败事实没有文件身份:不得发明/改写候选行——仍是唯一一行、 + # 状态保持 waiting、未绑定任何文件;门禁重投影(失败路径门禁更新归处理函数)。 + assert ShippingOnhandPreparationSourceAttempt.query.count() == 1 + refreshed = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id) + assert refreshed.status == 'waiting' + assert refreshed.onhand_file_id is None + assert _fake_gate_sync == [execution.id] + + +def _seed_direct_rpa_task(db, *, task_no: str, run_no: str, sample) -> None: + """复用动态订单 harness:直建 OT + 动态订单 + 客户确认 + 库存源种子 + RPA 触发种子。""" + from app.models import ShippingOrderTask + from tests.conftest import seed_rpa_inventory_trigger, seed_task_inventory_source + from tests.test_shipping_notice_inventory_rpa_workflow import ( + _attach_dynamic_order, + _confirm_direct_rpa_task_customer, + ) + + task = ShippingOrderTask( + task_no=task_no, user_id=1, source_type='direct_pdf', status='ready', + ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) + _confirm_direct_rpa_task_customer(task) + seed_task_inventory_source(task, source_code='DSV360_AWSDU') + seed_rpa_inventory_trigger(task, run_no=run_no) + db.session.add(task) + db.session.commit() + + +def _stub_structure_validation(monkeypatch): + """替身结构校验:onhand_structure_drift 仍读已删站点列(Task 2 已记录的 deferred + minor,legacy 套件待 s18 改写)——与本修复无关;本测试聚焦 commit 后投递接线。 + + 返回与真实 validate_production_inventory_structure 同形状的确定性解析参数: + field_mapping 用 conftest 种子字段 ID 对齐样例 xlsx 列头 + (Warehouse ID / SKU / Reservation ID / Qty,表头行 1,默认 sheet)。 + """ + from app.models import FreightRpaOnhandField + + fields = { + row.field_code: row + for row in FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.field_code.in_( + ['part_number', 'reservation_id', 'available_qty', 'warehouse_id'], + ) + ) + } + structure_check = { + 'field_mapping': { + str(fields['part_number'].id): 'SKU', + str(fields['reservation_id'].id): 'Reservation ID', + str(fields['available_qty'].id): 'Qty', + str(fields['warehouse_id'].id): 'Warehouse ID', + }, + 'header_row_index': 1, + 'sheet_name': 'Sheet', + 'level': 'exact', + 'difference': {}, + 'warnings': [], + } + monkeypatch.setattr( + 'app.services.shipping_notice.onhand_structure_drift.validate_production_inventory_structure', + lambda **_kwargs: structure_check, + ) + + +def test_single_callback_dispatches_onhand_fact_after_file_commit(app, tmp_path, monkeypatch): + """rpa_report_inventory:文件行 commit 后同请求投递 onhand 事实,字段与已提交行对齐。""" + from app import db + from app.models import FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory + from tests.conftest import rpa_callback_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'onhand-fact.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + register_report_handler('onhand', seen.append) + + with app.app_context(): + from app.models import ShippingOrderTask + + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-DISPATCH', run_no='RUN-ONHAND-FACT', sample=sample) + task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-DISPATCH').one() + result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT')) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-FACT', snapshot_status='ready', + ).first() + assert snap is not None + assert result.get('status') == 'ok' + # [断言意图] commit 后投递:恰好一条事实、字段与已提交文件行逐项对齐。 + assert len(seen) == 1 + fact = seen[0] + assert fact.report_kind == 'onhand' + assert fact.ok is True + assert fact.file_id == snap.id + assert fact.source_code == 'DSV360_AWSDU' + assert fact.sha256 == snap.file_sha256 + # 文件行已提交:rollback 后重查仍在(先 commit 再投递的顺序契约)。 + db.session.rollback() + db.session.expire_all() + assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None + + +def test_single_callback_handler_failure_propagates_and_keeps_file_row(app, tmp_path, monkeypatch): + """处理函数抛错:异常原样外抛(不折进 post_commit_warnings),已提交文件行保留。""" + from app import db + from app.models import FreightRpaOnhandReportFile, ShippingOrderTask + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory + from tests.conftest import rpa_callback_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'onhand-fact-fail.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + def boom(_fact) -> None: + raise RuntimeError('onhand handler down') + + register_report_handler('onhand', boom) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-RAISE', run_no='RUN-ONHAND-FACT-RAISE', sample=sample) + task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-RAISE').one() + + # [断言意图] 异常必须外抛(供 Worker 重试整笔回调),绝不折进 warnings 后返回 ok。 + with pytest.raises(RuntimeError, match='onhand handler down'): + rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT-RAISE')) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-FACT-RAISE', snapshot_status='ready', + ).first() + assert snap is not None + db.session.rollback() + db.session.expire_all() + # [断言意图] 处理函数失败不回滚已提交文件行。 + assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None + + +def test_batch_worker_dispatches_onhand_fact_after_commit(app, tmp_path, monkeypatch): + """process_rpa_report_inventory_batch:整批事务 commit 后逐文件投递 onhand 事实。""" + from app import db + from app.models import FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'onhand-fact-batch.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + register_report_handler('onhand', seen.append) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-BATCH', run_no='RUN-ONHAND-FACT-BATCH', sample=sample) + task_no = 'OT-ONHAND-FACT-BATCH' + + result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-FACT-BATCH', + 'trigger_type': 'on_demand', + 'results': [scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample), task_no=task_no, + )], + })) + assert result.get('status') == 'ok' + assert result.get('data', {}).get('success_count') == 1 + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-FACT-BATCH', snapshot_status='ready', + ).first() + assert snap is not None + # [断言意图] 整批 commit 后逐文件投递:恰一条 ok=True 事实,file_id 对齐已提交行。 + assert [fact.file_id for fact in seen] == [snap.id] + assert all(fact.report_kind == 'onhand' and fact.ok is True for fact in seen) + db.session.rollback() + db.session.expire_all() + assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None + + +def test_batch_handler_failure_does_not_skip_remaining_dispatch_or_finalize(app, tmp_path, monkeypatch): + """批量内单文件处理函数失败:其余已提交文件仍投递、排程收口仍执行、错误仍外抛、文件行保留。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample_a = drop_dir / 'onhand-fact-batch-a.xlsx' + sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + sample_b = drop_dir / 'onhand-fact-batch-b.xlsx' + sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + # [断言意图·观测点] 排程收口必须仍被调用(内部预存在 NameError 与本契约无关)。 + finalize_calls: list = [] + monkeypatch.setattr( + 'app.services.schedule.freight_rpa_onhand_finalize.finalize_shipping_inventory_schedule_run', + lambda schedule_run_id, **_kwargs: ( + finalize_calls.append(schedule_run_id) + or {'ok': True, 'schedule_finalize_status': 'finalized'} + ), + ) + # [断言意图·观测点] 首个文件处理函数失败,第二个必须照常收到事实。 + seen: list[ReportFact] = [] + calls = {'n': 0} + + def flaky(fact: ReportFact) -> None: + calls['n'] += 1 + seen.append(fact) + if calls['n'] == 1: + raise RuntimeError('onhand handler down mid-batch') + + register_report_handler('onhand', flaky) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + task = ScheduleTask( + schedule_no='SCH-ONHAND-BATCH-FAIL', name='Onhand batch fail', schedule_type='platform_job', + platform_api_path='freight-rpa-onhand', owner_user_id=1, cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no='RUN-ONHAND-BATCH-FAIL', schedule_task_id=task.id, status='running', + total_count=2, success_count=0, failed_count=0, skipped_count=0, + response_summary_json={'awaiting_rpa': True}, + ) + db.session.add(run) + db.session.commit() + + # [断言意图] 处理函数异常必须外抛(调用方/Job 见到失败)——但不得因此跳过 + # 其余文件投递与排程收口(断言在 pytest.raises 之后进行)。 + with pytest.raises(RuntimeError, match='onhand handler down mid-batch'): + process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-BATCH-FAIL', + 'schedule_run_id': run.id, + 'trigger_type': 'scheduled', + 'results': [ + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-BATCH-FAIL-A', + ), + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-BATCH-FAIL-B', + ), + ], + })) + + snaps = FreightRpaOnhandReportFile.query.filter( + FreightRpaOnhandReportFile.snapshot_status == 'ready', + FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B')), + ).order_by(FreightRpaOnhandReportFile.id).all() + # [断言意图] 两个文件行都已落库并保留(commit 先于投递,失败不回滚)。 + assert [snap.rpa_run_no for snap in snaps] == ['SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B'] + # [断言意图] 两个文件的事实都投递了(首文件失败不跳过次文件投递)。 + assert [fact.file_id for fact in seen] == [snap.id for snap in snaps] + # [断言意图] 排程收口仍执行(不被处理函数失败跳过)。 + assert finalize_calls == [run.id] + db.session.rollback() + db.session.expire_all() + assert {db.session.get(FreightRpaOnhandReportFile, snap.id) is not None for snap in snaps} == {True} + + +def test_callback_process_job_requeues_on_unexpected_exception(app, monkeypatch): + """Job 意外异常(含批量 commit 后处理函数失败重抛)必须可重试 requeue,而非终态 failed。""" + from app import db + from app.jobs.context import JobContext + from app.jobs.handlers import freight_rpa_onhand_callback_process as handler + from app.models import Job + + with app.app_context(): + job = Job( + domain='shipping_notice', + job_type='freight_rpa_onhand_callback_process', + status='running', + attempts=1, + max_attempts=3, + business_ref='inventory-callback:retryable-check', + payload_json={'callback_id': 'retryable-check'}, + ) + db.session.add(job) + db.session.commit() + + def _boom(_payload): + raise RuntimeError('dispatch re-raise after commit') + + monkeypatch.setattr( + 'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch', + _boom, + ) + + handler.run_shipping_inventory_callback_process( + JobContext(config={}, logger=None, extras={}), {'job_id': job.id}, + ) + db_session = db.session + db_session.expire_all() + # [断言意图] retryable=True → requeue(attempts 未耗尽时回到 queued 等待重试), + # 绝不落终态 failed——批量文件行已提交,重放按幂等契约补齐收口。 + refreshed = db_session.get(Job, job.id) + assert refreshed.status == 'queued' + + +def test_batch_handler_failure_rolls_back_partial_writes_and_next_file_dispatches(app, db_session, tmp_path, monkeypatch): + """批量内处理函数「先 bind 候选再抛错」:半途 flush 写必须回滚(不得被后续 commit 持久化),次文件照常投递。""" + from app import db + from app.models import FreightRpaOnhandReportFile, ShippingOnhandPreparationSourceAttempt + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample_a = drop_dir / 'rollback-a.xlsx' + sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + sample_b = drop_dir / 'rollback-b.xlsx' + sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + calls = {'n': 0} + + def bind_then_raise_or_settle(fact: ReportFact) -> None: + calls['n'] += 1 + seen.append(fact) + if calls['n'] == 1: + # [RED 场景] 模拟「先 bind 候选再抛错」的处理函数:半途 flush(不 commit)。 + from app.models import ShippingOnhandPreparationSourceAttempt as _Row + + row = ( + _Row.query.filter_by(source_code='DSV360_AWSDU') + .order_by(_Row.id) + .first() + ) + row.status = 'ready' + row.onhand_file_id = int(fact.file_id) + db.session.flush() + raise RuntimeError('bind then raise mid-batch') + # 次文件走真实处理函数:内部 settle(等待集)→ 门禁同步 → 自行 commit。 + handle_onhand_report(fact) + + register_report_handler('onhand', bind_then_raise_or_settle) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _task, _execution, _preparation, source_row = _seed_waiting_preparation( + db_session, task_no='OT-ONHAND-ROLLBACK', execution_no='EX-ONHAND-ROLLBACK', + ) + + with pytest.raises(RuntimeError, match='bind then raise mid-batch'): + process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-ROLLBACK', + 'trigger_type': 'on_demand', + 'results': [ + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-ROLLBACK-A', + ), + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-ROLLBACK-B', + ), + ], + })) + + snaps = FreightRpaOnhandReportFile.query.filter( + FreightRpaOnhandReportFile.snapshot_status == 'ready', + FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-ROLLBACK-A', 'SR-ROLLBACK-B')), + ).order_by(FreightRpaOnhandReportFile.id).all() + # [断言意图] 次文件照常投递:两个已提交文件的事实都送达处理函数。 + assert [fact.file_id for fact in seen] == [snap.id for snap in snaps] + + db.session.rollback() + db.session.expire_all() + # [断言意图] 首文件半途 bind 已回滚——不得被次文件处理函数的 commit 持久化成 + # file-A 绑定;次文件真实 settle 落到 file B(等待集在回滚后原样可 settle)。 + refreshed = db.session.get(ShippingOnhandPreparationSourceAttempt, source_row.id) + assert refreshed.status == 'ready' + assert refreshed.onhand_file_id == snaps[1].id + + +def test_batch_handler_failure_still_flushes_drop_file_cleanup_before_raise(app, tmp_path, monkeypatch): + """处理函数抛错:drop 文件清理(消费标记+移动/入队)必须先于错误外抛完成。""" + from app import db + from app.models import FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'cleanup-before-raise.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + def boom(_fact) -> None: + raise RuntimeError('onhand handler down cleanup') + + register_report_handler('onhand', boom) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-CLEANUP', run_no='RUN-ONHAND-CLEANUP', sample=sample) + + with pytest.raises(RuntimeError, match='onhand handler down cleanup'): + process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-CLEANUP', + 'trigger_type': 'on_demand', + 'results': [scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-CLEANUP', + )], + })) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-CLEANUP', snapshot_status='ready', + ).first() + assert snap is not None + # [断言意图] 错误已外抛,但 drop 文件清理先行完成:消费标记/移动先于重抛, + # 文件离开 drop 根、落入 processed 归档(移动失败时则入持久化 cleanup 队列)。 + assert not sample.exists() + assert (drop_dir / 'processed' / sample.name).exists() + + +def test_batch_retry_channel_redispatches_file_despite_consumed_callback_id(app, tmp_path, monkeypatch): + """重试通道:task-linked 项 Attempt 已消费 callback_id(整批重放必被跳过)时,失败文件仍重投事实。""" + from datetime import datetime + + from app import db + from app.models import FreightRpaOnhandReportFile, ShippingOrderTask, FreightRpaOnhandTaskAttempt + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import ( + OnhandReportDispatchAfterCommitError, + process_rpa_report_inventory_batch, + ) + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'retry-callback-id.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + calls = {'n': 0} + + def flaky(fact: ReportFact) -> None: + calls['n'] += 1 + seen.append(fact) + if calls['n'] == 1: + raise RuntimeError('onhand handler down first pass') + + register_report_handler('onhand', flaky) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-RETRY', run_no='RUN-ONHAND-RETRY', sample=sample) + task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-RETRY').one() + candidate_set_id = int(task.active_inventory_candidate_set_id or 1) + # [RED 场景] 结构化 per-source Attempt(v2 身份字段与回调 item 对齐): + # pass 1 的回调确认会把 attempt.callback_id 写入——整批重放随即被 replay 检查跳过。 + # source_run_no 用与批量 run_no 不同的 PSR 轮次号(与真实 Worker 形态一致: + # run_no=批量轮次、source_run_no=逐源轮次——run_no 消费标记按 source_run_no + # 匹配,不会误吞本 Attempt)。 + attempt = FreightRpaOnhandTaskAttempt( + task_no='OT-ONHAND-RETRY', + source_code='DSV360_AWSDU', + attempt_no=1, + source_run_no='PSR-ONHAND-RETRY-1', + status='queued', + triggered_at=datetime.utcnow(), + lease_token='test-lease-token', + execution_phase='trigger_written', + extra_json={ + 'trigger_mode': 'test', + 'candidate_set_id': candidate_set_id, + 'execution_id': 1, + 'gate_id': 1, + }, + ) + db.session.add(attempt) + db.session.commit() + + batch_payload = v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-RETRY', + 'trigger_type': 'on_demand', + 'results': [dict( + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-RETRY', + ), + callback_id='test-callback:RUN-ONHAND-RETRY', + source_run_no='PSR-ONHAND-RETRY-1', + attempt_no=1, + lease_token='test-lease-token', + candidate_set_id=candidate_set_id, + execution_id=1, + gate_id=1, + )], + }) + + # [STEP 1] 首轮:文件落地+回调确认(写 callback_id)+投递失败 → 专用异常携带清单外抛。 + with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo: + process_rpa_report_inventory_batch(batch_payload) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='PSR-ONHAND-RETRY-1', snapshot_status='ready', + ).first() + assert snap is not None + assert excinfo.value.failed_files == [{ + 'source_code': 'DSV360_AWSDU', + 'file_id': snap.id, + 'sha256': (snap.file_sha256 or None), + }] + # [断言意图·RED 场景] Attempt 已消费 callback_id——整批重放会被 replay 检查跳过。 + db.session.expire(attempt) + assert str(attempt.callback_id or '').strip() + armed_callback_id = str(attempt.callback_id) + + # [STEP 2] 整批重放(不带重试清单):item 被 replay 检查跳过——不落地、不投递, + # 证明整批重放无法补投(这正是「只重投失败文件」通道存在的原因)。 + replay_result = process_rpa_report_inventory_batch(dict(batch_payload)) + assert [fact.file_id for fact in seen] == [snap.id] + assert replay_result.get('data', {}).get('created') == [] + assert armed_callback_id == str( + FreightRpaOnhandTaskAttempt.query.filter_by( + task_no='OT-ONHAND-RETRY', source_code='DSV360_AWSDU', + ).order_by(FreightRpaOnhandTaskAttempt.id.desc()).first().callback_id or '', + ) + + # [STEP 3] 重试通道(Job 处理器写回的 retry_dispatch_files):只重投失败文件。 + retry_payload = {**batch_payload, 'retry_dispatch_files': excinfo.value.failed_files} + result = process_rpa_report_inventory_batch(retry_payload) + assert result.get('status') == 'ok' + assert result.get('data', {}).get('result_status') == 'retried' + # [断言意图] 同一 file_id 的事实再次送达处理函数(callback_id 已消费拦不住重投)。 + assert [fact.file_id for fact in seen] == [snap.id, snap.id] + + +def test_batch_retry_channel_reraises_while_handler_still_failing(app, monkeypatch): + """重试通道:处理函数仍未成功时必须继续携带清单重抛,绝不在未完成时返回 ok。""" + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.onhand_rpa_workflow import ( + OnhandReportDispatchAfterCommitError, + process_rpa_report_inventory_batch, + ) + + def boom(_fact) -> None: + raise RuntimeError('onhand handler still down') + + register_report_handler('onhand', boom) + + with app.app_context(): + file_id = _onhand_file_id() + marker = {'source_code': 'DSV360_AWSDU', 'file_id': file_id, 'sha256': None} + + # [断言意图] 处理函数持续失败:重试通道继续抛专用异常(携带同一未成功清单, + # Job 据此继续 requeue 直至 attempts 耗尽落终态 failed)——绝不返回 ok。 + with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo: + process_rpa_report_inventory_batch({'retry_dispatch_files': [marker]}) + assert excinfo.value.failed_files == [marker] + + +def test_callback_process_job_records_failed_files_for_retry(app, monkeypatch): + """Job 收口:投递失败重抛的清单写回 payload(retry_dispatch_files)并 requeue 可重试。""" + from app import db + from app.jobs.context import JobContext + from app.jobs.handlers import freight_rpa_onhand_callback_process as handler + from app.models import Job + from app.services.shipping_notice.onhand_rpa_workflow import OnhandReportDispatchAfterCommitError + + marker = {'source_code': 'DSV360_AWSDU', 'file_id': 4242, 'sha256': 'a' * 64} + + with app.app_context(): + job = Job( + domain='shipping_notice', + job_type='freight_rpa_onhand_callback_process', + status='running', + attempts=1, + max_attempts=3, + business_ref='inventory-callback:dispatch-retry-check', + payload_json={'callback_id': 'dispatch-retry-check'}, + ) + db.session.add(job) + db.session.commit() + + def _raise_dispatch_error(_payload): + raise OnhandReportDispatchAfterCommitError( + 'onhand handler down after commit', failed_files=[dict(marker)], + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch', + _raise_dispatch_error, + ) + + handler.run_shipping_inventory_callback_process( + JobContext(config={}, logger=None, extras={}), {'job_id': job.id}, + ) + db.session.expire_all() + # [断言意图] 清单写回 payload(重试只重投这些文件)+ requeue 可重试。 + refreshed = db.session.get(Job, job.id) + assert refreshed.status == 'queued' + assert refreshed.payload_json['retry_dispatch_files'] == [marker] diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 6c92183f..ee6f2935 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -418,7 +418,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta facts = _project_case_formal_gate_facts({ 'current_gate': { - 'gate_code': 'inventory_source_routing', + 'gate_code': 'onhand_source_routing', 'status': 'pending', 'blocking_reason_code': None, 'next_action_code': None, @@ -430,7 +430,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta assert facts is not None current_gate, blocking_reason, user_status = facts - assert current_gate['gate_code'] == 'inventory_source_routing' + assert current_gate['gate_code'] == 'onhand_source_routing' assert blocking_reason['code'] is None assert user_status == 'running' diff --git a/backend/tests/services/shipping_notice/test_report_model_boundary.py b/backend/tests/services/shipping_notice/test_report_model_boundary.py new file mode 100644 index 00000000..b6763d5f --- /dev/null +++ b/backend/tests/services/shipping_notice/test_report_model_boundary.py @@ -0,0 +1,32 @@ +""" +tests/services/shipping_notice/test_report_model_boundary.py + +用途:阶段 B Task 5 边界门禁——禁止发货域(shipping_notice)源码直接构造 + 货代 RPA 报表模型行(FreightRpaOnhandReportFile / FreightRpaInboundReportFile / + FreightRpaInboundReportConfig 的构造调用)。插入必须经 + freight_rpa/onhand/report_store,读取/下载必须走 freight_rpa/reports 查询面。 +依赖:无运行时依赖(纯文件系统扫描);backend/app/services/shipping_notice 源码。 +逻辑:rglob 全部 *.py 逐文件搜禁词构造片段;命中即失败并列出文件与片段, + 保证违规时能一眼定位,而不是只报一个计数。 +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.pure_unit + + +def test_shipping_notice_does_not_construct_rpa_report_rows(): + root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice" + banned_snippets = ("FreightRpaOnhandReportFile(", "FreightRpaInboundReportFile(", "FreightRpaInboundReportConfig(") + hits = [] + for path in root.rglob("*.py"): + text = path.read_text(encoding="utf-8") + for snippet in banned_snippets: + if snippet in text: + hits.append(f"{path.name}: {snippet}") + # 关键断言:三类 RPA 报表行的构造调用必须全部消失(插入已收敛进 report_store)。 + assert hits == [] \ No newline at end of file diff --git a/backend/tests/test_admin_freight_rpa_onhand_config.py b/backend/tests/test_admin_freight_rpa_onhand_config.py new file mode 100644 index 00000000..52f63ffb --- /dev/null +++ b/backend/tests/test_admin_freight_rpa_onhand_config.py @@ -0,0 +1,202 @@ +""" +tests/test_admin_freight_rpa_onhand_config.py + +用途:锁定 s18 后库存站点启用门禁与在手报表配置行(FreightRpaOnhandReportConfig)的服务层行为。 +依赖:conftest 的 app fixture(建表并播种 TEST_RUNTIME 配置)、app.core.errors.ValidationError、 + shipping_onhand_admin_service(assert_onhand_source_can_enable / save_onhand_report_config / + save_receipt_report_config)、FreightRpaOnhandReportConfig / FreightRpaSource 等模型。 +逻辑:验证启用中站点缺模板/缺配置行/缺解析绑定时 fail-closed;保存在手配置只写配置行、 + 不写站点已删除的三列,并递增配置行 config_version;在手与入站两侧解析方案 purpose 互斥。 +""" + +from __future__ import annotations + +import itertools + +import pytest + +from app.core.errors import ValidationError +from app.models import ( + FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaParsingProfile, FreightRpaProfile, +) +from app.services.admin.shipping_onhand_admin_service import ( + assert_onhand_source_can_enable, save_onhand_report_config, save_receipt_report_config, +) + +# 站点/连接编码自增,保证同一测试内多次构造不撞唯一约束。 +_SOURCE_SEQUENCE = itertools.count(1) + + +@pytest.fixture +def db_session(app): + """复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +def _source(*, enabled: bool, excel_template_id: int | None) -> FreightRpaSource: + """构造最小可落库的库存站点(fixed 仓库模式 + 专用连接 Profile),不自动 add 进会话。 + + Args: + enabled: 站点启用位;True 时调用方需自行保证模板/配置满足门禁或预期拒绝。 + excel_template_id: 发货模板外键;SQLite 测试库不强制外键,允许指向不存在的模板 id。 + + Returns: + FreightRpaSource: 未加入会话的站点对象,由调用方决定是否落库。 + """ + from app import db + + sequence = next(_SOURCE_SEQUENCE) + profile = FreightRpaProfile( + profile_code=f'TASK2_PROFILE_{sequence}', display_name=f'Task2 Profile {sequence}', + connector_type='dbs', login_url='https://test.invalid/dbs', + login_config_json={'auth_mode': 'password'}, + ) + db.session.add(profile) + db.session.flush() + return FreightRpaSource( + source_code=f'TASK2_SOURCE_{sequence}', display_name=f'Task2 Source {sequence}', + connector_type='dbs', rpa_profile_id=profile.id, excel_template_id=excel_template_id, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU', + enabled=enabled, + ) + + +def _published_onhand_profile_id() -> int: + """读取 conftest 播种的已发布在手解析方案(TEST_RUNTIME,purpose='onhand')。""" + profile = FreightRpaParsingProfile.query.filter_by( + profile_code='TEST_RUNTIME', status='published', + ).first() + assert profile is not None and profile.purpose == 'onhand' + return profile.id + + +def _published_inbound_profile_id(db_session) -> int: + """创建最小已发布入站解析方案,用于验证在手侧 fail-closed 拒绝跨 purpose 绑定。""" + profile = FreightRpaParsingProfile( + purpose='inbound', profile_code='TASK2_INBOUND', display_name='Task2 Inbound', + version=1, status='published', file_format='xlsx', definition_json={'field_mapping': {}}, + ) + db_session.add(profile) + db_session.commit() + return profile.id + + +def test_enabled_source_requires_onhand_profile_and_template(app, db_session): + """启用中站点缺发货模板必须被服务层拒绝。 + + [断言意图] 该状态同时违反 ck_freight_rpa_sources_enabled_template(enabled ⇒ 模板非空), + SQLite/PG 在 INSERT 时即拦截、无法落库,故按 save_source 提交前的调用形态验证未落库对象, + 与任务书原测试语义一致(服务层门禁先于数据库约束给出可解释错误码)。 + """ + source = _source(enabled=True, excel_template_id=None) + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_enabled_source_requires_onhand_report_config_row(app, db_session): + """启用中站点缺在手配置行时拒绝启用:配置行缺失是跨表状态,站点 CHECK 管不到。""" + source = _source(enabled=True, excel_template_id=9) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_enabled_source_requires_onhand_profile_binding(app, db_session): + """配置行存在但未绑解析方案时同样拒绝启用。""" + source = _source(enabled=True, excel_template_id=9) + db_session.add(source) + db_session.commit() + db_session.add(FreightRpaOnhandReportConfig(source=source)) + db_session.commit() + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_enabled_source_with_full_onhand_config_passes_gate(app, db_session): + """配置行 + 解析绑定 + 模板齐备的启用站点通过门禁(正向路径回归)。""" + source = _source(enabled=True, excel_template_id=9) + db_session.add(source) + db_session.commit() + db_session.add(FreightRpaOnhandReportConfig( + source=source, parsing_profile_id=_published_onhand_profile_id(), + )) + db_session.commit() + assert assert_onhand_source_can_enable(source) is None + + +def test_save_onhand_report_config_does_not_write_source_columns(app, db_session): + """保存在手配置只写配置行,不写站点已删除的 report_path_json 等三列。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + db_session.refresh(source) + assert not hasattr(source, "report_path_json") + config = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one() + assert config.report_path_json == {"menu": "stock"} + assert config.parsing_profile.purpose == "onhand" + + +def test_save_onhand_report_config_updates_row_and_bumps_config_version(app, db_session): + """已有配置行走更新并递增 config_version,行身份保持不变。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + first = save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + second = save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock2"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + assert second["id"] == first["id"] + row = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one() + assert row.report_path_json == {"menu": "stock2"} + # [断言意图] 首次插入默认 1,第二次保存必须递增为 2(任务书:有则更新并递增 config_version)。 + assert row.config_version == 2 + + +def test_save_onhand_report_config_rejects_non_onhand_parsing_profile(app, db_session): + """入站解析方案不得绑进在手配置;fail-closed 且不留下半写的配置行。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + save_onhand_report_config(source.id, { + "report_path_json": {}, + "query_parameters_json": [], + "parsing_profile_id": _published_inbound_profile_id(db_session), + }, actor_id=1) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + assert FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).count() == 0 + + +def test_save_receipt_report_config_keeps_inbound_only_binding(app, db_session): + """收料配置保存继续只接受 purpose='inbound' 的解析方案(在手/入站互斥回归)。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + save_receipt_report_config(source.id, { + # 先给合法 DBS 四段路径,确保失败点落在解析绑定校验(purpose 互斥)而非路径校验。 + "report_path_json": { + "program_group": "Bison", "program_label": "AWSBI", + "report_group": "Inbound", "report_name": "Receipt Detail", + }, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + assert exc.value.code == "SHIPPING.INBOUND_PROFILE_INVALID" diff --git a/backend/tests/test_admin_freight_rpa_routes.py b/backend/tests/test_admin_freight_rpa_routes.py new file mode 100644 index 00000000..324e51f4 --- /dev/null +++ b/backend/tests/test_admin_freight_rpa_routes.py @@ -0,0 +1,86 @@ +""" +tests/test_admin_freight_rpa_routes.py + +用途:锁定货代 RPA 管理路由已迁到 /api/admin/freight-rpa/,旧 shipping-notice 管理路径 404。 +依赖:Flask 测试客户端、admin blueprint、User。 +逻辑:只断言路径注册与管理员可达;权限表存量字符串不在本测试更新。 +""" + +from __future__ import annotations + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造遗留 Header 认证上下文,匹配现有管理 API 测试方式。""" + return {'X-Username': username, 'X-Role': role} + + +def _rules(app) -> set[str]: + """收集已注册的 URL 规则,用来断言旧路径没有双路由。""" + return {rule.rule for rule in app.url_map.iter_rules()} + + +def test_freight_rpa_admin_routes_moved_and_old_paths_404(app, client): + """新 sources 路径对管理员成功;旧 sources 与 inventory-fields 404;onhand/fields 已注册。""" + from app import db + from app.models import User + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + db.session.add(User( + username='freight-rpa-admin', + email='freight-rpa-admin@example.com', + role='admin', + status='active', + )) + db.session.commit() + + headers = _headers('freight-rpa-admin', 'admin') + listed = client.get('/api/admin/freight-rpa/sources', headers=headers) + # [断言意图] 管理员读取新 sources 列表必须走统一成功 envelope。 + assert listed.status_code == 200 + body = listed.get_json() + assert body['success'] is True + assert isinstance(body['data'], list) + + # [断言意图] 旧库存源路径无兼容路由。 + assert client.get('/api/admin/shipping-notice/sources', headers=headers).status_code == 404 + # [断言意图] 旧字段目录路径无兼容路由。 + assert client.get('/api/admin/shipping-notice/inventory-fields', headers=headers).status_code == 404 + + rules = _rules(app) + # [断言意图] 字段目录已挂到 onhand/fields,且旧规则不在 url map。 + assert '/api/admin/freight-rpa/onhand/fields' in rules + assert '/api/admin/shipping-notice/inventory-fields' not in rules + assert '/api/admin/shipping-notice/sources' not in rules + # [断言意图] 任务表里的旧前缀都不能再注册(含其子路径)。 + retired_prefixes = ( + '/api/admin/shipping-notice/sources', + '/api/admin/shipping-notice/source-validation-batches', + '/api/admin/shipping-notice/snapshots', + '/api/admin/shipping-notice/export-records', + '/api/admin/shipping-notice/routing-rules', + '/api/admin/shipping-notice/routing-fields', + '/api/admin/shipping-notice/inventory-fields', + '/api/admin/shipping-notice/configuration-catalog', + '/api/admin/shipping-notice/parsing-profiles', + '/api/admin/shipping-notice/inventory-structure-analyses', + '/api/admin/shipping-notice/external-mappings', + ) + for rule in rules: + for prefix in retired_prefixes: + assert rule != prefix and not rule.startswith(prefix + '/'), rule + assert '/api/admin/freight-rpa/sources//inbound-report-config' in rules + assert '/api/admin/freight-rpa/onhand/validation-batches' in rules + + fields = client.get('/api/admin/freight-rpa/onhand/fields', headers=headers) + assert fields.status_code == 200 + assert fields.get_json()['success'] is True + + # [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板与异动字段不动。 + assert '/api/admin/shipping-notice/temporary-onhand-sessions' in rules + assert '/api/admin/shipping-notice/temporary-inventory-sessions' not in rules + assert '/api/admin/shipping-notice/excel-templates' in rules + assert '/api/admin/shipping-notice/movement-fields' in rules + # [断言意图] rpa-profiles 仍在 freight-rpa,不重复注册到 shipping-notice。 + assert '/api/admin/freight-rpa/rpa-profiles' in rules + assert '/api/admin/shipping-notice/rpa-profiles' not in rules diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index df30caa8..1c030663 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -26,7 +26,7 @@ from app.models import ( ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingNotice, User, ) @@ -148,12 +148,12 @@ def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str | ) db.session.add(snapshot_line) db.session.flush() - db.session.add(ShippingNoticeLineInventoryMatch( + db.session.add(ShippingNoticeLineOnhandMatch( task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, match_result='matched', - inventory_status='ready', + onhand_status='ready', is_current=True, )) notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id) diff --git a/backend/tests/test_admin_shipping_inventory.py b/backend/tests/test_admin_shipping_inventory.py index be9bbe12..95ce6ab2 100644 --- a/backend/tests/test_admin_shipping_inventory.py +++ b/backend/tests/test_admin_shipping_inventory.py @@ -1,9 +1,9 @@ """ tests/test_admin_shipping_inventory.py -用途:验证货代库存后台的只读快照/导出记录接口及管理员权限。 +用途:验证货代 RPA 管理端只读快照/导出记录、配置目录与站点保存接口。 依赖:Flask 测试客户端、库存文件和排程运行模型。 -逻辑:库存快照来自库存文件;没有库存文件的失败 RPA 运行也必须出现在导出记录中。 +逻辑:请求打到 /api/admin/freight-rpa/;快照来自在手文件,失败排程即使没有文件也出现在导出记录中。 """ from __future__ import annotations @@ -12,8 +12,8 @@ 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.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, User +from app.models import FreightRpaSource, FreightRpaProfile from app.services.shipping_notice.order_schema import service as order_schema_service from tests.conftest import parse_api_data, parse_api_error @@ -39,8 +39,8 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p _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', + file_record = FreightRpaOnhandReportFile( + onhand_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', ) @@ -57,23 +57,23 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p )) db.session.commit() - for path in ('/api/admin/shipping-notice/snapshots', '/api/admin/shipping-notice/export-records'): + for path in ('/api/admin/freight-rpa/onhand/snapshots', '/api/admin/freight-rpa/onhand/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')) + snapshots = client.get('/api/admin/freight-rpa/onhand/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')) + downloaded = client.get('/api/admin/freight-rpa/onhand/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')) + exports = client.get('/api/admin/freight-rpa/onhand/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') @@ -104,7 +104,7 @@ def test_inventory_configuration_catalog_is_admin_only_and_backend_controlled(ap }], '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' + path = '/api/admin/freight-rpa/onhand/configuration-catalog' forbidden = client.get(path, headers=_headers('inventory-user', 'user')) assert forbidden.status_code == 403 @@ -128,8 +128,8 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app 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', + '/api/admin/freight-rpa/onhand/routing-fields', + '/api/admin/freight-rpa/onhand/configuration-catalog', ): response = client.get(path, headers=_headers('inventory-admin', 'admin')) assert response.status_code == 200 @@ -143,7 +143,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - profile = ShippingRpaProfile( + profile = FreightRpaProfile( 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, ) @@ -162,7 +162,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m }, 'query_parameters_json': [], } - created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin')) + created = client.post('/api/admin/freight-rpa/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 @@ -171,12 +171,12 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']} activation = client.post( - f"/api/admin/shipping-notice/sources/{source['id']}/activate", + f"/api/admin/freight-rpa/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['code'] == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED' assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template'] @@ -185,25 +185,25 @@ def test_latest_inventory_configuration_test_is_admin_only(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - profile = ShippingRpaProfile( + profile = FreightRpaProfile( profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs', login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True, ) db.session.add(profile) - source = ShippingInventorySource( + # s18 起站点行不再承载报表路径/查询条件;本用例只验证权限与空 envelope,无需配置行。 + source = FreightRpaSource( source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs', rpa_profile=profile, 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=[], enabled=False, + enabled=False, ) db.session.add(source) db.session.commit() source_id = source.id - forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest') + forbidden = client.get(f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest') assert forbidden.status_code in {401, 403} response = client.get( - f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest', + f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest', headers=_headers('inventory-admin', 'admin'), ) assert response.status_code == 200 diff --git a/backend/tests/test_admin_shipping_receipt_config.py b/backend/tests/test_admin_shipping_receipt_config.py index f4560ad6..9de04668 100644 --- a/backend/tests/test_admin_shipping_receipt_config.py +++ b/backend/tests/test_admin_shipping_receipt_config.py @@ -1,16 +1,16 @@ """ 收料报表配置管理接口测试。 -用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。 +用途:验证站点内独立入站报表配置的权限、DBS/Crane 规则及不可影响在手配置的边界。 依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。 -逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。 +逻辑:请求打到 /api/admin/freight-rpa/sources//inbound-report-config;保存只更新入站配置并留存前后快照审计。 """ from __future__ import annotations import pytest -from app.models import ShippingAuditEvent, ShippingInventorySource, User +from app.models import ShippingAuditEvent, FreightRpaSource, User from tests.conftest import parse_api_data, parse_api_error @@ -49,21 +49,23 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id + # s18 起在手报表路径/查询条件归 onhand_report_config 配置行,站点行不再承载。 + onhand_config = source.onhand_report_config inventory_before = { - 'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json), + 'path': dict(onhand_config.report_path_json), 'parameters': list(onhand_config.query_parameters_json), 'config_version': source.config_version, } forbidden = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json=_dbs_payload(), headers=_headers('receipt-user', 'user'), ) assert forbidden.status_code == 403 response = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -74,13 +76,14 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): assert config['report_path_json']['report_group'] == 'Inbound' with app.app_context(): - source = ShippingInventorySource.query.get(source_id) - # 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。 - assert source.report_path_json == inventory_before['path'] - assert source.query_parameters_json == inventory_before['parameters'] + source = FreightRpaSource.query.get(source_id) + # 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义(s18 起读配置行)。 + onhand_config = source.onhand_report_config + assert onhand_config.report_path_json == inventory_before['path'] + assert onhand_config.query_parameters_json == inventory_before['parameters'] assert source.config_version == inventory_before['config_version'] audit = ShippingAuditEvent.query.filter_by( - event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id), + event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id), ).one() assert audit.before_snapshot_json is None assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02'] @@ -91,17 +94,18 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() dbs_id = dbs.id from app import db crane_profile = dbs.rpa_profile.__class__( profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane', login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, ) - crane_source = ShippingInventorySource( + # s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。 + crane_source = FreightRpaSource( source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane', rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', - report_path_json={}, query_parameters_json=[], enabled=False, + enabled=False, ) db.session.add(crane_source) db.session.commit() @@ -110,7 +114,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c invalid_date = _dbs_payload() invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=invalid_date, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 @@ -119,7 +123,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c invalid_selector = _dbs_payload() invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=invalid_selector, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 @@ -129,7 +133,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c missing_warehouse = _dbs_payload() missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=missing_warehouse, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -139,7 +143,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c empty_warehouse = _dbs_payload() empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=empty_warehouse, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -151,7 +155,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c 'query_parameters_json': [], } response = client.put( - f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config', json=invalid_crane, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 @@ -161,9 +165,9 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c def _create_parsing_profile(profile_code: str, *, status: str, purpose: str): """创建入站/在手解析 Profile 种子;定义仅用于绑定校验,不参与解析。""" from app import db - from app.models import ShippingInventoryParsingProfile + from app.models import FreightRpaParsingProfile - profile = ShippingInventoryParsingProfile( + profile = FreightRpaParsingProfile( purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则', version=1, status=status, file_format='xlsx', definition_json={'sheet_name': 'Movement', 'header_row_index': 1, @@ -181,14 +185,14 @@ def test_receipt_config_binds_published_inbound_profile(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id profile = _create_parsing_profile('CRANE_MOVE_STD', status='published', purpose='inbound') profile_id = profile.id payload = {**_dbs_payload(), 'parsing_profile_id': profile_id} response = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json=payload, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -200,7 +204,7 @@ def test_receipt_config_binds_published_inbound_profile(app, client): from app.models import ShippingAuditEvent audit = ShippingAuditEvent.query.filter_by( - event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id), + event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id), ).order_by(ShippingAuditEvent.id.desc()).first() assert audit.metadata_json['parsing_profile_id'] == profile_id @@ -210,7 +214,7 @@ def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id draft = _create_parsing_profile('MOVE_DRAFT', status='draft', purpose='inbound') onhand_profile = _create_parsing_profile('INV_PUBLISHED', status='published', purpose='onhand') @@ -218,7 +222,7 @@ def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client): for profile_id in cases: response = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json={**_dbs_payload(), 'parsing_profile_id': profile_id}, headers=_headers('receipt-admin', 'admin'), ) @@ -232,20 +236,20 @@ def test_receipt_config_empty_profile_id_unbinds(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id profile = _create_parsing_profile('MOVE_UNBIND', status='published', purpose='inbound') profile_id = profile.id bound = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json={**_dbs_payload(), 'parsing_profile_id': profile_id}, headers=_headers('receipt-admin', 'admin'), ) assert bound.status_code == 200 unbound = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json={**_dbs_payload(), 'parsing_profile_id': None}, headers=_headers('receipt-admin', 'admin'), ) @@ -260,15 +264,16 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): with app.app_context(): _create_users() from app import db - dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() crane_profile = dbs.rpa_profile.__class__( profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane', login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, ) - crane_source = ShippingInventorySource( + # s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。 + crane_source = FreightRpaSource( source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane', rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', - report_path_json={}, query_parameters_json=[], enabled=False, + enabled=False, ) db.session.add(crane_source) db.session.commit() @@ -279,7 +284,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): 'query_parameters_json': [], } response = client.put( - f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config', json=default_query, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -289,7 +294,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): {'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False}, ]} rejected = client.put( - f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config', json=configured, headers=_headers('receipt-admin', 'admin'), ) assert rejected.status_code == 400 @@ -299,22 +304,22 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): def test_retire_rejects_profile_bound_by_receipt_report_config(app): """绑定收料报表配置的 published 解析 Profile 退役必须被拒(退役守卫补查)。 - 背景:retire 此前只核查库存源(ShippingInventorySource)绑定,遗漏了 - 收料报表配置(ShippingReceiptReportConfig.parsing_profile_id)——入站文件 + 背景:retire 此前只核查库存源(FreightRpaSource)绑定,遗漏了 + 收料报表配置(FreightRpaInboundReportConfig.parsing_profile_id)——入站文件 解析链会因规则退役静默失去规则。守卫补查后两者任一绑定都返回 - SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED。 + SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED。 """ from app import db - from app.models import ShippingReceiptReportConfig - from app.services.shipping_notice import inventory_parsing_profile + from app.models import FreightRpaInboundReportConfig + from app.services.shipping_notice import onhand_parsing_profile app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() profile = _create_parsing_profile('MOVE_RETIRE_GUARD', status='published', purpose='inbound') - db.session.add(ShippingReceiptReportConfig( - inventory_source_id=source.id, parsing_profile_id=profile.id, + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, parsing_profile_id=profile.id, report_path_json={}, query_parameters_json=[], )) db.session.commit() @@ -322,8 +327,8 @@ def test_retire_rejects_profile_bound_by_receipt_report_config(app): # 关键断言:仅绑定收料配置(无库存源绑定)也必须拒绝退役,沿用既有错误码。 with pytest.raises(Exception) as exc_info: - inventory_parsing_profile.retire(profile_id) - assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED' + onhand_parsing_profile.retire(profile_id) + assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED' # 关键断言:被拒后 Profile 状态保持 published,不得被半退役。 - assert ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1 + assert FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1 diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index 48fc4e51..246a091e 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -197,7 +197,7 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie } monkeypatch.setattr( - 'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_inventory_file', + 'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_onhand_file', fake_upload_inventory, ) res = client.post( diff --git a/backend/tests/test_customer_resolution_rebind.py b/backend/tests/test_customer_resolution_rebind.py index d435bf3c..61732394 100644 --- a/backend/tests/test_customer_resolution_rebind.py +++ b/backend/tests/test_customer_resolution_rebind.py @@ -22,7 +22,7 @@ from app.models import ( ShippingCustomer, ShippingCustomerShadowResolution, ShippingExportArtifact, - ShippingInventoryParsingProfile, + FreightRpaParsingProfile, ShippingNotice, ShippingOrderCandidate, ShippingOrderExtraction, @@ -154,7 +154,7 @@ def _attach_ready_export_artifact(notice: ShippingNotice) -> None: from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction template = _template_row() - profile = ShippingInventoryParsingProfile( + profile = FreightRpaParsingProfile( profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published', file_format='xlsx', definition_json={}, ) diff --git a/backend/tests/test_freight_receipt_rpa_access.py b/backend/tests/test_freight_receipt_rpa_access.py index 3a15cf10..a2da6a16 100644 --- a/backend/tests/test_freight_receipt_rpa_access.py +++ b/backend/tests/test_freight_receipt_rpa_access.py @@ -10,27 +10,29 @@ def _headers(username: str, role: str) -> dict[str, str]: def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch): """排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active') other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active') db.session.add_all([recipient, other]); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64) + report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64) db.session.add(report_file); db.session.commit() file_id = report_file.id - monkeypatch.setattr('app.services.shipping_notice.receipt_report_access.file_asset_storage.get_bytes', lambda _key: b'xlsx') + # 阶段 B Task 5:inbound_report_access 改经 freight_rpa/reports.read_inbound_file_bytes 读字节, + # monkeypatch 目标随之改到存储单例本身(所有 import 方共享同一实例,补丁全链路生效)。 + monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'xlsx') - allowed = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user')) - denied = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user')) + allowed = client.get(f'/api/workspace/inbound-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user')) + denied = client.get(f'/api/workspace/inbound-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user')) assert allowed.status_code == 200 assert allowed.data == b'xlsx' assert denied.status_code == 403 @@ -39,62 +41,62 @@ def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, def test_receipt_recipient_lists_only_own_archived_files(app, client): """接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active') other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active') db.session.add_all([recipient, other]); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id]) db.session.add_all([own_task, other_task]); db.session.flush() own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success') other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success') db.session.add_all([own_run, other_run]); db.session.flush() - own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={}) - other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={}) + own_unit = FreightRpaInboundUnitRun(schedule_run_id=own_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={}) + other_unit = FreightRpaInboundUnitRun(schedule_run_id=other_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={}) db.session.add_all([own_unit, other_unit]); db.session.flush() - own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64) - db.session.add_all([own_file, ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)]) + own_file = FreightRpaInboundReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64) + db.session.add_all([own_file, FreightRpaInboundReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)]) db.session.commit() own_file_id = own_file.id - response = client.get('/api/workspace/receipt-report-files', headers=_headers('receipt-list-user', 'user')) + response = client.get('/api/workspace/inbound-report-files', headers=_headers('receipt-list-user', 'user')) assert response.status_code == 200 items = response.get_json()['data']['items'] # 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。 assert [item['id'] for item in items] == [own_file_id] assert 'storage_key' not in items[0] - assert items[0]['download_url'].endswith(f'/receipt-report-files/{own_file_id}/download') + assert items[0]['download_url'].endswith(f'/inbound-report-files/{own_file_id}/download') def test_receipt_file_list_filters_before_applying_limit(app): """其他人的新文件再多,也不能挤掉接收人较早的可见归档。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User - from app.services.shipping_notice.receipt_report_access import list_receipt_report_files + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User + from app.services.shipping_notice.inbound_report_access import list_receipt_report_files with app.app_context(): recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active') other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active') db.session.add_all([recipient, other]); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id]) db.session.add_all([own_task, other_task]); db.session.flush() own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success') other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success') db.session.add_all([own_run, other_run]); db.session.flush() - own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={}) - other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={}) + own_unit = FreightRpaInboundUnitRun(schedule_run_id=own_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={}) + other_unit = FreightRpaInboundUnitRun(schedule_run_id=other_run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={}) db.session.add_all([own_unit, other_unit]); db.session.flush() - own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64) + own_file = FreightRpaInboundReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64) db.session.add(own_file); db.session.flush() for index in range(3): - db.session.add(ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64)) + db.session.add(FreightRpaInboundReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64)) db.session.commit() items = list_receipt_report_files(recipient, limit=1) @@ -106,26 +108,26 @@ def test_receipt_file_list_filters_before_applying_limit(app): def test_admin_can_resend_without_reexporting(app, client, monkeypatch): """管理员重发只调用文件投递,不创建 RPA 单元或 trigger。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id]) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64) + report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64) db.session.add(report_file); db.session.commit() file_id = report_file.id calls = [] monkeypatch.setattr('app.api.schedule.runs.deliver_inbound_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0}) - response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin')) + response = client.post(f'/api/admin/inbound-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin')) assert response.status_code == 200 assert calls == [(file_id, True)] @@ -133,27 +135,27 @@ def test_admin_can_resend_without_reexporting(app, client, monkeypatch): def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch): """失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed') db.session.add(run); db.session.flush() - failed = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []}) + failed = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []}) db.session.add(failed); db.session.commit() failed_id = failed.id captured = [] monkeypatch.setattr('app.api.schedule.runs.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json') - response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin')) + response = client.post(f'/api/admin/inbound-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin')) assert response.status_code == 200 with app.app_context(): - retry = ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=failed_id).one() + retry = FreightRpaInboundUnitRun.query.filter_by(retry_of_id=failed_id).one() assert retry.status == 'awaiting_rpa' assert retry.callback_id != 'receipt-failed' assert captured and captured[0][1][0]['callback_id'] == retry.callback_id @@ -162,24 +164,24 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client): """管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={}) db.session.add(unit); db.session.commit() unit_id = unit.id - response = client.get('/api/admin/receipt-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin')) + response = client.get('/api/admin/inbound-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin')) assert response.status_code == 200 assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id] with app.app_context(): - assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_units_listed').count() == 1 + assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_units_listed').count() == 1 diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index b422e9c0..491aec93 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -7,17 +7,43 @@ import hashlib import pytest +def _register_legacy_terminal_handler(unit): + """注册测试用 inbound 事实处理函数,复刻拆分前的终态收尾(桥 + 证据同步 + finalize)。 + + 核心逻辑:Task 6 起 ingest_inbound_callback 不再收 on_terminal 钩子,本文件 + 的桥接/进度断言改经 register_report_handler 注入留守的 + inbound_report_storage._finish_inbound_callback_terminal(Task 7 将平移为 + in_transit_transfer 的 handle_inbound_report);fact → 旧钩子实参逐字段换算, + 行为与拆分前逐点一致。 + """ + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.inbound_report_storage import _finish_inbound_callback_terminal + + def _handle(fact) -> None: + _finish_inbound_callback_terminal( + unit, + ok=fact.ok, + file_no=str(fact.file_id) if fact.file_id is not None else None, + file_sha256=fact.sha256, + error_code=fact.error_code, + error_message=fact.error_message, + ) + + register_report_handler("inbound", _handle) + return _handle + + def test_receipt_unit_processing_and_batch_progress(app): """开始导出标记 processing;每笔完成后 batch-progress 抬升排程计数。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_finalize import ( + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import ( mark_receipt_unit_processing, report_receipt_batch_progress, ) with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask( schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', @@ -31,8 +57,8 @@ def test_receipt_unit_processing_and_batch_progress(app): ) db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( - schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-live-progress', status='awaiting_rpa', config_snapshot_json={}, ) @@ -46,7 +72,7 @@ def test_receipt_unit_processing_and_batch_progress(app): }) assert marked['updated'] is True db.session.expire_all() - assert db.session.get(ShippingReceiptRpaUnitRun, unit.id).status == 'processing' + assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'processing' progressed = report_receipt_batch_progress({ 'schema_version': 'freight_rpa.inbound.v1', @@ -66,11 +92,11 @@ def test_receipt_unit_processing_and_batch_progress(app): def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): """success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask( schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', @@ -84,8 +110,8 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): ) db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( - schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-progress', status='awaiting_rpa', config_snapshot_json={}, ) @@ -99,6 +125,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): 'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None, ) + _register_legacy_terminal_handler(unit) payload = { 'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, @@ -117,39 +144,40 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch): """同一 callback 重放只归档一条收料文件,绝不创建库存快照。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit); db.session.commit() monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes') monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None) + _register_legacy_terminal_handler(unit) payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()} first = ingest_receipt_callback(payload) second = ingest_receipt_callback(payload) assert first['file_id'] == second['file_id'] - assert ShippingInventoryFile.query.count() == 0 + assert FreightRpaOnhandReportFile.query.count() == 0 def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch): """收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun + from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit) transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E', business_date='2026-09-17', status='preparing_files', trigger_type='manual') db.session.add(transfer_run); db.session.flush() @@ -157,6 +185,7 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch): db.session.add(job); db.session.commit() monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes') monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None) + _register_legacy_terminal_handler(unit) payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()} result = ingest_receipt_callback(payload) @@ -170,21 +199,22 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch): def test_ingest_failed_advance_is_durable(app): """failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun + from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit) transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E-FAIL', business_date='2026-09-17', status='preparing_files', trigger_type='manual') db.session.add(transfer_run); db.session.flush() job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback') db.session.add(job); db.session.commit() + _register_legacy_terminal_handler(unit) payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'} result = ingest_receipt_callback(payload) @@ -221,11 +251,11 @@ def test_ingest_empty_persists_no_receipt_data(app): [断言意图] 单元 status=empty 且 error_code/error_message 为 no_receipt_data,供管理端展示跳过原因。 """ from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask( schedule_no='SCH-RECEIPT-EMPTY', name='Receipt empty', @@ -239,9 +269,9 @@ def test_ingest_empty_persists_no_receipt_data(app): run = ScheduleRun(run_no='RUN-RECEIPT-EMPTY', schedule_task_id=task.id, status='running') db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( + unit = FreightRpaInboundUnitRun( schedule_run_id=run.id, - inventory_source_id=source.id, + source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', @@ -251,6 +281,7 @@ def test_ingest_empty_persists_no_receipt_data(app): ) db.session.add(unit) db.session.commit() + _register_legacy_terminal_handler(unit) result = ingest_receipt_callback({ 'schema_version': 'freight_rpa.inbound.v1', @@ -261,7 +292,7 @@ def test_ingest_empty_persists_no_receipt_data(app): }) assert result['status'] == 'empty' db.session.expire_all() - saved = db.session.get(ShippingReceiptRpaUnitRun, unit.id) + saved = db.session.get(FreightRpaInboundUnitRun, unit.id) assert saved is not None assert saved.status == 'empty' assert saved.error_code == 'no_receipt_data' diff --git a/backend/tests/test_freight_receipt_rpa_notifications.py b/backend/tests/test_freight_receipt_rpa_notifications.py index 6e67e56e..966b7b48 100644 --- a/backend/tests/test_freight_receipt_rpa_notifications.py +++ b/backend/tests/test_freight_receipt_rpa_notifications.py @@ -7,22 +7,22 @@ def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipient """同一文件只向排程接收人发送一次,重放不会重复调用企微。""" from app import db from app.models import ( - ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, User, + ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, User, ) from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file with app.app_context(): recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user') db.session.add(recipient); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64) + report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64) db.session.add(report_file); db.session.commit() monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.get_bytes', lambda _key: b'receipt-data') monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.upload_wecom_temp_media', lambda *_args: 'media-1') @@ -38,28 +38,28 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch): """企微投递失败也必须保留接收人、时间、失败码和文件身份审计。""" from app import db from app.models import ( - ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, User, + ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, User, ) from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file with app.app_context(): recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active') db.session.add(recipient); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64) + report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64) db.session.add(report_file); db.session.commit() outcome = deliver_inbound_file(report_file.id) assert outcome['failed_count'] == 1 - audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one() + audit = ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_file_notification_attempted', aggregate_id=str(report_file.id)).one() # 审计结果遵循统一枚举;业务投递状态仍保留为 failed。 assert audit.result == 'failure' assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND' @@ -68,18 +68,18 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch): def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True): """构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。""" from app.models import ( - ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None) db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64) + report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64) db.session.add(report_file) db.session.commit() return task, run, report_file @@ -115,7 +115,7 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_ """收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。""" from app import db from app.models import User - from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete with app.app_context(): app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives') @@ -157,23 +157,23 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path): from app import db from app.models import ( - ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete with app.app_context(): app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel') - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True}) db.session.add(run); db.session.flush() - unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={}) - unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={}) - unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={}) + unit_ok = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={}) + unit_empty = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={}) + unit_fail = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={}) db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush() - db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64)) + db.session.add(FreightRpaInboundReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64)) db.session.commit() outcome = finalize_receipt_schedule_run_if_complete(run.id) diff --git a/backend/tests/test_freight_receipt_rpa_schedule.py b/backend/tests/test_freight_receipt_rpa_schedule.py index d517864f..10b2800b 100644 --- a/backend/tests/test_freight_receipt_rpa_schedule.py +++ b/backend/tests/test_freight_receipt_rpa_schedule.py @@ -8,26 +8,27 @@ from datetime import datetime, timedelta def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, monkeypatch): """一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile - from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaProfile + from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule with app.app_context(): - dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - crane_profile = ShippingRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'}) - crane = ShippingInventorySource( + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + crane_profile = FreightRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'}) + # s18 起站点行不再承载解析绑定/报表路径/查询条件;入站排程只读 FreightRpaInboundReportConfig。 + crane = FreightRpaSource( source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile, - parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, - warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True, + excel_template=dbs.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', enabled=True, ) - empty_dbs = ShippingInventorySource( + empty_dbs = FreightRpaSource( source_code='DSV360_EMPTY_QP', display_name='Empty QP', connector_type='dbs', rpa_profile=dbs.rpa_profile, - parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, - warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', report_path_json={}, query_parameters_json=[], enabled=True, + excel_template=dbs.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', enabled=True, ) db.session.add_all([ crane, empty_dbs, - ShippingReceiptReportConfig( - inventory_source_id=dbs.id, + FreightRpaInboundReportConfig( + source_id=dbs.id, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', @@ -39,11 +40,11 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, ]) db.session.flush() db.session.add_all([ - ShippingReceiptReportConfig( - inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[], + FreightRpaInboundReportConfig( + source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[], ), - ShippingReceiptReportConfig( - inventory_source_id=empty_dbs.id, + FreightRpaInboundReportConfig( + source_id=empty_dbs.id, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', @@ -62,7 +63,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, captured = {} monkeypatch.setattr( - 'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger', + 'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json', ) total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run) @@ -94,14 +95,14 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa """收料 Worker 离线时排程立即 failed,不写 trigger、不落 unit。""" from app import db from app.core.errors import ServiceUnavailableError - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - db.session.add(ShippingReceiptReportConfig( - inventory_source_id=source.id, + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', @@ -121,7 +122,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa trigger_calls = [] monkeypatch.setattr( - 'app.services.schedule.freight_inbound_rpa_job.assert_receipt_rpa_worker_ready', + 'app.services.schedule.freight_rpa_inbound_job.assert_receipt_rpa_worker_ready', lambda: (_ for _ in ()).throw(ServiceUnavailableError( RPA_WORKER_OFFLINE_MESSAGE, code='RPA.WORKER_OFFLINE', @@ -129,7 +130,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa )), ) monkeypatch.setattr( - 'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger', + 'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger', lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json', ) @@ -140,7 +141,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa assert details == [] assert errors == ['receipt worker offline'] assert trigger_calls == [] - assert ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0 + assert FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0 failed_log = next(log for log in logs if isinstance(log, dict) and log.get('status') == 'failed') assert failed_log['detail'].get('reasons') == ['no_worker_heartbeat'] assert not any( @@ -152,19 +153,19 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa def test_receipt_schedule_options_only_return_enabled_configured_sources(app): """动态排程选项只暴露库存站点已启用且已配置收料的站点。""" from app import db - from app.models import ShippingInventorySource, ShippingReceiptReportConfig + from app.models import FreightRpaSource, FreightRpaInboundReportConfig from app.services.schedule.job_options import list_job_options with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - db.session.add(ShippingReceiptReportConfig( - inventory_source_id=source.id, + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}], )) db.session.commit() - options = list_job_options('shipping_receipt_sources') + options = list_job_options('freight_rpa_inbound_sources') assert any(item['value'] == source.source_code for item in options) @@ -172,17 +173,17 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app): def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app): """无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_finalize import recover_stale_receipt_rpa_schedule_runs + from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_receipt_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True}) db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit); db.session.commit() assert recover_stale_receipt_rpa_schedule_runs(task) == 1 @@ -191,8 +192,8 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app): assert run.status == 'failed' assert unit.status == 'failed' assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT' - assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0 - assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1 + assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0 + assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1 def test_receipt_trigger_is_published_atomically(app, tmp_path): @@ -210,17 +211,17 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path): def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app): """全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True}) db.session.add(run); db.session.flush() - db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={})) + db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={})) db.session.commit() # [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径); @@ -234,19 +235,19 @@ def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app): def test_receipt_recovery_respects_fresh_activity_of_long_batch(app): """长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True}) db.session.add(run); db.session.flush() # 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚) - db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30))) - db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45))) + db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30))) + db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45))) db.session.commit() # [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s—— @@ -273,27 +274,27 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): def test_stale_orphan_inbound_units_are_failed_by_full_scan(app): """按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。""" from app import db - from app.models import ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units + from app.models import ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() # 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后 # 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。 - stale_queued = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', + stale_queued = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type='dbs', callback_id='inbound-orphan-queued', status='queued', config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5), ) - stale_processing = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', + stale_processing = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type='dbs', callback_id='inbound-orphan-processing', status='processing', config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=6), started_at=datetime.utcnow() - timedelta(minutes=5), ) - fresh_processing = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', + fresh_processing = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type='dbs', callback_id='inbound-orphan-fresh', status='processing', config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(seconds=45), started_at=datetime.utcnow() - timedelta(seconds=30), @@ -315,10 +316,10 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app): assert stale_queued.finished_at is not None assert stale_processing.status == 'failed' assert fresh_processing.status == 'processing' - assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0 + assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0 # [断言意图] 审计须含失败结果与 before/after 快照——与 run 级回收同语义由测试锁定。 timeout_event = ShippingAuditEvent.query.filter_by( - event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(stale_queued.id), + event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(stale_queued.id), ).one() assert timeout_event.result == 'failure' assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed' diff --git a/backend/tests/test_freight_rpa_batch_s_grep_gate.py b/backend/tests/test_freight_rpa_batch_s_grep_gate.py new file mode 100644 index 00000000..aa93f81e --- /dev/null +++ b/backend/tests/test_freight_rpa_batch_s_grep_gate.py @@ -0,0 +1,292 @@ +""" +tests/test_freight_rpa_batch_s_grep_gate.py + +用途:批次 S 生产路径 grep 门禁。白名单外的旧表名、旧 admin inventory 路径、 + ShippingInventory 类名(含 camelCase 助手)、outbound_upload 必须为零。 +依赖:backend/app 与 frontend/src 源码(只读)。不读 docs/superpowers,不读历史迁移。 +逻辑:pytest 调用本文件扫描器。ALLOWED_TOKENS 只有两个 HTTP 工具名。 + 四个任务/行级类名已改为 Onhand,旧名整词现在失败。 + 缩写约束名因下划线前缀不是整词。履约 shipment、movement、中文「库存」不在禁词正则里。 +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.pure_unit + +REPO = Path(__file__).resolve().parents[2] +SCAN_ROOTS = ( + REPO / "backend" / "app", + REPO / "frontend" / "src", +) +SKIP_PARTS = frozenset({ + "node_modules", + "__pycache__", + ".venv", + "dist", + "contract_payment", + "contract-payment", +}) +SOURCE_SUFFIXES = frozenset({".py", ".ts", ".vue", ".js", ".json", ".yml", ".yaml"}) + +# 词边界整词。函数名 list_shipping_inventory_sources、缩写约束 uq_shipping_inventory_* +# 前面还有下划线,不是独立表名,不会命中。 +PREFIX_TOKEN_RE = re.compile(r"\bshipping_(?:inventory|receipt)_[a-z0-9_]+\b") +# 29 表里不以 shipping_inventory_ / shipping_receipt_ 开头、但已改名的表。 +EXTRA_RETIRED_TABLES = ( + "shipping_rpa_profiles", + "shipping_task_inventory_rpa_attempts", + "shipping_task_inventory_links", + "shipping_temporary_inventory_sessions", + "shipping_notice_line_inventory_matches", + "shipping_notice_inventory_verifications", + "shipping_notice_inventory_verification_lines", +) +EXTRA_TABLE_RE = re.compile(r"\b(?:" + "|".join(EXTRA_RETIRED_TABLES) + r")\b") +# 无前导词边界:getShippingInventory* / listShippingInventory* / shippingInventory* 都要命中。 +CLASS_RE = re.compile(r"(?i)shippinginventory[a-z0-9_]*") +PATH_RE = re.compile(r"/api/admin/shipping-notice/inventory-") +UPLOAD_RE = re.compile(r"\boutbound_upload\b") +EXPLANATION_RE = re.compile(r"retired|legacy|废弃|退役|曾用|旧名|旧表|原表|原名|已改名") +RETIRED_CLASS_RE = re.compile( + r"\b(?:ShippingTaskInventoryLink|ShippingTaskInventoryRpaAttempt|" + r"ShippingTemporaryInventorySession|ShippingNoticeLineInventoryMatch)\b" +) + +# 只放行两个 HTTP 工具名。movement / shipment_* 不靠把模块名塞进这里。 +ALLOWED_TOKENS = frozenset({ + "ensure_inventory", + "upload_inventory_file", +}) + +ONHAND_CLASS_FILES = ( + REPO / "backend" / "app" / "models" / "shipping.py", + REPO / "backend" / "app" / "models" / "shipping_onhand_task_rpa_attempts.py", + REPO / "backend" / "app" / "models" / "shipping_temporary_onhand.py", + REPO / "backend" / "app" / "models" / "shipping_notice_line_onhand_match.py", +) + + +def _is_allowed(token: str) -> bool: + """两个 HTTP 工具名,以及 movement / shipment 履约词。""" + if token in ALLOWED_TOKENS: + return True + lowered = token.lower() + if lowered == "movement" or lowered.startswith("movement_") or "_movement" in lowered: + return True + if ( + lowered.startswith("shipment_") + or "_shipment_" in lowered + or lowered.endswith("_shipment") + or lowered == "generate_shipment_excel" + ): + return True + return False + + +def _is_explaining_comment(line: str) -> bool: + """整行是注释,并且在解释退役名,才从门禁里放过。""" + stripped = line.lstrip() + if not stripped.startswith(("#", "//", "*", "/*", "
- +
- +
@@ -197,178 +197,178 @@ @@ -382,30 +382,30 @@ - {{ t('admin.shippingInventory.enabled') }} + {{ t('admin.freightRpa.enabled') }} {{ sourceDirty - ? t('admin.shippingInventory.saveBeforeReadinessAction') + ? t('admin.freightRpa.saveBeforeReadinessAction') : (!source.enabled && firstBlockingCheck - ? t('admin.shippingInventory.readinessBlockedBy', { requirement: t(`admin.shippingInventory.activationRequirement.${firstBlockingCheck.code}`) }) - : t('admin.shippingInventory.sourceEnabledToggleHint')) + ? t('admin.freightRpa.readinessBlockedBy', { requirement: t(`admin.freightRpa.activationRequirement.${firstBlockingCheck.code}`) }) + : t('admin.freightRpa.sourceEnabledToggleHint')) }}
- {{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }} - {{ t('admin.shippingInventory.publish') }} - {{ t('admin.shippingInventory.retire') }} - {{ t('admin.shippingInventory.publishTemplate') }} - {{ t('admin.shippingInventory.createTemplateVersion') }} - {{ t('admin.shippingInventory.cloneTemplate') }} - {{ t('admin.shippingInventory.retireTemplate') }} - {{ t('admin.shippingInventory.publishProfile') }} - {{ t('admin.shippingInventory.retireProfile') }} - {{ t('admin.shippingInventory.retireInventoryField') }} + {{ saving ? t('admin.freightRpa.saving') : t('admin.save') }} + {{ t('admin.freightRpa.publish') }} + {{ t('admin.freightRpa.retire') }} + {{ t('admin.freightRpa.publishTemplate') }} + {{ t('admin.freightRpa.createTemplateVersion') }} + {{ t('admin.freightRpa.cloneTemplate') }} + {{ t('admin.freightRpa.retireTemplate') }} + {{ t('admin.freightRpa.publishProfile') }} + {{ t('admin.freightRpa.retireProfile') }} + {{ t('admin.freightRpa.retireInventoryField') }} {{ t('admin.delete') }} {{ t('admin.cancel') }}
@@ -433,12 +433,12 @@ :before-close="closeTemplateCloneDialog" >
- - -
{{ t('admin.cancel') }}{{ templateClone.saving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.cloneTemplateConfirm') }}
+ + +
{{ t('admin.cancel') }}{{ templateClone.saving ? t('admin.freightRpa.saving') : t('admin.freightRpa.cloneTemplateConfirm') }}
- - -
{{ t('admin.cancel') }}{{ bulkBinding.saving ? t('admin.shippingInventory.saving') : t('admin.shippingInventory.bulkBindParsingProfile') }}
+ + +
{{ t('admin.cancel') }}{{ bulkBinding.saving ? t('admin.freightRpa.saving') : t('admin.freightRpa.bulkBindParsingProfile') }}
-
{{ allFilteredBatchValidationSourcesSelected ? t('admin.shippingInventory.batchValidationClearFiltered') : t('admin.shippingInventory.batchValidationSelectFiltered') }}{{ t('admin.shippingInventory.batchValidationSelected', { count: batchValidation.sourceIds.length }) }}
+
{{ allFilteredBatchValidationSourcesSelected ? t('admin.freightRpa.batchValidationClearFiltered') : t('admin.freightRpa.batchValidationSelectFiltered') }}{{ t('admin.freightRpa.batchValidationSelected', { count: batchValidation.sourceIds.length }) }}
{{ item.display_name || item.source_code }}{{ item.source_code }} · {{ connectionName(item.source_code) }} -

{{ t('admin.shippingInventory.batchValidationNoSites') }}

+

{{ t('admin.freightRpa.batchValidationNoSites') }}

-
{{ t('admin.cancel') }}{{ batchValidation.saving ? t('admin.shippingInventory.configurationTestRunning') : t('admin.shippingInventory.batchValidation') }}
+
{{ t('admin.cancel') }}{{ batchValidation.saving ? t('admin.freightRpa.configurationTestRunning') : t('admin.freightRpa.batchValidation') }}
-
{{ t(`admin.shippingInventory.batchValidationStatus.${batchValidation.result.status}`) }}{{ t('admin.shippingInventory.batchValidationProgress', batchValidation.result) }}
{{ batchCompletedCount }} / {{ batchValidation.result.total_count }}
+
{{ t(`admin.freightRpa.batchValidationStatus.${batchValidation.result.status}`) }}{{ t('admin.freightRpa.batchValidationProgress', batchValidation.result) }}
{{ batchCompletedCount }} / {{ batchValidation.result.total_count }}
-
-
{{ sourceTitleById(run.inventory_source_id) }}{{ t(`admin.shippingInventory.configurationTestStage.${run.stage}`) }}
{{ run.error_message }}

{{ t('admin.shippingInventory.batchValidationNoRuns') }}

-
{{ t('admin.shippingInventory.retryFailedValidation') }}{{ t('admin.close') }}
+
+
{{ sourceTitleById(run.source_id) }}{{ t(`admin.freightRpa.configurationTestStage.${run.stage}`) }}
{{ run.error_message }}

{{ t('admin.freightRpa.batchValidationNoRuns') }}

+
{{ t('admin.freightRpa.retryFailedValidation') }}{{ t('admin.close') }}
@@ -537,55 +537,55 @@ import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; import PaginationBar from '@/shared/components/PaginationBar.vue'; import { useMessage } from '@/shared/composables/useMessage'; import { - createShippingInventoryField, - deleteShippingInventoryExternalMapping, - deleteShippingInventoryField, + createShippingOnhandField, + deleteShippingOnhandExternalMapping, + deleteShippingOnhandField, deleteShippingExcelTemplate, - deleteShippingInventoryParsingProfile, - deleteShippingInventoryRule, - deleteShippingInventorySource, - activateShippingInventorySource, - deactivateShippingInventorySource, + deleteShippingOnhandParsingProfile, + deleteShippingOnhandRule, + deleteShippingOnhandSource, + activateShippingOnhandSource, + deactivateShippingOnhandSource, deleteShippingRpaProfile, - getShippingInventoryConfig, - getShippingInventoryFields, - getShippingInventoryConfigurationCatalog, - getShippingInventoryRoutingFields, + getShippingOnhandConfig, + getShippingOnhandFields, + getShippingOnhandConfigurationCatalog, + getShippingOnhandRoutingFields, createShippingExcelTemplate, createShippingExcelTemplateVersion, cloneShippingExcelTemplate, getShippingExcelTemplateLayout, - createShippingInventoryStructureAnalysis, - createShippingInventoryParsingDraftFromAnalysis, + createShippingOnhandStructureAnalysis, + createShippingOnhandParsingDraftFromAnalysis, fetchMovementFields, - previewShippingInventorySampleReplacement, + previewShippingOnhandSampleReplacement, createShippingParsingDraftFromTemporarySession, - adoptShippingInventoryParsingProfile, - listShippingTemporaryInventorySessions, - startShippingInventoryValidationBatch, - getShippingInventoryValidationBatch, - getLatestActiveShippingInventoryValidationBatch, - retryFailedShippingInventoryValidationBatch, - downloadShippingInventorySnapshot, + adoptShippingOnhandParsingProfile, + listShippingTemporaryOnhandSessions, + startShippingOnhandValidationBatch, + getShippingOnhandValidationBatch, + getLatestActiveShippingOnhandValidationBatch, + retryFailedShippingOnhandValidationBatch, + downloadShippingOnhandSnapshot, updateShippingExcelTemplate, publishShippingExcelTemplate, retireShippingExcelTemplate, - retireShippingInventoryField, - publishShippingInventoryParsingProfile, - retireShippingInventoryParsingProfile, - publishShippingInventoryRule, - retireShippingInventoryRule, - saveShippingInventoryExternalMapping, - updateShippingInventoryField, - saveShippingInventoryRule, - saveShippingInventorySource, + retireShippingOnhandField, + publishShippingOnhandParsingProfile, + retireShippingOnhandParsingProfile, + publishShippingOnhandRule, + retireShippingOnhandRule, + saveShippingOnhandExternalMapping, + updateShippingOnhandField, + saveShippingOnhandRule, + saveShippingOnhandSource, saveShippingRpaProfile, - bulkBindShippingInventorySourceParsingProfile, + bulkBindShippingOnhandSourceParsingProfile, getShippingReceiptReportConfig, saveShippingReceiptReportConfig, } from '@/features/admin/api/admin.api'; -import type { ShippingInventoryReadinessCheck, ShippingInventoryValidationBatch } from '@/features/admin/api/admin.api'; -import { normaliseInventoryReportPath } from './shippingInventorySourceForm'; +import type { ShippingOnhandReadinessCheck, ShippingOnhandValidationBatch } from '@/features/admin/api/admin.api'; +import { normaliseInventoryReportPath } from './shippingOnhandSourceForm'; import { buildReceiptReportConfigPayload } from './receiptReportConfigForm'; import { buildMovementFieldMapping } from './movementParsingProfileForm'; @@ -597,7 +597,7 @@ type ParsingFieldMapping = { inventory_field: string; source_header: string }; type ParsingMatchKey = { order_field_id: string; inventory_field: string }; type TemplateMapping = { sheet: string; row_mode: 'header' | 'line'; start_row: number; target_column: number; source_kind: 'order_field' | 'inventory_field' | 'system_fact' | 'constant'; source_key: string; formatter: string }; type InventoryFieldForm = { display_name: string; description: string; value_type: 'text' | 'integer' | 'decimal' | 'date'; usage_type: 'match_identity' | 'inventory_quantity' | 'warehouse_identity' | 'general'; sort_order: number; status: 'active' | 'retired' }; -type SourceActivation = { ready: boolean; checks: ShippingInventoryReadinessCheck[]; missing_requirements: string[] }; +type SourceActivation = { ready: boolean; checks: ShippingOnhandReadinessCheck[]; missing_requirements: string[] }; const { t } = useI18n(); const route = useRoute(); @@ -650,14 +650,14 @@ const filenameVariableMenuOpen = ref(false); const filenameVariableActiveIndex = ref(0); const filenameVariableQuery = ref(''); const filenameVariables = [ - { key: '{business_no}', labelKey: 'admin.shippingInventory.filenameVariableBusinessNo' }, - { key: '{customer_short_code}', labelKey: 'admin.shippingInventory.filenameVariableCustomer' }, - { key: '{business_date}', labelKey: 'admin.shippingInventory.filenameVariableBusinessDate' }, - { key: '{sequence}', labelKey: 'admin.shippingInventory.filenameVariableSequence' }, - { key: '{task_no}', labelKey: 'admin.shippingInventory.filenameVariableTaskNo' }, - { key: '{source_code}', labelKey: 'admin.shippingInventory.filenameVariableSource' }, - { key: '{date}', labelKey: 'admin.shippingInventory.filenameVariableDate' }, - { key: '{ts}', labelKey: 'admin.shippingInventory.filenameVariableTimestamp' }, + { key: '{business_no}', labelKey: 'admin.freightRpa.filenameVariableBusinessNo' }, + { key: '{customer_short_code}', labelKey: 'admin.freightRpa.filenameVariableCustomer' }, + { key: '{business_date}', labelKey: 'admin.freightRpa.filenameVariableBusinessDate' }, + { key: '{sequence}', labelKey: 'admin.freightRpa.filenameVariableSequence' }, + { key: '{task_no}', labelKey: 'admin.freightRpa.filenameVariableTaskNo' }, + { key: '{source_code}', labelKey: 'admin.freightRpa.filenameVariableSource' }, + { key: '{date}', labelKey: 'admin.freightRpa.filenameVariableDate' }, + { key: '{ts}', labelKey: 'admin.freightRpa.filenameVariableTimestamp' }, ]; const filenameVariableCandidates = computed(() => { const query = filenameVariableQuery.value.toLowerCase(); @@ -702,10 +702,11 @@ const inventoryField = reactive({ display_name: '', descript const excelTemplate = reactive({ template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [] as TemplateMapping[], file: null as File | null }); const templateClone = reactive({ visible: false, template_code: '', display_name: '', saving: false }); const bulkBinding = reactive({ visible: false, sourceIds: [] as number[], profileId: 0, saving: false }); -const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingInventoryValidationBatch | null }); +const batchValidation = reactive({ visible: false, sourceIds: [] as number[], query: '', statusFilter: 'all' as 'all' | 'processing' | 'completed' | 'completed_empty' | 'failed', saving: false, result: null as ShippingOnhandValidationBatch | null }); let batchValidationTimer: number | null = null; // snapshot_ttl_seconds:管理端不再展示;保存时透传存量值。运行时过期以全局 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS 为准。 -const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation }); +// s18 起报表路径/查询条件/解析方案绑定归 onhand_report_config 配置行(站点 DTO 嵌套对象),站点头部只留连接/模板/仓库模式。 +const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, onhand_report_config: { report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], parsing_profile_id: 0 }, enabled: false, activation: { ready: false, checks: [] as ShippingOnhandReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation }); const receiptConfig = reactive({ report_path_json: { program_group: '', program_label: '', report_group: 'Inbound', report_name: '' } as Record, query_parameters_json: [] as Parameter[], parsing_profile_id: null as number | null }); const receiptConfigExists = ref(false); const receiptSectionTouched = ref(false); @@ -714,7 +715,7 @@ const inventoryPathOpen = ref(true); const receiptBaseline = ref(''); const sourceBaseline = ref(''); const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] }); -const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true }); +const mapping = reactive({ source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true }); const compatibleRoutingFields = computed(() => routingFields.value.filter((item) => item.scope === (rule.scope === 'task' ? 'header' : 'line'))); const activeInventoryFields = computed(() => inventoryFields.value.filter((item) => item.status === 'active')); const matchingInventoryFields = computed(() => activeInventoryFields.value.filter((item) => item.usage_type === 'match_identity')); @@ -730,8 +731,8 @@ const canAddParsingMatchKey = computed(() => Boolean( )); /** 库存报表配置徽标:DBS 看路径四段;Crane 无路径卡内容时看是否已绑库存解析。 */ const inventoryReportConfigExists = computed(() => { - if (source.connector_type !== 'dbs') return Number(source.parsing_profile_id) > 0; - const path = source.report_path_json || {}; + if (source.connector_type !== 'dbs') return Number(source.onhand_report_config.parsing_profile_id) > 0; + const path = source.onhand_report_config.report_path_json || {}; return ['program_group', 'program_label', 'report_group', 'report_name'] .every((key) => String((path as Record)[key] || '').trim()); }); @@ -743,48 +744,48 @@ const firstBlockingCheck = computed(() => (source.activation?.checks || []).find const sampleReplacementNotice = computed(() => { const difference = pendingSampleReplacement.value?.difference || {}; const missing = Array.isArray(difference.missing_mapped_headers) ? difference.missing_mapped_headers : []; - if (difference.file_format_changed) return t('admin.shippingInventory.sampleReplacementFileFormatChanged'); + if (difference.file_format_changed) return t('admin.freightRpa.sampleReplacementFileFormatChanged'); return missing.length - ? t('admin.shippingInventory.sampleReplacementMappingRequired', { columns: missing.join('、') }) - : t('admin.shippingInventory.sampleReplacementReady'); + ? t('admin.freightRpa.sampleReplacementMappingRequired', { columns: missing.join('、') }) + : t('admin.freightRpa.sampleReplacementReady'); }); const sampleReplacementDifferenceLines = computed(() => { const difference = pendingSampleReplacement.value?.difference || {}; const lines: string[] = []; - if (Array.isArray(difference.added_columns) && difference.added_columns.length) lines.push(t('admin.shippingInventory.sampleReplacementAddedColumns', { columns: difference.added_columns.join('、') })); - if (Array.isArray(difference.missing_columns) && difference.missing_columns.length) lines.push(t('admin.shippingInventory.sampleReplacementMissingColumns', { columns: difference.missing_columns.join('、') })); - if (difference.column_order_changed) lines.push(t('admin.shippingInventory.sampleReplacementColumnOrderChanged')); + if (Array.isArray(difference.added_columns) && difference.added_columns.length) lines.push(t('admin.freightRpa.sampleReplacementAddedColumns', { columns: difference.added_columns.join('、') })); + if (Array.isArray(difference.missing_columns) && difference.missing_columns.length) lines.push(t('admin.freightRpa.sampleReplacementMissingColumns', { columns: difference.missing_columns.join('、') })); + if (difference.column_order_changed) lines.push(t('admin.freightRpa.sampleReplacementColumnOrderChanged')); return lines; }); const operators = [ - { value: 'equals', label: t('admin.shippingInventory.operatorEquals') }, { value: 'not_equals', label: t('admin.shippingInventory.operatorNotEquals') }, - { value: 'in', label: t('admin.shippingInventory.operatorIn') }, { value: 'not_in', label: t('admin.shippingInventory.operatorNotIn') }, - { value: 'prefix', label: t('admin.shippingInventory.operatorPrefix') }, { value: 'suffix', label: t('admin.shippingInventory.operatorSuffix') }, - { value: 'contains', label: t('admin.shippingInventory.operatorContains') }, { value: 'numeric_length', label: t('admin.shippingInventory.operatorNumericLength') }, - { value: 'string_length', label: t('admin.shippingInventory.operatorStringLength') }, { value: 'is_empty', label: t('admin.shippingInventory.operatorIsEmpty') }, - { value: 'is_not_empty', label: t('admin.shippingInventory.operatorIsNotEmpty') }, + { value: 'equals', label: t('admin.freightRpa.operatorEquals') }, { value: 'not_equals', label: t('admin.freightRpa.operatorNotEquals') }, + { value: 'in', label: t('admin.freightRpa.operatorIn') }, { value: 'not_in', label: t('admin.freightRpa.operatorNotIn') }, + { value: 'prefix', label: t('admin.freightRpa.operatorPrefix') }, { value: 'suffix', label: t('admin.freightRpa.operatorSuffix') }, + { value: 'contains', label: t('admin.freightRpa.operatorContains') }, { value: 'numeric_length', label: t('admin.freightRpa.operatorNumericLength') }, + { value: 'string_length', label: t('admin.freightRpa.operatorStringLength') }, { value: 'is_empty', label: t('admin.freightRpa.operatorIsEmpty') }, + { value: 'is_not_empty', label: t('admin.freightRpa.operatorIsNotEmpty') }, ]; const tabs = computed(() => [ - { key: 'parsing' as const, group: 'inventory', labelKey: 'admin.shippingInventory.parsingProfiles', helpKey: 'admin.shippingInventory.parsingProfilesHelp', count: parsingProfiles.value.length }, - { key: 'profiles' as const, group: 'inventory', labelKey: 'admin.shippingInventory.connections', helpKey: 'admin.shippingInventory.connectionsHelp', count: profiles.value.length }, - { key: 'sources' as const, group: 'inventory', labelKey: 'admin.shippingInventory.sources', helpKey: 'admin.shippingInventory.sourcesHelp', count: sources.value.length }, - { key: 'mappings' as const, group: 'inventory', labelKey: 'admin.shippingInventory.externalMappings', helpKey: 'admin.shippingInventory.mappingsHelp', count: mappings.value.length }, - { key: 'rules' as const, group: 'inventory', labelKey: 'admin.shippingInventory.rules', helpKey: 'admin.shippingInventory.rulesHelp', count: rules.value.length }, - { key: 'templates' as const, group: 'inventory', labelKey: 'admin.shippingInventory.excelTemplates', helpKey: 'admin.shippingInventory.excelTemplatesHelp', count: excelTemplates.value.length }, - { key: 'snapshots' as const, group: 'audit', labelKey: 'admin.shippingInventory.snapshots', helpKey: 'admin.shippingInventory.snapshotsHelp', count: snapshots.value.length }, - { key: 'exports' as const, group: 'audit', labelKey: 'admin.shippingInventory.exports', helpKey: 'admin.shippingInventory.exportsHelp', count: exports.value.length }, + { key: 'parsing' as const, group: 'inventory', labelKey: 'admin.freightRpa.parsingProfiles', helpKey: 'admin.freightRpa.parsingProfilesHelp', count: parsingProfiles.value.length }, + { key: 'profiles' as const, group: 'inventory', labelKey: 'admin.freightRpa.connections', helpKey: 'admin.freightRpa.connectionsHelp', count: profiles.value.length }, + { key: 'sources' as const, group: 'inventory', labelKey: 'admin.freightRpa.sources', helpKey: 'admin.freightRpa.sourcesHelp', count: sources.value.length }, + { key: 'mappings' as const, group: 'inventory', labelKey: 'admin.freightRpa.externalMappings', helpKey: 'admin.freightRpa.mappingsHelp', count: mappings.value.length }, + { key: 'rules' as const, group: 'inventory', labelKey: 'admin.freightRpa.rules', helpKey: 'admin.freightRpa.rulesHelp', count: rules.value.length }, + { key: 'templates' as const, group: 'inventory', labelKey: 'admin.freightRpa.excelTemplates', helpKey: 'admin.freightRpa.excelTemplatesHelp', count: excelTemplates.value.length }, + { key: 'snapshots' as const, group: 'audit', labelKey: 'admin.freightRpa.snapshots', helpKey: 'admin.freightRpa.snapshotsHelp', count: snapshots.value.length }, + { key: 'exports' as const, group: 'audit', labelKey: 'admin.freightRpa.exports', helpKey: 'admin.freightRpa.exportsHelp', count: exports.value.length }, ]); -const snapshotColumnLabels = computed(() => [t('admin.shippingInventory.snapshotFile'), t('admin.shippingInventory.source'), t('admin.shippingInventory.warehouse'), t('admin.shippingInventory.exportedAt'), t('admin.shippingInventory.expiresAt'), t('admin.shippingInventory.lineCount'), t('admin.shippingInventory.sourceRun'), t('admin.shippingInventory.status'), t('admin.shippingInventory.actions')]); -const exportColumnLabels = computed(() => [t('admin.shippingInventory.runNo'), t('admin.shippingInventory.source'), t('admin.shippingInventory.connection'), t('admin.shippingInventory.triggerMode'), t('admin.shippingInventory.startedAt'), t('admin.shippingInventory.duration'), t('admin.shippingInventory.exportResult'), t('admin.shippingInventory.status'), t('admin.shippingInventory.actions')]); +const snapshotColumnLabels = computed(() => [t('admin.freightRpa.snapshotFile'), t('admin.freightRpa.source'), t('admin.freightRpa.warehouse'), t('admin.freightRpa.exportedAt'), t('admin.freightRpa.expiresAt'), t('admin.freightRpa.lineCount'), t('admin.freightRpa.sourceRun'), t('admin.freightRpa.status'), t('admin.freightRpa.actions')]); +const exportColumnLabels = computed(() => [t('admin.freightRpa.runNo'), t('admin.freightRpa.source'), t('admin.freightRpa.connection'), t('admin.freightRpa.triggerMode'), t('admin.freightRpa.startedAt'), t('admin.freightRpa.duration'), t('admin.freightRpa.exportResult'), t('admin.freightRpa.status'), t('admin.freightRpa.actions')]); const snapshotTableWidth = computed(() => snapshotColumnWidths.value.reduce((total, width) => total + width, 0)); const exportTableWidth = computed(() => exportColumnWidths.value.reduce((total, width) => total + width, 0)); const currentTab = computed(() => tabs.value.find((item) => item.key === activeTab.value) ?? tabs.value[0]!); const currentSection = computed(() => activeTab.value === 'inventoryFields' - ? { labelKey: 'admin.shippingInventory.parsingProfiles', helpKey: 'admin.shippingInventory.parsingProfilesHelp' } + ? { labelKey: 'admin.freightRpa.parsingProfiles', helpKey: 'admin.freightRpa.parsingProfilesHelp' } : currentTab.value); const currentEditorSection = computed(() => activeTab.value === 'inventoryFields' - ? { labelKey: 'admin.shippingInventory.inventoryFields', helpKey: 'admin.shippingInventory.inventoryFieldsHelp' } + ? { labelKey: 'admin.freightRpa.inventoryFields', helpKey: 'admin.freightRpa.inventoryFieldsHelp' } : currentTab.value); const isInventoryMappingSection = computed(() => ['parsing', 'inventoryFields'].includes(activeTab.value)); const isEditableTab = computed(() => ['profiles', 'parsing', 'inventoryFields', 'templates', 'sources', 'rules', 'mappings'].includes(activeTab.value)); @@ -837,7 +838,7 @@ const orderFieldName = (fieldId: string): string => String(routingFields.value.f const templateSourceOptions = (mapping: TemplateMapping) => { if (mapping.source_kind === 'order_field') return orderFieldsForTemplateRow(mapping.row_mode).map((item) => ({ value: item.field_id, label: orderFieldOptionLabel(item) })); if (mapping.source_kind === 'inventory_field') return activeInventoryFields.value.map((item) => ({ value: String(item.id), label: inventoryFieldOptionLabel(item) })); - if (mapping.source_kind === 'system_fact') return templateSystemFacts.value.map((item) => ({ value: item, label: t(`admin.shippingInventory.systemFact.${item}`) })); + if (mapping.source_kind === 'system_fact') return templateSystemFacts.value.map((item) => ({ value: item, label: t(`admin.freightRpa.systemFact.${item}`) })); return []; }; const templateSourceOptionGroups = (mapping: TemplateMapping) => { @@ -847,24 +848,24 @@ const templateSourceOptionGroups = (mapping: TemplateMapping) => { const lineFields = routingFields.value.filter((item) => item.scope === 'line') .map((item) => ({ value: item.field_id, label: orderFieldOptionLabel(item) })); const groups = [ - { label: t('admin.shippingInventory.sourceGroupOrderRepeated'), options: headerFields }, - { label: t('admin.shippingInventory.sourceGroupOrderLine'), options: lineFields }, + { label: t('admin.freightRpa.sourceGroupOrderRepeated'), options: headerFields }, + { label: t('admin.freightRpa.sourceGroupOrderLine'), options: lineFields }, ].filter((group) => group.options.length); - return groups.length ? groups : [{ label: t('admin.shippingInventory.noSourceOptions'), options: [] }]; + return groups.length ? groups : [{ label: t('admin.freightRpa.noSourceOptions'), options: [] }]; } const options = templateSourceOptions(mapping); - if (!options.length) return [{ label: t('admin.shippingInventory.noSourceOptions'), options: [] }]; + if (!options.length) return [{ label: t('admin.freightRpa.noSourceOptions'), options: [] }]; const label = mapping.source_kind === 'order_field' - ? t('admin.shippingInventory.sourceGroupOrder') + ? t('admin.freightRpa.sourceGroupOrder') : mapping.source_kind === 'inventory_field' - ? t('admin.shippingInventory.sourceGroupInventory') - : t('admin.shippingInventory.sourceGroupSystem'); + ? t('admin.freightRpa.sourceGroupInventory') + : t('admin.freightRpa.sourceGroupSystem'); return [{ label, options }]; }; const templateColumns = (sheet: string, currentColumn: number) => { const columns = templateSheetColumns.value[sheet] || []; - return columns.length || !currentColumn ? columns : [{ index: currentColumn, label: t('admin.shippingInventory.savedTargetColumn', { column: currentColumn }) }]; + return columns.length || !currentColumn ? columns : [{ index: currentColumn, label: t('admin.freightRpa.savedTargetColumn', { column: currentColumn }) }]; }; const canDeleteCurrent = computed(() => (activeTab.value !== 'rules' || selectedRuleStatus.value === 'draft') && (activeTab.value !== 'templates' || selectedTemplateStatus.value === 'draft') && (activeTab.value !== 'parsing' || selectedParsingStatus.value === 'draft')); const pagedSnapshots = computed(() => paginate(snapshots.value, snapshotPage.value)); @@ -873,12 +874,13 @@ const auditDetailEntries = computed(() => { if (!auditDetail.value) return []; const item = auditDetail.value.item; return [ - ['库存源', sourceName(item.source_code)], ['货代仓库', warehouseName(item)], ['运行号', item.rpa_run_no || t('admin.shippingInventory.historyNotCaptured')], ['状态', auditStatus(item.export_status || item.snapshot_status)], ['导出时间', auditDate(item.exported_at)], ['有效至', auditDate(item.expires_at)], ['库存行数', item.line_count ? t('admin.shippingInventory.lineCountValue', { count: item.line_count }) : t('admin.shippingInventory.historyNotCaptured')], ['结果说明', item.error_message || auditResult(item)], + ['库存源', sourceName(item.source_code)], ['货代仓库', warehouseName(item)], ['运行号', item.rpa_run_no || t('admin.freightRpa.historyNotCaptured')], ['状态', auditStatus(item.export_status || item.snapshot_status)], ['导出时间', auditDate(item.exported_at)], ['有效至', auditDate(item.expires_at)], ['库存行数', item.line_count ? t('admin.freightRpa.lineCountValue', { count: item.line_count }) : t('admin.freightRpa.historyNotCaptured')], ['结果说明', item.error_message || auditResult(item)], ].map(([label, value]) => ({ label, value })); }); const filteredBatchValidationSources = computed(() => { const query = batchValidation.query.trim().toLowerCase(); - return sources.value.filter((item) => !item.enabled && item.parsing_profile_id && ( + // s18 起解析方案绑定挂在站点 DTO 的 onhand_report_config 嵌套对象上。 + return sources.value.filter((item) => !item.enabled && item.onhand_report_config?.parsing_profile_id && ( !query || [item.display_name, item.source_code, connectionName(item.source_code)].some((value) => String(value || '').toLowerCase().includes(query)) )); }); @@ -906,7 +908,7 @@ const filteredBatchValidationRuns = computed(() => { async function load(): Promise { try { const [[profileRows, sourceRows, ruleRows, mappingRows, snapshotRows, exportRows, parsingRows, templateRows], inventoryFieldRows, fieldCatalog, configurationCatalog, temporarySessions, movementFieldRows] = await Promise.all([ - getShippingInventoryConfig(), getShippingInventoryFields(), getShippingInventoryRoutingFields(), getShippingInventoryConfigurationCatalog(), listShippingTemporaryInventorySessions(), fetchMovementFields(), + getShippingOnhandConfig(), getShippingOnhandFields(), getShippingOnhandRoutingFields(), getShippingOnhandConfigurationCatalog(), listShippingTemporaryOnhandSessions(), fetchMovementFields(), ]); profiles.value = profileRows as Item[]; sources.value = sourceRows as Item[]; rules.value = ruleRows as Item[]; mappings.value = mappingRows as Item[]; snapshots.value = snapshotRows as Item[]; exports.value = exportRows as Item[]; @@ -1014,7 +1016,7 @@ function createNew(): void { templateSheetColumns.value = {}; } if (activeTab.value === 'sources') { - Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['parsing_profile', 'excel_template'] } }); + Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, onhand_report_config: { report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], parsing_profile_id: 0 }, enabled: false, activation: { ready: false, checks: [], missing_requirements: ['parsing_profile', 'excel_template'] } }); resetReceiptConfig('dbs'); receiptConfigExists.value = false; receiptSectionTouched.value = false; @@ -1024,7 +1026,7 @@ function createNew(): void { sourceBaseline.value = ''; } if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }], source_codes: [] }); - if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true }); + if (activeTab.value === 'mappings') Object.assign(mapping, { source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true }); drawerOpen.value = true; } @@ -1068,10 +1070,16 @@ function selectItem(item: Item): void { void loadTemplateLayout(selectedId.value); } if (activeTab.value === 'sources') { + // s18 起在手报表配置从站点 DTO 的 onhand_report_config 嵌套对象回填(无配置行时按空配置初始化)。 + const itemConfig = (item.onhand_report_config || {}) as { report_path_json?: Record; query_parameters_json?: Parameter[]; parsing_profile_id?: number | string }; const reportPath = item.connector_type === 'dbs' - ? { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(item.report_path_json || {}) } - : item.report_path_json; - Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: normaliseInventoryReportPath(item.connector_type, reportPath), query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })) }); + ? { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(itemConfig.report_path_json || {}) } + : itemConfig.report_path_json; + Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', onhand_report_config: { + report_path_json: normaliseInventoryReportPath(item.connector_type, reportPath), + query_parameters_json: (itemConfig.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })), + parsing_profile_id: itemConfig.parsing_profile_id ? Number(itemConfig.parsing_profile_id) : 0, + } }); sourceBaseline.value = serialiseSourceInput(); void loadReceiptConfig(Number(item.id), String(item.connector_type || '')); } @@ -1126,7 +1134,7 @@ function closeBatchValidation(): void { async function submitBatchValidation(): Promise { batchValidation.saving = true; try { - batchValidation.result = await startShippingInventoryValidationBatch(batchValidation.sourceIds); + batchValidation.result = await startShippingOnhandValidationBatch(batchValidation.sourceIds); await pollBatchValidation(); } catch (cause) { showError(cause, 'configurationTestFailed'); } finally { batchValidation.saving = false; } @@ -1136,7 +1144,7 @@ async function pollBatchValidation(): Promise { const result = batchValidation.result; if (!result) return; try { - batchValidation.result = await getShippingInventoryValidationBatch(result.id); + batchValidation.result = await getShippingOnhandValidationBatch(result.id); if (batchValidation.result.status === 'queued' || batchValidation.result.status === 'running') { batchValidationTimer = window.setTimeout(() => { void pollBatchValidation(); }, 2000); } @@ -1146,7 +1154,7 @@ async function pollBatchValidation(): Promise { /** 页面刷新后从服务端恢复仍在运行的批量验证,并继续轮询真实状态。 */ async function restoreActiveBatchValidation(): Promise { try { - const active = await getLatestActiveShippingInventoryValidationBatch(); + const active = await getLatestActiveShippingOnhandValidationBatch(); if (!active) return; batchValidation.result = active; batchValidation.visible = true; @@ -1157,7 +1165,7 @@ async function restoreActiveBatchValidation(): Promise { async function retryBatchValidation(): Promise { if (!batchValidation.result) return; try { - batchValidation.result = await retryFailedShippingInventoryValidationBatch(batchValidation.result.id); + batchValidation.result = await retryFailedShippingOnhandValidationBatch(batchValidation.result.id); await pollBatchValidation(); } catch (cause) { showError(cause, 'configurationTestFailed'); } } @@ -1166,12 +1174,12 @@ async function retryBatchValidation(): Promise { async function submitBulkParsingBinding(): Promise { bulkBinding.saving = true; try { - await bulkBindShippingInventorySourceParsingProfile({ + await bulkBindShippingOnhandSourceParsingProfile({ source_ids: bulkBinding.sourceIds, parsing_profile_id: bulkBinding.profileId, }); bulkBinding.visible = false; await load(); - message.success(t('admin.shippingInventory.bulkParsingProfileBound')); + message.success(t('admin.freightRpa.bulkParsingProfileBound')); } catch (cause) { showError(cause, 'saveFailed'); } finally { bulkBinding.saving = false; } } @@ -1215,22 +1223,22 @@ async function saveCurrent(): Promise { if (temporaryInventorySessionSelected.value) { await createShippingParsingDraftFromTemporarySession(selectedTemporaryInventorySession.value, payload); } else { - if (!structureAnalysis.value) throw new Error(t('admin.shippingInventory.inventorySampleRequired')); + if (!structureAnalysis.value) throw new Error(t('admin.freightRpa.inventorySampleRequired')); if (pendingSampleReplacement.value && !sampleReplacementConfirmed.value) { - const preview = await previewShippingInventorySampleReplacement(selectedId.value!, Number(structureAnalysis.value.id), { + const preview = await previewShippingOnhandSampleReplacement(selectedId.value!, Number(structureAnalysis.value.id), { field_mapping: payload.field_mapping, }) as Item; pendingSampleReplacement.value = preview; - if (!preview.can_confirm) throw new Error(t('admin.shippingInventory.sampleReplacementCannotConfirm')); + if (!preview.can_confirm) throw new Error(t('admin.freightRpa.sampleReplacementCannotConfirm')); confirmation.visible = true; confirmation.action = 'replaceInventorySample'; - confirmation.title = t('admin.shippingInventory.replaceInventorySample'); - confirmation.message = t('admin.shippingInventory.replaceInventorySampleConfirm'); - confirmation.confirmText = t('admin.shippingInventory.confirmSampleReplacement'); + confirmation.title = t('admin.freightRpa.replaceInventorySample'); + confirmation.message = t('admin.freightRpa.replaceInventorySampleConfirm'); + confirmation.confirmText = t('admin.freightRpa.confirmSampleReplacement'); confirmation.tone = 'primary'; return; } - await createShippingInventoryParsingDraftFromAnalysis(Number(structureAnalysis.value.id), { ...payload, profile_id: selectedId.value || undefined, confirm_sample_replacement: sampleReplacementConfirmed.value }); + await createShippingOnhandParsingDraftFromAnalysis(Number(structureAnalysis.value.id), { ...payload, profile_id: selectedId.value || undefined, confirm_sample_replacement: sampleReplacementConfirmed.value }); } } if (activeTab.value === 'inventoryFields') { @@ -1238,20 +1246,25 @@ async function saveCurrent(): Promise { display_name: inventoryField.display_name, description: inventoryField.description, value_type: inventoryField.value_type, usage_type: inventoryField.usage_type, sort_order: inventoryField.sort_order, }; - if (selectedId.value) await updateShippingInventoryField(selectedId.value, payload); - else await createShippingInventoryField(payload); + if (selectedId.value) await updateShippingOnhandField(selectedId.value, payload); + else await createShippingOnhandField(payload); } if (activeTab.value === 'templates') { const definition = { filename_pattern: excelTemplate.filename_pattern, mappings: excelTemplate.mappings }; if (selectedId.value) await updateShippingExcelTemplate(selectedId.value, { display_name: excelTemplate.display_name, definition }); else { - if (!excelTemplate.file) throw new Error(t('admin.shippingInventory.templateFileRequired')); + if (!excelTemplate.file) throw new Error(t('admin.freightRpa.templateFileRequired')); const form = new FormData(); form.set('template_code', excelTemplate.template_code); form.set('display_name', excelTemplate.display_name || excelTemplate.template_code); form.set('definition', JSON.stringify(definition)); form.set('file', excelTemplate.file); await createShippingExcelTemplate(form); } } if (activeTab.value === 'sources') { - await saveShippingInventorySource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json) }, selectedId.value || undefined); + // s18 起在手报表配置随站点载荷内嵌 onhand_report_config 提交(服务端写配置行),站点头部只存基础字段。 + await saveShippingOnhandSource({ ...source, enabled: false, fixed_warehouse_id: source.warehouse_resolution_mode === 'fixed' ? source.fixed_warehouse_id : null, onhand_report_config: { + report_path_json: normaliseInventoryReportPath(source.connector_type, source.onhand_report_config.report_path_json), + query_parameters_json: source.onhand_report_config.query_parameters_json, + parsing_profile_id: source.onhand_report_config.parsing_profile_id, + } }, selectedId.value || undefined); // 收料与站点同批保存:仅当已有配置或管理员展开过收料卡时才提交,避免未配置站点被误建空收料配置。 if (selectedId.value && (receiptSectionTouched.value || (receiptConfigExists.value && receiptBaseline.value !== serialiseReceiptInput()))) { try { @@ -1265,8 +1278,8 @@ async function saveCurrent(): Promise { } } } - if (activeTab.value === 'rules') await saveShippingInventoryRule({ rule_code: rule.rule_code, rule_name: rule.rule_name || rule.rule_code, scope: rule.scope, priority: rule.priority, match_mode: 'all', action_type: 'add_source_candidates', action_payload_json: { source_codes: splitValues(rule.source_codes) }, conditions: rule.conditions.map((condition) => ({ source_kind: 'order_field', order_field_id: condition.order_field_id, operator: condition.operator, expected_value_json: normalizeExpectedValue(condition) })) }, selectedId.value || undefined); - if (activeTab.value === 'mappings') await saveShippingInventoryExternalMapping({ ...mapping, freight_warehouse_id: mapping.freight_warehouse_id || null, external_organization_code: mapping.external_organization_code || null, external_site_code: mapping.external_site_code || null }, selectedId.value || undefined); + if (activeTab.value === 'rules') await saveShippingOnhandRule({ rule_code: rule.rule_code, rule_name: rule.rule_name || rule.rule_code, scope: rule.scope, priority: rule.priority, match_mode: 'all', action_type: 'add_source_candidates', action_payload_json: { source_codes: splitValues(rule.source_codes) }, conditions: rule.conditions.map((condition) => ({ source_kind: 'order_field', order_field_id: condition.order_field_id, operator: condition.operator, expected_value_json: normalizeExpectedValue(condition) })) }, selectedId.value || undefined); + if (activeTab.value === 'mappings') await saveShippingOnhandExternalMapping({ ...mapping, freight_warehouse_id: mapping.freight_warehouse_id || null, external_organization_code: mapping.external_organization_code || null, external_site_code: mapping.external_site_code || null }, selectedId.value || undefined); await load(); closeDrawer(); } catch (cause) { showError(cause, 'saveFailed'); } @@ -1276,12 +1289,12 @@ async function saveCurrent(): Promise { /** 发布当前草稿规则,同时由服务端保存不可变审计定义。 */ async function publishCurrentRule(): Promise { if (!selectedId.value) return; - try { await publishShippingInventoryRule(selectedId.value); await load(); } catch (cause) { showError(cause, 'saveFailed'); } + try { await publishShippingOnhandRule(selectedId.value); await load(); } catch (cause) { showError(cause, 'saveFailed'); } } /** 归档已发布规则,保留其审计版本并停止它参与后续库存源路由。 */ async function retireCurrentRule(): Promise { - openConfirmation('retireRule', t('admin.shippingInventory.confirmRetire')); + openConfirmation('retireRule', t('admin.freightRpa.confirmRetire')); } /** 发布模板时由后端验证实际工作表、稳定字段引用和目标列冲突。 */ @@ -1289,7 +1302,7 @@ async function publishCurrentTemplate(): Promise { if (selectedId.value) { /** 发布库存解析前由后端校验字段映射、匹配键和当前订单模板引用。 */ async function publishCurrentParsingProfile(): Promise { if (!selectedId.value) return; - try { await publishShippingInventoryParsingProfile(selectedId.value); await load(); } + try { await publishShippingOnhandParsingProfile(selectedId.value); await load(); } catch (cause) { showError(cause, 'saveFailed'); } } /** 复用已保存模板文件和映射,创建可编辑的新草稿版本。 */ @@ -1304,7 +1317,7 @@ async function createTemplateVersion(): Promise { /** 从当前模板版本复制受管文件和配置,作为新编码下独立的 v1 草稿。 */ function openTemplateCloneDialog(): void { templateClone.template_code = ''; - templateClone.display_name = `${excelTemplate.display_name || excelTemplate.template_code} ${t('admin.shippingInventory.copySuffix')}`; + templateClone.display_name = `${excelTemplate.display_name || excelTemplate.template_code} ${t('admin.freightRpa.copySuffix')}`; templateClone.visible = true; } function closeTemplateCloneDialog(): void { @@ -1325,15 +1338,15 @@ async function cloneCurrentTemplate(): Promise { finally { templateClone.saving = false; } } /** 退役模板前由后端确认没有启用库存源仍在引用。 */ -async function retireCurrentTemplate(): Promise { openConfirmation('retireTemplate', t('admin.shippingInventory.confirmRetireTemplate')); } +async function retireCurrentTemplate(): Promise { openConfirmation('retireTemplate', t('admin.freightRpa.confirmRetireTemplate')); } /** 解析 Profile 仅在没有库存源引用时允许退役。 */ -async function retireCurrentParsingProfile(): Promise { openConfirmation('retireParsing', t('admin.shippingInventory.confirmRetireProfile')); } +async function retireCurrentParsingProfile(): Promise { openConfirmation('retireParsing', t('admin.freightRpa.confirmRetireProfile')); } /** 停用未被后续配置引用的扩展库存字段,核心字段不可执行此操作。 */ -async function retireCurrentInventoryField(): Promise { openConfirmation('retireInventoryField', t('admin.shippingInventory.confirmRetireInventoryField')); } +async function retireCurrentInventoryField(): Promise { openConfirmation('retireInventoryField', t('admin.freightRpa.confirmRetireInventoryField')); } /** 删除无引用的错误配置;服务端会拒绝任何会破坏业务或审计链路的请求。 */ async function deleteCurrent(): Promise { - openConfirmation('delete', t('admin.shippingInventory.confirmDelete')); + openConfirmation('delete', t('admin.freightRpa.confirmDelete')); } /** 打开平台统一确认弹窗,避免删除和归档操作使用浏览器原生提示框。 */ @@ -1342,8 +1355,8 @@ function openConfirmation(action: Exclude, messa confirmation.action = action; confirmation.message = message; confirmation.tone = action === 'delete' ? 'danger' : 'primary'; - confirmation.title = t(action === 'delete' ? 'admin.shippingInventory.confirmDeleteTitle' : 'admin.shippingInventory.confirmRetireTitle'); - confirmation.confirmText = t(action === 'delete' ? 'admin.delete' : 'admin.shippingInventory.retire'); + confirmation.title = t(action === 'delete' ? 'admin.freightRpa.confirmDeleteTitle' : 'admin.freightRpa.confirmRetireTitle'); + confirmation.confirmText = t(action === 'delete' ? 'admin.delete' : 'admin.freightRpa.retire'); confirmation.visible = true; } @@ -1353,23 +1366,23 @@ async function confirmPendingAction(): Promise { const action = confirmation.action; clearConfirmation(); try { - if (action === 'retireRule') await retireShippingInventoryRule(selectedId.value); + if (action === 'retireRule') await retireShippingOnhandRule(selectedId.value); if (action === 'retireTemplate') await retireShippingExcelTemplate(selectedId.value); - if (action === 'retireParsing') await retireShippingInventoryParsingProfile(selectedId.value); - if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value); + if (action === 'retireParsing') await retireShippingOnhandParsingProfile(selectedId.value); + if (action === 'retireInventoryField') await retireShippingOnhandField(selectedId.value); if (action === 'deactivateSource') { - await deactivateShippingInventorySource(selectedId.value); + await deactivateShippingOnhandSource(selectedId.value); await refreshSelectedSource(); return; } if (action === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; } if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value); - if (action === 'delete' && activeTab.value === 'sources') await deleteShippingInventorySource(selectedId.value); + if (action === 'delete' && activeTab.value === 'sources') await deleteShippingOnhandSource(selectedId.value); if (action === 'delete' && activeTab.value === 'templates') await deleteShippingExcelTemplate(selectedId.value); - if (action === 'delete' && activeTab.value === 'parsing') await deleteShippingInventoryParsingProfile(selectedId.value); - if (action === 'delete' && activeTab.value === 'rules') await deleteShippingInventoryRule(selectedId.value); - if (action === 'delete' && activeTab.value === 'mappings') await deleteShippingInventoryExternalMapping(selectedId.value); - if (action === 'delete' && activeTab.value === 'inventoryFields') await deleteShippingInventoryField(selectedId.value); + if (action === 'delete' && activeTab.value === 'parsing') await deleteShippingOnhandParsingProfile(selectedId.value); + if (action === 'delete' && activeTab.value === 'rules') await deleteShippingOnhandRule(selectedId.value); + if (action === 'delete' && activeTab.value === 'mappings') await deleteShippingOnhandExternalMapping(selectedId.value); + if (action === 'delete' && activeTab.value === 'inventoryFields') await deleteShippingOnhandField(selectedId.value); await load(); closeDrawer(); } catch (cause) { showError(cause, 'deleteFailed'); } @@ -1383,7 +1396,7 @@ function clearConfirmation(): void { confirmation.visible = false; confirmation. */ async function onSourceEnabledToggle(): Promise { if (!selectedId.value || sourceDirty.value || sourceToggling.value) { - if (sourceDirty.value) message.warning(t('admin.shippingInventory.saveBeforeReadinessAction')); + if (sourceDirty.value) message.warning(t('admin.freightRpa.saveBeforeReadinessAction')); return; } if (source.enabled) { @@ -1392,7 +1405,7 @@ async function onSourceEnabledToggle(): Promise { } sourceToggling.value = true; try { - await activateShippingInventorySource(selectedId.value); + await activateShippingOnhandSource(selectedId.value); await refreshSelectedSource(); } catch (cause) { showError(cause, 'saveFailed'); } finally { sourceToggling.value = false; } @@ -1402,9 +1415,9 @@ async function onSourceEnabledToggle(): Promise { function requestSourceDeactivation(): void { confirmation.visible = true; confirmation.action = 'deactivateSource'; - confirmation.title = t('admin.shippingInventory.deactivateSource'); - confirmation.message = t('admin.shippingInventory.deactivateSourceConfirm'); - confirmation.confirmText = t('admin.shippingInventory.deactivateSource'); + confirmation.title = t('admin.freightRpa.deactivateSource'); + confirmation.message = t('admin.freightRpa.deactivateSourceConfirm'); + confirmation.confirmText = t('admin.freightRpa.deactivateSource'); confirmation.tone = 'danger'; } @@ -1418,7 +1431,7 @@ async function refreshSelectedSource(): Promise { } /** 新增一行结构化 DBS 查询参数,避免要求管理员编辑 JSON。 */ -function addParameter(): void { source.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false }); } +function addParameter(): void { source.onhand_report_config.query_parameters_json.push({ name: '', mode: 'single', values: [], required: false, select_all: false }); } /** 把已保存 movement 规则的定义与只读字段目录合并为可编辑映射行;目录缺失时退化为纯 code 行。 */ function buildMovementMappings(item: Item) { const saved = (item.definition?.field_mapping || {}) as Record; @@ -1446,18 +1459,18 @@ function resetMappingRowsForPurpose(): void { function addParsingFieldMapping(): void { if (!structureAnalysis.value) { - message.warning(t('admin.shippingInventory.inventorySampleRequired')); + message.warning(t('admin.freightRpa.inventorySampleRequired')); return; } parsing.field_mappings.push({ inventory_field: '', source_header: '' }); } function addParsingMatchKey(): void { if (!unusedMatchingInventoryFields.value.length || !unusedOrderMatchFields.value.length) { - message.warning(t('admin.shippingInventory.matchKeysComplete')); + message.warning(t('admin.freightRpa.matchKeysComplete')); return; } if (!structureAnalysis.value) { - message.warning(t('admin.shippingInventory.matchKeysAnalysisRequired')); + message.warning(t('admin.freightRpa.matchKeysAnalysisRequired')); return; } parsing.match_keys.push({ order_field_id: '', inventory_field: '' }); @@ -1481,9 +1494,9 @@ async function analyseInventorySample(event: Event): Promise { if (!file) return; analysisLoading.value = true; try { - const analysis = await createShippingInventoryStructureAnalysis(file) as Item; + const analysis = await createShippingOnhandStructureAnalysis(file) as Item; if (selectedId.value) { - const preview = await previewShippingInventorySampleReplacement(selectedId.value, Number(analysis.id)) as Item; + const preview = await previewShippingOnhandSampleReplacement(selectedId.value, Number(analysis.id)) as Item; pendingSampleReplacement.value = preview; sampleReplacementConfirmed.value = false; } @@ -1505,8 +1518,8 @@ async function analyseInventorySample(event: Event): Promise { async function adoptRecommendedProfile(profileId: number): Promise { if (!structureAnalysis.value) return; try { - structureAnalysis.value = await adoptShippingInventoryParsingProfile(Number(structureAnalysis.value.id), profileId) as Item; - message.success(t('admin.shippingInventory.parsingPlanAdopted')); + structureAnalysis.value = await adoptShippingOnhandParsingProfile(Number(structureAnalysis.value.id), profileId) as Item; + message.success(t('admin.freightRpa.parsingPlanAdopted')); } catch (cause) { showError(cause, 'inventoryAnalysisFailed'); } } /** 切换分析候选时清理不属于新表头的旧字段选择,避免提交虚构栏位。 */ @@ -1604,7 +1617,7 @@ async function onTemplateFile(event: Event): Promise { })); if (!excelTemplate.mappings.length && templateSheets.value[0]) addTemplateMapping(); } catch { - message.error(t('admin.shippingInventory.templateLayoutReadFailed')); + message.error(t('admin.freightRpa.templateLayoutReadFailed')); } } /** @@ -1616,7 +1629,7 @@ async function onTemplateFile(event: Event): Promise { function rowTitle(item: Item): string { // [STEP] mappings:关系本体是来源↔目标,只显示目标仓名无法扫清单 if (activeTab.value === 'mappings') { - const sourceId = Number(item.inventory_source_id || 0); + const sourceId = Number(item.source_id || 0); const sourceLabel = sourceId ? sourceTitleById(sourceId) : '-'; const targetName = String(item.external_warehouse_name || '-'); return `${sourceLabel} → ${targetName}`; @@ -1636,10 +1649,10 @@ function rowMeta(item: Item): string { const inTransit = String(item.in_transit_warehouse_code || '').trim(); return inTransit ? `${inTransit} → ${targetCode}` : targetCode; } - if (activeTab.value === 'inventoryFields') return `${t(`admin.shippingInventory.inventoryFieldType.${item.value_type || 'text'}`)} · ${t(`admin.shippingInventory.inventoryFieldPurposeOption.${item.usage_type || 'general'}`)}`; - if (item.connector_type) return String(item.display_name ? t(`admin.shippingInventory.platform.${item.connector_type}`) : item.connector_type); + if (activeTab.value === 'inventoryFields') return `${t(`admin.freightRpa.inventoryFieldType.${item.value_type || 'text'}`)} · ${t(`admin.freightRpa.inventoryFieldPurposeOption.${item.usage_type || 'general'}`)}`; + if (item.connector_type) return String(item.display_name ? t(`admin.freightRpa.platform.${item.connector_type}`) : item.connector_type); // 解析规则列表带出用途徽标文案,库存/入站/出站三种规则在列表一眼可分。 - if (activeTab.value === 'parsing') return `${t(`admin.shippingInventory.parsingPurpose.${item.purpose}`)} · V${item.version ?? '-'}`; + if (activeTab.value === 'parsing') return `${t(`admin.freightRpa.parsingPurpose.${item.purpose}`)} · V${item.version ?? '-'}`; return String(item.source_code || item.profile_code || item.rule_code || item.external_warehouse_code || '-'); } @@ -1649,8 +1662,8 @@ function inventoryFieldOptionLabel(field: Item): string { return description ? `${field.display_name} - ${description}` : String(field.display_name || ''); } function formatDate(value: unknown): string { return value ? new Date(String(value)).toLocaleString() : '-'; } -function auditDate(value: unknown): string { return value ? formatDate(value) : t('admin.shippingInventory.historyNotCaptured'); } -function sourceName(sourceCode: unknown): string { return String(sourceCode || t('admin.shippingInventory.historyNotCaptured')); } +function auditDate(value: unknown): string { return value ? formatDate(value) : t('admin.freightRpa.historyNotCaptured'); } +function sourceName(sourceCode: unknown): string { return String(sourceCode || t('admin.freightRpa.historyNotCaptured')); } function sourceTitleById(sourceId: number): string { const item = sources.value.find((source) => Number(source.id) === Number(sourceId)); return String(item?.display_name || item?.source_code || sourceId); @@ -1659,10 +1672,15 @@ function sourceTitleById(sourceId: number): string { function serialiseSourceInput(): string { return JSON.stringify({ 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, + rpa_profile_id: source.rpa_profile_id, excel_template_id: source.excel_template_id, warehouse_resolution_mode: source.warehouse_resolution_mode, fixed_warehouse_id: source.fixed_warehouse_id, snapshot_ttl_seconds: source.snapshot_ttl_seconds, - report_path_json: normaliseInventoryReportPath(source.connector_type, source.report_path_json), query_parameters_json: source.query_parameters_json, + // 在手报表配置(含解析绑定)参与脏检查:解析绑定直接影响测试导出与启用门禁输入。 + onhand_report_config: { + report_path_json: normaliseInventoryReportPath(source.connector_type, source.onhand_report_config.report_path_json), + query_parameters_json: source.onhand_report_config.query_parameters_json, + parsing_profile_id: source.onhand_report_config.parsing_profile_id, + }, }); } @@ -1676,18 +1694,18 @@ function serialiseReceiptInput(): string { }); } -function connectionName(sourceCode: unknown): string { const sourceItem = sources.value.find((source) => source.source_code === sourceCode); const profileItem = profiles.value.find((profile) => Number(profile.id) === Number(sourceItem?.rpa_profile_id)); return profileItem?.profile_code || t('admin.shippingInventory.historyNotCaptured'); } -function warehouseName(item: Item): string { return item.warehouse_id || (item.source_code === 'CRANE' ? t('admin.shippingInventory.dynamicWarehouse') : t('admin.shippingInventory.historyNotCaptured')); } -function auditStatus(value: unknown): string { const key = String(value || 'unknown'); return t(`admin.shippingInventory.auditStatus.${key}`); } +function connectionName(sourceCode: unknown): string { const sourceItem = sources.value.find((source) => source.source_code === sourceCode); const profileItem = profiles.value.find((profile) => Number(profile.id) === Number(sourceItem?.rpa_profile_id)); return profileItem?.profile_code || t('admin.freightRpa.historyNotCaptured'); } +function warehouseName(item: Item): string { return item.warehouse_id || (item.source_code === 'CRANE' ? t('admin.freightRpa.dynamicWarehouse') : t('admin.freightRpa.historyNotCaptured')); } +function auditStatus(value: unknown): string { const key = String(value || 'unknown'); return t(`admin.freightRpa.auditStatus.${key}`); } function auditStatusClass(value: unknown): string { const key = String(value || 'unknown'); return ['ready', 'success'].includes(key) ? 'ready' : ['failed', 'partial_failed'].includes(key) ? 'failed' : 'neutral'; } -function auditResult(item: Item): string { return item.inventory_file_no ? t('admin.shippingInventory.exportResultReady') : t('admin.shippingInventory.historyNotCaptured'); } +function auditResult(item: Item): string { return item.inventory_file_no ? t('admin.freightRpa.exportResultReady') : t('admin.freightRpa.historyNotCaptured'); } function openAuditDetail(item: Item, kind: 'snapshot' | 'export'): void { auditDetail.value = { item, kind }; } function paginate(items: Item[], page: number): Item[] { const start = (page - 1) * auditPageSize.value; return items.slice(start, start + auditPageSize.value); } -function downloadSnapshot(item: Item): void { void downloadShippingInventorySnapshot(Number(item.id), `${item.inventory_file_no || 'inventory'}.xlsx`).catch((cause) => { showError(cause, 'downloadFailed'); }); } +function downloadSnapshot(item: Item): void { void downloadShippingOnhandSnapshot(Number(item.id), `${item.inventory_file_no || 'inventory'}.xlsx`).catch((cause) => { showError(cause, 'downloadFailed'); }); } /** 将货代管理操作失败交给平台统一消息弹窗,禁止跨工作区保留页面级错误。 */ function showError(cause: unknown, fallbackKey: 'loadFailed' | 'saveFailed' | 'deleteFailed' | 'downloadFailed' | 'inventoryAnalysisFailed' | 'configurationTestFailed' | 'templateLayoutReadFailed'): void { - message.error(cause instanceof Error ? cause.message : t(`admin.shippingInventory.${fallbackKey}`)); + message.error(cause instanceof Error ? cause.message : t(`admin.freightRpa.${fallbackKey}`)); } /** 仅在管理员主动聚焦凭据输入框后开放编辑,阻止浏览器在抽屉打开时自动回填已保存密码。 */ diff --git a/frontend/src/features/admin/modules/shipping-inventory/movementFieldLabels.spec.ts b/frontend/src/features/admin/modules/freight-rpa/movementFieldLabels.spec.ts similarity index 85% rename from frontend/src/features/admin/modules/shipping-inventory/movementFieldLabels.spec.ts rename to frontend/src/features/admin/modules/freight-rpa/movementFieldLabels.spec.ts index f7b3f8b4..8c24d6a8 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/movementFieldLabels.spec.ts +++ b/frontend/src/features/admin/modules/freight-rpa/movementFieldLabels.spec.ts @@ -1,10 +1,10 @@ /** - * features/admin/modules/shipping-inventory/movementFieldLabels.spec.ts + * features/admin/modules/freight-rpa/movementFieldLabels.spec.ts * 用途:锁定库存解析管理页「标准异动字段」标签映射与后端 MOVEMENT_FIELDS 契约一致。 * 依赖:vitest、四语言 locales 下各 admin.json。 * 逻辑:页面用 `movementFields.${item.code}` 动态取标签,code 集合由后端目录接口 * (movement_contract.MOVEMENT_FIELDS)在运行期下发,静态 i18n 工具查不出缺键—— - * 后端扩字段而语言包未同步时,界面会把原始 key(如 admin.shippingInventory. + * 后端扩字段而语言包未同步时,界面会把原始 key(如 admin.freightRpa. * movementFields.order_type)直接渲染给用户(2026-10-15 实测回归)。 */ @@ -23,10 +23,10 @@ const BACKEND_MOVEMENT_FIELD_CODES = [ ] as const; const LABEL_MAPS: Record> = { - 'zh-CN': (zhCN as Record).shippingInventory.movementFields, - 'zh-TW': (zhTW as Record).shippingInventory.movementFields, - en: (en as Record).shippingInventory.movementFields, - th: (th as Record).shippingInventory.movementFields, + 'zh-CN': (zhCN as Record).freightRpa.movementFields, + 'zh-TW': (zhTW as Record).freightRpa.movementFields, + en: (en as Record).freightRpa.movementFields, + th: (th as Record).freightRpa.movementFields, }; describe('movementFieldLabels', () => { diff --git a/frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts b/frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.spec.ts similarity index 96% rename from frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts rename to frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.spec.ts index 27c3c78b..4853adcb 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts +++ b/frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.spec.ts @@ -1,5 +1,5 @@ /** - * features/admin/modules/shipping-inventory/movementParsingProfileForm.spec.ts + * features/admin/modules/freight-rpa/movementParsingProfileForm.spec.ts * 用途:覆盖收料异动解析规则映射的组装边界。 * 依赖:movementParsingProfileForm、vitest。 * 逻辑:标准异动字段是只读领域契约——映射键必须是契约 code,必填字段缺失要阻断保存。 diff --git a/frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.ts b/frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts similarity index 96% rename from frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.ts rename to frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts index e9a4703b..bb139bfe 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/movementParsingProfileForm.ts +++ b/frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts @@ -1,5 +1,5 @@ /** - * features/admin/modules/shipping-inventory/movementParsingProfileForm.ts + * features/admin/modules/freight-rpa/movementParsingProfileForm.ts * 用途:组装入站解析规则(purpose='inbound')的标准异动字段映射载荷。 * 依赖:无外部依赖。 * 逻辑:标准异动字段目录由后端 /admin/shipping-notice/movement-fields 只读下发, diff --git a/frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts b/frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts similarity index 97% rename from frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts rename to frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts index b3995086..46c20d6b 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts +++ b/frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts @@ -1,5 +1,5 @@ /** - * features/admin/modules/shipping-inventory/receiptReportConfigForm.spec.ts + * features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts * 用途:覆盖收料报表表单的独立载荷边界。 * 依赖:receiptReportConfigForm、vitest。 * 逻辑:防止收料配置保存时把库存站点路径、库存查询条件或启停状态误发到库存接口; diff --git a/frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.ts b/frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.ts similarity index 83% rename from frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.ts rename to frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.ts index 051c2eab..64be4ea6 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/receiptReportConfigForm.ts +++ b/frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.ts @@ -1,8 +1,8 @@ /** - * features/admin/modules/shipping-inventory/receiptReportConfigForm.ts + * features/admin/modules/freight-rpa/receiptReportConfigForm.ts * 用途:构建独立收料报表配置的受限保存载荷。 * 依赖:无外部依赖。 - * 逻辑:页面仅将收料路径与查询条件提交到收料配置 API,与库存同构(查询条件可选,空=页面默认), + * 逻辑:页面仅将收料路径与查询条件提交到 /api/admin/freight-rpa/sources//inbound-report-config,与库存同构(查询条件可选,空=页面默认), * 隔离库存站点字段;收料无独立启停字段,是否运行统一由库存站点 enabled 决定。 */ diff --git a/frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts b/frontend/src/features/admin/modules/freight-rpa/shippingOnhandReadiness.spec.ts similarity index 81% rename from frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts rename to frontend/src/features/admin/modules/freight-rpa/shippingOnhandReadiness.spec.ts index b7d0d4e2..e54d5771 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts +++ b/frontend/src/features/admin/modules/freight-rpa/shippingOnhandReadiness.spec.ts @@ -1,20 +1,20 @@ /** - * features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts + * features/admin/modules/freight-rpa/shippingOnhandReadiness.spec.ts * 用途:覆盖库存站点上线检查与测试恢复的纯状态映射。 - * 依赖:shippingInventoryReadiness、vitest。 + * 依赖:shippingOnhandReadiness、vitest。 * 逻辑:防止页面把已完成项目显示为待办,或持续轮询服务端已结束的测试任务。 */ import { describe, expect, it } from 'vitest'; -import type { ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api'; -import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness'; -import { normaliseInventoryReportPath } from './shippingInventorySourceForm'; +import type { ShippingOnhandReadinessCheck } from '@/features/admin/api/admin.api'; +import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingOnhandReadiness'; +import { normaliseInventoryReportPath } from './shippingOnhandSourceForm'; -const check = (status: ShippingInventoryReadinessCheck['status'], blocking: boolean): ShippingInventoryReadinessCheck => ({ +const check = (status: ShippingOnhandReadinessCheck['status'], blocking: boolean): ShippingOnhandReadinessCheck => ({ code: 'configuration_test', status, blocking, action: 'run_configuration_test', evidence: {}, }); -describe('shippingInventoryReadiness', () => { +describe('shippingOnhandReadiness', () => { it('keeps stale checks actionable and visually distinct from ordinary pending work', () => { // 关键断言:配置已变更的测试不能被渲染成普通待办,管理员必须重新测试。 expect(readinessMarkerKind('stale')).toBe('attention'); diff --git a/frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts b/frontend/src/features/admin/modules/freight-rpa/shippingOnhandReadiness.ts similarity index 65% rename from frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts rename to frontend/src/features/admin/modules/freight-rpa/shippingOnhandReadiness.ts index d91ed1ba..d3e75e1e 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts +++ b/frontend/src/features/admin/modules/freight-rpa/shippingOnhandReadiness.ts @@ -1,11 +1,11 @@ /** - * features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts + * features/admin/modules/freight-rpa/shippingOnhandReadiness.ts * 用途:归一库存站点上线检查与配置测试的前端展示状态。 - * 依赖:admin.api 中的 Inventory Readiness/Test 类型。 - * 逻辑:ShippingInventoryPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。 + * 依赖:admin.api 的 ShippingOnhandReadinessCheck / ShippingOnhandConfigurationTest。 + * 逻辑:FreightRpaPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。 */ -import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api'; +import type { ShippingOnhandConfigurationTest, ShippingOnhandReadinessCheck } from '@/features/admin/api/admin.api'; export type ReadinessMarker = 'complete' | 'attention' | 'pending'; @@ -15,7 +15,7 @@ export type ReadinessMarker = 'complete' | 'attention' | 'pending'; * @param status - 后端 `checks[]` 返回的稳定状态。 * @returns 供页面选择图形和颜色的有限标记,不参与启用门禁计算。 */ -export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['status']): ReadinessMarker { +export function readinessMarkerKind(status: ShippingOnhandReadinessCheck['status']): ReadinessMarker { if (status === 'passed') return 'complete'; if (status === 'failed' || status === 'stale') return 'attention'; return 'pending'; @@ -27,7 +27,7 @@ export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['sta * @param check - 后端权威检查项。 * @returns 为 true 时页面可展示对应的单一下一步动作。 */ -export function needsReadinessAction(check: ShippingInventoryReadinessCheck): boolean { +export function needsReadinessAction(check: ShippingOnhandReadinessCheck): boolean { return check.status !== 'passed' && check.blocking; } @@ -37,6 +37,6 @@ export function needsReadinessAction(check: ShippingInventoryReadinessCheck): bo * @param test - 当前恢复或新发起的测试运行。 * @returns 是否继续轮询。 */ -export function isConfigurationTestRunning(test: ShippingInventoryConfigurationTest | null): boolean { +export function isConfigurationTestRunning(test: ShippingOnhandConfigurationTest | null): boolean { return Boolean(test && ['awaiting_rpa', 'processing'].includes(test.status)); } diff --git a/frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts b/frontend/src/features/admin/modules/freight-rpa/shippingOnhandSourceForm.ts similarity index 81% rename from frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts rename to frontend/src/features/admin/modules/freight-rpa/shippingOnhandSourceForm.ts index 3d57c8c0..40ca73c8 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts +++ b/frontend/src/features/admin/modules/freight-rpa/shippingOnhandSourceForm.ts @@ -1,8 +1,8 @@ /** - * features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts + * features/admin/modules/freight-rpa/shippingOnhandSourceForm.ts * 用途:规范化库存站点表单中仅适用于 DBS 的报表路径字段。 * 依赖:无外部依赖,仅处理库存站点表单的连接器类型和 JSON 路径。 - * 逻辑:ShippingInventoryPage 在回填、保存和脏状态比较时调用,避免非 DBS 站点携带 DBS 默认路径。 + * 逻辑:FreightRpaPage 在回填、保存和脏状态比较时调用,避免非 DBS 站点携带 DBS 默认路径。 */ export type InventoryReportPath = Record; diff --git a/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts b/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts index b38fc75b..96f31127 100644 --- a/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts +++ b/frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts @@ -2,7 +2,7 @@ * features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts * 用途:复现「货代库存 RPA」平台任务参数表单的渲染。 * 背景:排程编辑弹窗选择 freight-rpa-onhand 后,库存源多选字段不呈现,且弹窗按钮疑似失效。 - * 断言:给定带 source_codes(multi_select/options_source=shipping_inventory_sources) 的定义, + * 断言:给定带 source_codes(multi_select/options_source=freight_rpa_sources) 的定义, * 挂载后应渲染「库存源」标签及动态选项,而不是抛错或渲染为空。 */ import { describe, expect, it, vi, beforeEach } from 'vitest'; @@ -19,26 +19,26 @@ vi.mock('@/features/admin/api/schedule.api', () => ({ ), })); -const shippingInventoryRpaDefinition = { +const shippingOnhandRpaDefinition = { task_type: 'freight-rpa-onhand', label: '货代库存 RPA', - label_key: 'admin.schedule.form.platformJobShippingInventory', + label_key: 'admin.schedule.form.platformJobFreightRpaOnhand', description: '按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。', - description_key: 'admin.schedule.form.shippingInventoryJobHint', + description_key: 'admin.schedule.form.freightRpaOnhandJobHint', category: 'shipping', params_schema: [ { key: 'source_codes', type: 'multi_select', label: '库存源', - label_key: 'admin.schedule.form.shippingInventorySources', + label_key: 'admin.schedule.form.freightRpaSources', required: false, default: [], - options_source: 'shipping_inventory_sources', + options_source: 'freight_rpa_sources', placeholder: '留空则导出全部启用库存源', - placeholder_key: 'admin.schedule.form.shippingInventorySourcesPlaceholder', + placeholder_key: 'admin.schedule.form.freightRpaSourcesPlaceholder', help: '选择需要执行的库存源;选项来自库存源配置,留空则全部执行。', - help_key: 'admin.schedule.form.shippingInventorySourcesHelp', + help_key: 'admin.schedule.form.freightRpaSourcesHelp', }, ], defaults: { source_codes: [] }, @@ -57,7 +57,7 @@ function mountForm() { }); return mount(DynamicTaskParamsForm, { props: { - definition: shippingInventoryRpaDefinition as any, + definition: shippingOnhandRpaDefinition as any, modelValue: { source_codes: [] }, valid: true, }, diff --git a/frontend/src/features/admin/modules/transfer-types/transferTypes.api.ts b/frontend/src/features/admin/modules/transfer-types/transferTypes.api.ts index 9ee8d83d..aa943613 100644 --- a/frontend/src/features/admin/modules/transfer-types/transferTypes.api.ts +++ b/frontend/src/features/admin/modules/transfer-types/transferTypes.api.ts @@ -113,11 +113,12 @@ export const updateTransferType = (code: string, payload: TransferTypePayload) = /** * 拉取货代库存外部仓库映射档,仅用于固定仓库编码的存在性黄色提示校验。 + * 核心逻辑:请求 /api/admin/freight-rpa/onhand/external-mappings;失败时返回空数组,不阻断类型配置。 * @returns 映射行数组;请求失败返回空数组(校验静默降级为「未命中」语义之外的不提示) */ export const listExternalWarehouseMappings = async (): Promise>> => { try { - return await requestJson>>('/api/admin/shipping-notice/external-mappings'); + return await requestJson>>('/api/admin/freight-rpa/onhand/external-mappings'); } catch { // 校验属辅助提示,加载失败不影响配置主流程 return []; diff --git a/frontend/src/features/admin/shippingConfigNavigation.spec.ts b/frontend/src/features/admin/shippingConfigNavigation.spec.ts index 0755629c..3ba20804 100644 --- a/frontend/src/features/admin/shippingConfigNavigation.spec.ts +++ b/frontend/src/features/admin/shippingConfigNavigation.spec.ts @@ -11,7 +11,7 @@ import { ADMIN_MODULE_METAS, SHIPPING_CONFIG_SUB_MODULE_METAS } from './constant import type { ShippingManagementGroupKey } from './stores/admin-nav.store'; const shippingRoutes = adminRoutes[0].children?.filter((route) => - route.name === 'AdminShippingInventory' + route.name === 'AdminFreightRpa' || route.name === 'AdminShippingFieldAssets' || route.name === 'AdminShippingOrderSchema' || route.name === 'AdminShippingIdentityRules' @@ -27,7 +27,7 @@ describe('shipping configuration navigation contract', () => { const moduleIds = ADMIN_MODULE_METAS.map((item) => item.id); expect(moduleIds.slice(moduleIds.indexOf('schedules'), moduleIds.indexOf('announcements') + 1)).toEqual([ 'schedules', - 'shipping_inventory', + 'freight_rpa', 'announcements', ]); }); @@ -40,18 +40,18 @@ describe('shipping configuration navigation contract', () => { { id: 'order_document_profiles', routeName: 'AdminShippingOrderDocumentProfiles', path: 'shipping-order-document-profiles', labelKey: 'admin.nav.shippingOrderDocumentProfiles', groupKey: 'admin.nav.shippingOrderRecognition' }, { id: 'identity_rules', routeName: 'AdminShippingIdentityRules', path: 'shipping-identity-rules', labelKey: 'admin.nav.shippingIdentityRules', groupKey: 'admin.nav.shippingOrderRecognition' }, { id: 'order_extraction_runs', routeName: 'AdminShippingOrderExtractionRuns', path: 'shipping-order-extraction-runs', labelKey: 'admin.nav.shippingOrderExtractionRuns', groupKey: 'admin.nav.shippingOrderRecognition' }, - { id: 'inventory_fields', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.parsingProfiles', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'parsing' } }, - { id: 'connections', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.connections', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'profiles' } }, - { id: 'inventory_sites', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.sources', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'sources' } }, - { id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } }, - { id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } }, + { id: 'inventory_fields', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.parsingProfiles', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'parsing' } }, + { id: 'connections', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.connections', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'profiles' } }, + { id: 'inventory_sites', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.sources', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'sources' } }, + { id: 'warehouse_mappings', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.externalMappings', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'mappings' } }, + { id: 'routing_rules', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.rules', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'rules' } }, // 调拨类型(原顶级入口移入,路由独立注册于 AdminTransferTypes,故不在 shippingRoutes 深链集合内) - { id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', groupKey: 'admin.nav.shippingInventoryManagement' }, - { id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } }, + { id: 'transfer_types', routeName: 'AdminTransferTypes', path: 'transfer-types', labelKey: 'admin.nav.transferTypes', groupKey: 'admin.nav.freightRpaManagement' }, + { id: 'shipping_templates', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.excelTemplates', groupKey: 'admin.nav.freightRpaManagement', query: { section: 'templates' } }, { id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' }, { id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' }, - { id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } }, - { id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } }, + { id: 'inventory_snapshots', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } }, + { id: 'export_records', routeName: 'AdminFreightRpa', path: 'shipping-notice', labelKey: 'admin.freightRpa.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } }, ]); expect(shippingRoutes).toHaveLength(8); expect(shippingRoutes.some((route) => route.name === 'AdminShippingReviewSupervision')).toBe(false); @@ -62,7 +62,7 @@ describe('shipping configuration navigation contract', () => { const groups = [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))] satisfies ShippingManagementGroupKey[]; expect(groups).toEqual([ 'admin.nav.shippingOrderRecognition', - 'admin.nav.shippingInventoryManagement', + 'admin.nav.freightRpaManagement', 'admin.nav.shippingRunAudit', ]); }); @@ -70,14 +70,14 @@ describe('shipping configuration navigation contract', () => { it('keeps all deep links behind the shared shipping inventory admin boundary', () => { // 关键断言:菜单可见性不是授权;所有页面均须保留 requiresAdmin 和共享模块权限标识。 expect(shippingRoutes.map((route) => route.meta)).toEqual([ - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'inventory' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'field_assets' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_schema' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'identity_rules' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_extraction_runs' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'shipping_audit' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'process_gates' }), - expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'inventory' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'field_assets' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'order_schema' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'identity_rules' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'order_extraction_runs' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'shipping_audit' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'process_gates' }), + expect.objectContaining({ requiresAdmin: true, adminModule: 'freight_rpa', adminSubModule: 'order_document_profiles' }), ]); }); @@ -89,7 +89,7 @@ describe('shipping configuration navigation contract', () => { expect(editorRoute?.path).toBe('shipping-order-document-profiles/:profileCode/drafts/:profileId/edit'); expect(editorRoute?.meta).toEqual(expect.objectContaining({ requiresAdmin: true, - adminModule: 'shipping_inventory', + adminModule: 'freight_rpa', adminSubModule: 'order_document_profiles', })); }); diff --git a/frontend/src/features/admin/types/admin.types.ts b/frontend/src/features/admin/types/admin.types.ts index 03b13380..ea3ce971 100644 --- a/frontend/src/features/admin/types/admin.types.ts +++ b/frontend/src/features/admin/types/admin.types.ts @@ -17,7 +17,7 @@ export type AdminModuleId = | 'linked_services' | 'permissions' | 'platform_apps' - | 'shipping_inventory' + | 'freight_rpa' | 'procurement_contract' | 'training_config' | 'integration_connector' diff --git a/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts b/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts index 9bc66653..fa8edf4a 100644 --- a/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts +++ b/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts @@ -9,7 +9,7 @@ import { describe, expect, it } from 'vitest'; describe('shipping API runtime entrypoints', () => { it('does not expose direct inventory match or Excel generation actions', () => { - expect(Object.prototype.hasOwnProperty.call(shippingApi, 'matchWorkspaceShippingInventory')).toBe(false); + expect(Object.prototype.hasOwnProperty.call(shippingApi, 'matchWorkspaceShippingOnhand')).toBe(false); expect(Object.prototype.hasOwnProperty.call(shippingApi, 'generateWorkspaceShippingExcel')).toBe(false); }); }); diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index c860f7e9..13a5d332 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -60,7 +60,7 @@ import type { ShippingOrderReviewLlmSuggestionResponse, ShippingOrderReviewReparseResponse, ShippingOrderReviewRun, - ShippingTaskInventoryCandidatesResponse, + ShippingTaskOnhandCandidatesResponse, ShippingTaskUiState, } from '../types/shipping.api.types'; @@ -205,7 +205,7 @@ export const workspaceShippingNoticeExportUrl = (businessNo: string) => `/api/workspace/shipping-notices/${encodeURIComponent(businessNo)}/export`; /** 当前任务已关联库存快照的受控下载 URL;后端会再次校验任务归属与活动 link。 */ -export const workspaceShippingInventoryFileUrl = (taskNo: string) => +export const workspaceShippingOnhandFileUrl = (taskNo: string) => `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/inventory-file`; /** 当前任务指定明细匹配快照的受控下载 URL;文件号必须由行级投影提供。 */ @@ -622,7 +622,7 @@ export const getWorkspaceTaskInventoryCandidates = ( if (options?.version != null) params.set('version', String(options.version)); if (options?.includeHistory != null) params.set('include_history', String(options.includeHistory)); const query = params.toString(); - return requestJson( + return requestJson( `/api/workspace/shipping-notice/tasks/${encodeURIComponent(taskNo)}/inventory-candidates${query ? `?${query}` : ''}`, ); }; @@ -1348,7 +1348,7 @@ export async function removeWorkspaceShippingNoticeLine( * @param file - 已按库存源发布方案导出的 xls/xlsx/csv 文件 * @returns 库存解析与后续匹配结果 */ -export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) { +export async function uploadWorkspaceShippingOnhand(taskNo: string, file: File) { const form = new FormData(); form.append('file', file); const body = await requestJson( diff --git a/frontend/src/features/chat/components/ChatViewContent.vue b/frontend/src/features/chat/components/ChatViewContent.vue index 09f29800..109f19e5 100644 --- a/frontend/src/features/chat/components/ChatViewContent.vue +++ b/frontend/src/features/chat/components/ChatViewContent.vue @@ -672,7 +672,7 @@ watch(() => page.currentAgentId, () => { @add-remote-url="page.addRemoteUrlAttachment" - @shipping-inventory-selected="page.handleShippingInventorySelected" + @shipping-inventory-selected="page.handleShippingOnhandSelected" @use-shipping-suggested-prompt="page.useShippingSuggestedPrompt" diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts index 18fcbc8a..189ba046 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts @@ -15,13 +15,13 @@ const i18n = createI18n({ locale: 'zh-CN', messages: { 'zh-CN': { - 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配', + 'chat.shippingOrderReview.processGate.actionCodes.retry_onhand_matching': '重新库存匹配', workspace: { shippingNotice: { processGate: { actionCodes: { - reload_inventory_result: '重新读取库存结果', - retry_inventory_preparation: '重新获取库存', + reload_onhand_result: '重新读取库存结果', + retry_onhand_preparation: '重新获取库存', confirm_customer: '确认客户', }, inventoryActions: { @@ -76,7 +76,7 @@ describe('ReviewCurrentProcessingCard', () => { it('hides a legacy primary action while inventory preparation is running', () => { const wrapper = mount(ReviewCurrentProcessingCard, { props: { - stageCode: 'inventory_preparation', + stageCode: 'onhand_preparation', userStatus: 'running', primaryAction: { code: 'edit_formal_task', i18nKey: 'edit_formal_task' }, }, @@ -90,8 +90,8 @@ describe('ReviewCurrentProcessingCard', () => { it('keeps the retry action for retryable states', () => { const wrapper = mount(ReviewCurrentProcessingCard, { props: { - stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true, - primaryAction: { code: 'retry_inventory_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' }, + stageCode: 'onhand_preparation', userStatus: 'retryable', retryable: true, + primaryAction: { code: 'retry_onhand_preparation', i18nKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' }, }, global: { plugins: [i18n] }, }); @@ -105,8 +105,8 @@ describe('ReviewCurrentProcessingCard', () => { // 此用例用 reload_inventory_result(仍为写契约有效码)验证卡片对库存动作文案的渲染。 const wrapper = mount(ReviewCurrentProcessingCard, { props: { - stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true, - primaryAction: { code: 'reload_inventory_result' }, + stageCode: 'onhand_preparation', userStatus: 'retryable', retryable: true, + primaryAction: { code: 'reload_onhand_result' }, }, global: { plugins: [i18n] }, }); @@ -131,11 +131,11 @@ describe('ReviewCurrentProcessingCard', () => { it('renders Gate label_key for every primary action presentation', () => { const wrapper = mount(ReviewCurrentProcessingCard, { props: { - stageCode: 'inventory_matching', + stageCode: 'onhand_matching', userStatus: 'waiting_human', primaryAction: { - code: 'retry_inventory_matching', - label_key: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching', + code: 'retry_onhand_matching', + label_key: 'chat.shippingOrderReview.processGate.actionCodes.retry_onhand_matching', } as any, }, global: { plugins: [i18n] }, @@ -220,7 +220,7 @@ describe('ReviewCurrentProcessingCard', () => { it('renders a localized reason instead of an internal blocking code in the next step', () => { const wrapper = mount(ReviewCurrentProcessingCard, { props: { - stageCode: 'inventory_matching', + stageCode: 'onhand_matching', userStatus: 'waiting_human', blockingReason: { code: 'inventory_shortage_review_required' }, }, @@ -235,18 +235,18 @@ describe('ReviewCurrentProcessingCard', () => { it('hides internal inventory recovery targets while retaining the stable primary action', async () => { const wrapper = mount(ReviewCurrentProcessingCard, { props: { - stageCode: 'inventory_matching', + stageCode: 'onhand_matching', userStatus: 'waiting_human', - primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' }, + primaryAction: { code: 'retry_onhand_matching', i18nKey: 'retry_onhand_matching' }, recoveryActions: [{ - code: 'retry_inventory_from_preparation', - i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching', + code: 'retry_onhand_from_preparation', + i18nKey: 'chat.shippingOrderReview.processGate.actionCodes.retry_onhand_matching', }], }, global: { plugins: [i18n] }, }); - expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(false); + expect(wrapper.find('[data-testid="review-current-task-recovery-retry_onhand_from_preparation"]').exists()).toBe(false); expect(wrapper.findAll('button').length).toBe(1); }); @@ -255,19 +255,19 @@ describe('ReviewCurrentProcessingCard', () => { props: { stageCode: 'fulfillment_prep', userStatus: 'waiting_human', - primaryAction: { code: 'retry_inventory_matching' }, - recoveryActions: [{ code: 'retry_inventory_preparation' }], + primaryAction: { code: 'retry_onhand_matching' }, + recoveryActions: [{ code: 'retry_onhand_preparation' }], }, global: { plugins: [i18n] }, }); await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click'); - await wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]').trigger('click'); + await wrapper.get('[data-testid="review-current-task-recovery-retry_onhand_preparation"]').trigger('click'); // 两个稳定 action 码分别进入 Gate API:重匹配不可误触 RPA,重新获取库存才会触发 RPA。 expect(wrapper.emitted('action')).toEqual([ - ['retry_inventory_matching', {}], - ['retry_inventory_preparation', {}], + ['retry_onhand_matching', {}], + ['retry_onhand_preparation', {}], ]); }); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue index e28ba126..e27d27a0 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue @@ -317,7 +317,7 @@ const businessActionTitle = computed(() => { }); const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_')); -const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation'); +const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_onhand_preparation'); /** * 阶段能力禁用态裁决:与视图层 submitFormalGateAction 的点击拦截同源(展示=执行同源)。 diff --git a/frontend/src/features/chat/components/shipping-review/ReviewInventoryIssueFallbackCard.vue b/frontend/src/features/chat/components/shipping-review/ReviewInventoryIssueFallbackCard.vue index 100347f8..170099cd 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewInventoryIssueFallbackCard.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewInventoryIssueFallbackCard.vue @@ -31,7 +31,7 @@ const { t, te } = useI18n(); const visible = computed(() => { const actions = props.fallback?.allowed_actions || []; - return Boolean(props.fallback && actions.includes('retry_inventory_preparation')); + return Boolean(props.fallback && actions.includes('retry_onhand_preparation')); }); /** @@ -71,7 +71,7 @@ const reasonLabel = computed(() => { :disabled="busy" @click="emit('retry-preparation')" > - {{ t(inventoryActionLabelKey('retry_inventory_preparation')!) }} + {{ t(inventoryActionLabelKey('retry_onhand_preparation')!) }} diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts index 8dad1322..36881339 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts @@ -55,7 +55,7 @@ describe('ReviewLineInventoryOps', () => { it('keeps inventory actions out of the line even when present', () => { const wrapper = mountOps({ retryable: false, - inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'], + inventory_allowed_actions: ['retry_onhand_preparation', 'retry_onhand_matching'], line_allowed_actions: ['close_unfulfillable'], }); expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false); diff --git a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts index 38dd6c9e..90e6ba26 100644 --- a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts +++ b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts @@ -474,7 +474,7 @@ describe('ShippingConversationProcessingCard', () => { customerName: null, poNumber: 'PO-FIRST', }, childOrderTasks: [{ - orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'inventory_matching', + orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'onhand_matching', customerName: null, poNumber: 'PO-SECOND', lastActivityAt: null, }], }); @@ -976,23 +976,23 @@ describe('ShippingConversationProcessingCard', () => { status: 'waiting_review', stage: 'waiting_review', currentGate: { - gateCode: 'inventory_matching', - nextActionCode: 'open_inventory_match_review', + gateCode: 'onhand_matching', + nextActionCode: 'open_onhand_match_review', blockingReasonCode: 'inventory_match_not_ready', }, - availableActions: ['open_inventory_match_review'], + availableActions: ['open_onhand_match_review'], uiState: { status: 'waiting_human', stage: 'waiting_review', lifecycleStage: 'order_review', lifecycleEntries: [], blocking_reason: { code: 'inventory_match_not_ready' }, - primary_action: { code: 'open_inventory_match_review', i18nKey: null, parameters: {}, executionMode: 'immediate' }, + primary_action: { code: 'open_onhand_match_review', i18nKey: null, parameters: {}, executionMode: 'immediate' }, secondary_actions: [], }, }), buildWorkItem('OT-PROC', { - stage: 'inventory_matching', + stage: 'onhand_matching', }), ], }, @@ -1006,7 +1006,7 @@ describe('ShippingConversationProcessingCard', () => { expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0); const task = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]'); expect(task.find('[data-testid="unified-action-primary"]').exists()).toBe(true); - expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('open_inventory_match_review'); + expect(task.find('[data-testid="unified-action-primary"]').text()).toContain('open_onhand_match_review'); await task.find('button').trigger('click'); await flushPromises(); diff --git a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue index b9c0670d..7408f774 100644 --- a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue +++ b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue @@ -775,7 +775,7 @@ function currentNeedLabel(task: ConversationProcessingUserTask): string { const labels: Record = { confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer', resolve_field_conflicts: 'chat.shippingProcessing.currentNeed.resolveFieldConflicts', - open_inventory_match_review: 'chat.shippingProcessing.currentNeed.inventoryMatch', + open_onhand_match_review: 'chat.shippingProcessing.currentNeed.inventoryMatch', open_order_processing: 'chat.shippingProcessing.currentNeed.orderDraft', retry: 'chat.shippingProcessing.currentNeed.retry', retry_parse: 'chat.shippingProcessing.currentNeed.retry', diff --git a/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts b/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts index ed5b1500..c8417140 100644 --- a/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts +++ b/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts @@ -280,7 +280,7 @@ describe('ShippingWorkflowTimeline', () => { it('uses the clicked secondary action lifecycle target instead of falling back to view-result handling', async () => { const file = fileProjection({ uiState: { - status: 'waiting_human', stage: 'inventory_matching', lifecycleStage: 'fulfillment_prep', + status: 'waiting_human', stage: 'onhand_matching', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [{ code: 'view_result', enabled: true, executionMode: 'navigate', diff --git a/frontend/src/features/chat/composables/useChatPage.ts b/frontend/src/features/chat/composables/useChatPage.ts index 7bcc8056..c899730f 100644 --- a/frontend/src/features/chat/composables/useChatPage.ts +++ b/frontend/src/features/chat/composables/useChatPage.ts @@ -459,7 +459,7 @@ export function useChatPage() { const leaveMessageHandlers = createLeaveMessageHandlers(leave); const shippingMessageHandlers = createShippingMessageHandlers(shipping); const trainingHandlers = createTrainingHandlers(training); - const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef)); + const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingOnhandPickerRef)); const shippingNoticePickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingNoticePickerRef)); const showChatRating = ref(false); @@ -627,13 +627,13 @@ export function useChatPage() { bumpWorkflowRefresh: shipping.bumpWorkflowRefresh, focusedConversationTaskNo: shipping.focusedConversationTaskNo, setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo, - shippingInventorySelectionActive: shipping.shippingInventorySelectionActive, - shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId, + shippingOnhandSelectionActive: shipping.shippingOnhandSelectionActive, + shippingOnhandSelectionTaskId: shipping.shippingOnhandSelectionTaskId, queryShippingShortageDetails: shipping.queryShippingShortageDetails, - selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask, - cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection, + selectShippingOnhandUploadTask: shipping.selectShippingOnhandUploadTask, + cancelShippingOnhandTaskSelection: shipping.cancelShippingOnhandTaskSelection, shippingSuggestedPrompt: shipping.shippingSuggestedPrompt, - handleShippingInventorySelected: shipping.handleShippingInventorySelected, + handleShippingOnhandSelected: shipping.handleShippingOnhandSelected, useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt, handleSidebarNewChat, goToWorkspace: routeSync.goToWorkspace, diff --git a/frontend/src/features/chat/composables/useChatShipping.ts b/frontend/src/features/chat/composables/useChatShipping.ts index 4d31a2bf..343f5803 100644 --- a/frontend/src/features/chat/composables/useChatShipping.ts +++ b/frontend/src/features/chat/composables/useChatShipping.ts @@ -187,13 +187,13 @@ export function useChatShipping(options: UseChatShippingOptions) { () => isShippingNoticeAgent.value && attachments.value.length > 0, ); const shippingAutoFlowRequested = ref(false); - const shippingInventoryPickerRef = ref(null); + const shippingOnhandPickerRef = ref(null); const shippingNoticePickerRef = ref(null); const pendingShippingUploadTaskId = ref(''); const pendingShippingNoticeTaskId = ref(''); - const pendingShippingInventoryFile = ref(null); - const shippingInventorySelectionActive = ref(false); - const shippingInventorySelectionTaskId = ref(''); + const pendingShippingOnhandFile = ref(null); + const shippingOnhandSelectionActive = ref(false); + const shippingOnhandSelectionTaskId = ref(''); const prepareMarkdownDisplayText = (text: string) => { return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value); @@ -264,9 +264,9 @@ export function useChatShipping(options: UseChatShippingOptions) { shippingAutoFlowRequested.value = false; pendingShippingUploadTaskId.value = ''; pendingShippingNoticeTaskId.value = ''; - pendingShippingInventoryFile.value = null; - shippingInventorySelectionActive.value = false; - shippingInventorySelectionTaskId.value = ''; + pendingShippingOnhandFile.value = null; + shippingOnhandSelectionActive.value = false; + shippingOnhandSelectionTaskId.value = ''; resolvedShippingTaskId.value = ''; activeShippingTaskDetail.value = null; lastConversationSyncKey.value = ''; @@ -667,11 +667,11 @@ export function useChatShipping(options: UseChatShippingOptions) { const { handleShippingAutoUploadFile, handleShippingAutoUploadNoticeBatch, - openShippingInventoryPicker, + openShippingOnhandPicker, openShippingNoticePicker, - selectShippingInventoryUploadTask, - cancelShippingInventoryTaskSelection, - handleShippingInventorySelected, + selectShippingOnhandUploadTask, + cancelShippingOnhandTaskSelection, + handleShippingOnhandSelected, shippingSuggestedPrompt, useShippingSuggestedPrompt, isShippingNoticeBatchSubmitting, @@ -681,14 +681,14 @@ export function useChatShipping(options: UseChatShippingOptions) { attachments, input, shippingAutoFlowRequested, - shippingInventoryPickerRef, + shippingOnhandPickerRef, shippingNoticePickerRef, pendingShippingUploadTaskId, pendingShippingNoticeTaskId, - pendingShippingInventoryFile, + pendingShippingOnhandFile, resolvedShippingTaskId, - shippingInventorySelectionActive, - shippingInventorySelectionTaskId, + shippingOnhandSelectionActive, + shippingOnhandSelectionTaskId, getActiveShippingTaskId, startChatTurn, refreshShippingActions, @@ -716,7 +716,7 @@ export function useChatShipping(options: UseChatShippingOptions) { getActiveShippingTaskId, messages, sendShippingMenuMessage, - openShippingInventoryPicker, + openShippingOnhandPicker, openShippingNoticePicker, openShippingCustomerDialog, executeShippingDecision, @@ -943,11 +943,11 @@ export function useChatShipping(options: UseChatShippingOptions) { isShippingNoticeAgent, prepareMarkdownDisplayText, shippingAutoFlowRequested, - shippingInventoryPickerRef, + shippingOnhandPickerRef, shippingNoticePickerRef, pendingShippingUploadTaskId, - shippingInventorySelectionActive, - shippingInventorySelectionTaskId, + shippingOnhandSelectionActive, + shippingOnhandSelectionTaskId, allowsSendWithAttachmentsOnly, shippingTaskIdFromQuery, isShippingActionBusy, @@ -963,10 +963,10 @@ export function useChatShipping(options: UseChatShippingOptions) { addShippingParseReviewLine, removeShippingParseReviewLine, handleShippingActionClick, - handleShippingInventorySelected, + handleShippingOnhandSelected, finalizeShippingAssistantMessage, - selectShippingInventoryUploadTask, - cancelShippingInventoryTaskSelection, + selectShippingOnhandUploadTask, + cancelShippingOnhandTaskSelection, shippingSuggestedPrompt, useShippingSuggestedPrompt, enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles, diff --git a/frontend/src/features/chat/page/useChatPageConversation.spec.ts b/frontend/src/features/chat/page/useChatPageConversation.spec.ts index d3dc5154..155ac3b5 100644 --- a/frontend/src/features/chat/page/useChatPageConversation.spec.ts +++ b/frontend/src/features/chat/page/useChatPageConversation.spec.ts @@ -77,14 +77,14 @@ const createUploadContext = ( attachments: ref([]), input: ref(''), shippingAutoFlowRequested: ref(false), - shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), + shippingOnhandPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), pendingShippingUploadTaskId: ref(''), pendingShippingNoticeTaskId: ref(''), - pendingShippingInventoryFile: ref(null), + pendingShippingOnhandFile: ref(null), resolvedShippingTaskId: ref(''), - shippingInventorySelectionActive: ref(false), - shippingInventorySelectionTaskId: ref(''), + shippingOnhandSelectionActive: ref(false), + shippingOnhandSelectionTaskId: ref(''), getActiveShippingTaskId: () => '', startChatTurn: vi.fn(async () => true), refreshShippingActions: vi.fn(async () => undefined), diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts index c1caf135..31be97cd 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts @@ -244,7 +244,7 @@ describe('useShippingOrderReview historical readonly', () => { it('maps confirmed case to non-closed lifecycle for post-confirm automation', () => { // 关键断言:confirmed 不得映射 closed,否则统一进度轨道会被误判为终态。 expect(mapReviewContextLifecycleStatus('confirmed', null)).toBe('building_order'); - expect(mapReviewContextLifecycleStatus('confirmed', 'inventory_matching')).toBe('inventory_matching'); + expect(mapReviewContextLifecycleStatus('confirmed', 'onhand_matching')).toBe('onhand_matching'); expect(mapReviewContextLifecycleStatus('closed', null)).toBe('closed'); expect(mapReviewContextLifecycleStatus('quality_issue', null)).toBe('closed'); }); @@ -518,7 +518,7 @@ describe('useShippingOrderReview build eligibility writes', () => { }); api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-1', status: 'completed' }); api.getProcessingWorkItem.mockResolvedValue({ - work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation', + work_item_no: 'OT-1', status: 'processing', stage: 'onhand_preparation', }); const review = useShippingOrderReview(); @@ -1222,8 +1222,8 @@ describe('useShippingOrderReview build eligibility writes', () => { workItemNo: 'OT-1', status: 'waiting_human', userStatus: 'waiting_human', - stage: 'inventory_matching', - currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' }, + stage: 'onhand_matching', + currentGate: { gateCode: 'onhand_matching', status: 'blocked_manual' }, uiState: { status: 'waiting_human', lifecycleStage: 'fulfillment_prep', @@ -1278,8 +1278,8 @@ describe('useShippingOrderReview build eligibility writes', () => { }); api.getEvidence.mockResolvedValue({ items: [] }); api.getProcessingWorkItem.mockResolvedValue({ - work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation', - currentGate: { gateCode: 'inventory_preparation', status: 'running' }, + work_item_no: 'OT-1', status: 'processing', stage: 'onhand_preparation', + currentGate: { gateCode: 'onhand_preparation', status: 'running' }, }); api.confirmCase.mockResolvedValue({ task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false, diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts index 51fe3b31..bd5c1673 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts @@ -229,7 +229,7 @@ export function mapReviewContextLifecycleStatus( if (cs === 'closed') return 'closed'; // [UI-05] confirmed ? closed if (cs === 'confirmed') { - if (['building_order', 'inventory_matching', 'generating_excel'].includes(rs)) return rs; + if (['building_order', 'onhand_matching', 'generating_excel'].includes(rs)) return rs; if (['manual_upload_pending', 'upload_rpa_pending', 'upload_rpa_running'].includes(rs)) return rs; return 'building_order'; } @@ -240,7 +240,7 @@ export function mapReviewContextLifecycleStatus( if (['layout_parsing', 'waiting_layout'].includes(rs)) return 'layout_parsing'; if (['routing', 'matching_profile', 'extracting', 'merging_supplement'].includes(rs)) return 'extracting'; if (['review_required', 'partially_completed', 'candidate_ready'].includes(rs)) return 'pending_review'; - if (['building_order', 'inventory_matching', 'generating_excel'].includes(rs)) return rs; + if (['building_order', 'onhand_matching', 'generating_excel'].includes(rs)) return rs; if (['draft', 'ready', 'unreviewed', 'superseded'].includes(cs)) return 'pending_review'; return 'pending_review'; } diff --git a/frontend/src/features/chat/shipping/conversationProcessingProjection.ts b/frontend/src/features/chat/shipping/conversationProcessingProjection.ts index 12b5ccb4..4c63bd1a 100644 --- a/frontend/src/features/chat/shipping/conversationProcessingProjection.ts +++ b/frontend/src/features/chat/shipping/conversationProcessingProjection.ts @@ -296,8 +296,8 @@ export function normalizeLifecycleStatus( const HUMAN_ACTION_CODES = new Set([ 'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate', 'open_order_review', 'open_order_processing', 'enter_manual_review', - 'open_inventory_match_review', 'rematch', 'match_inventory', - 'open_shortage_review', 'upload_inventory_file', 'open_manual_upload', + 'open_onhand_match_review', 'rematch', 'match_inventory', + 'open_shortage_review', 'upload_onhand_file', 'open_manual_upload', 'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', 'open_profile_review', ]); @@ -308,7 +308,7 @@ const PROCESSING_LIFECYCLES = new Set([ 'layout_parsing', 'extracting', 'building_order', - 'inventory_matching', + 'onhand_matching', 'generating_excel', 'upload_rpa_pending', 'upload_rpa_running', @@ -337,7 +337,7 @@ export function mapLifecycleToNodeStatus( status === 'layout_parsing' || status === 'extracting' || status === 'building_order' - || status === 'inventory_matching' + || status === 'onhand_matching' || status === 'generating_excel' ) { return 'running'; diff --git a/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts b/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts index c31573a3..6b3da509 100644 --- a/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts +++ b/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts @@ -34,15 +34,15 @@ describe('normalizeShippingProcessingProjection', () => { process_gate: { execution_no: 'EXE-1', status: 'blocked', - current_gate_code: 'inventory_preparation', + current_gate_code: 'onhand_preparation', expected_gate_version: 3, current_blocking_gate: { - gate_code: 'inventory_preparation', + gate_code: 'onhand_preparation', status: 'blocked_manual', evaluation_version: 3, }, - next_action_code: 'retry_inventory_preparation', - allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'], + next_action_code: 'retry_onhand_preparation', + allowed_actions: ['retry_onhand_preparation', 'upload_onhand_file'], }, available_actions: ['open_review'], ui_state: { @@ -75,9 +75,9 @@ describe('normalizeShippingProcessingProjection', () => { expect(normalized!.currentGate?.attemptNo).toBe(1); expect(normalized!.processGate).toMatchObject({ execution_no: 'EXE-1', - current_gate_code: 'inventory_preparation', + current_gate_code: 'onhand_preparation', expected_gate_version: 3, - next_action_code: 'retry_inventory_preparation', + next_action_code: 'retry_onhand_preparation', }); expect(normalized!.sourceSummary.filename).toBe('a.pdf'); expect(normalized!.sourceSummary.documentId).toBe(17); @@ -199,7 +199,7 @@ describe('normalizeShippingProcessingProjection', () => { submission_no: 'SUB-1', intake_no: 'INT-1', status: 'processing', - stage: 'inventory_matching', + stage: 'onhand_matching', progress_version: 2, last_activity_at: '2026-08-08T22:00:00', source_summary: {}, @@ -259,7 +259,7 @@ describe('normalizeShippingProcessingProjection', () => { workItemNo: 'OT-1', workItemType: 'order_task', status: 'waiting_review', - stage: 'inventory_matching', + stage: 'onhand_matching', userStatus: 'waiting_human', uiState: { status: 'waiting_human', lifecycleStage: 'fulfillment_prep' }, })).toBeNull(); diff --git a/frontend/src/features/chat/shipping/normalizeShippingProcessing.ts b/frontend/src/features/chat/shipping/normalizeShippingProcessing.ts index eebd1fcd..cef310ca 100644 --- a/frontend/src/features/chat/shipping/normalizeShippingProcessing.ts +++ b/frontend/src/features/chat/shipping/normalizeShippingProcessing.ts @@ -9,8 +9,8 @@ import type { ConversationProcessingUiState, OrderIntakeSourceType, ProcessGateSummary, - ShippingInventoryPerSourceAttempt, - ShippingInventoryPreparationSummary, + ShippingOnhandPerSourceAttempt, + ShippingOnhandPreparationSummary, ShippingOrderTaskSummary, ShippingProcessingBlockingReason, ShippingProcessingFacts, @@ -304,7 +304,7 @@ function normalizeAggregateSummary( * 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。 * 注意:只投影当前准备结果;失败后由具体 Gate 动作决定下一步。 */ -function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null { +function normalizeInventoryPreparation(raw: unknown): ShippingOnhandPreparationSummary | null { if (!raw || typeof raw !== 'object') return null; const item = raw as Record; const toStrArr = (value: unknown): string[] => { @@ -322,7 +322,7 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0; const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false); const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record | undefined; - const latestAttempts: Record = {}; + const latestAttempts: Record = {}; if (latestRaw && typeof latestRaw === 'object') { for (const [key, val] of Object.entries(latestRaw)) { if (!val || typeof val !== 'object') continue; @@ -331,7 +331,7 @@ function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparati if (!sourceCode) continue; const attemptNo = Number(row.attempt_no ?? row.attemptNo ?? 0) || 0; const status = String(row.status || '').trim().toLowerCase() || 'unknown'; - const entry: ShippingInventoryPerSourceAttempt = { + const entry: ShippingOnhandPerSourceAttempt = { sourceCode, attemptNo, status, diff --git a/frontend/src/features/chat/shipping/shippingDownload.ts b/frontend/src/features/chat/shipping/shippingDownload.ts index 5294f29c..6bd8822a 100644 --- a/frontend/src/features/chat/shipping/shippingDownload.ts +++ b/frontend/src/features/chat/shipping/shippingDownload.ts @@ -8,7 +8,7 @@ import { downloadWorkspaceShippingExportArchive as requestShippingExportArchive, workspaceShippingNoticeExportUrl, workspaceShippingExportUrl, - workspaceShippingInventoryFileUrl, + workspaceShippingOnhandFileUrl, workspaceShippingLineInventoryFileUrl, } from '@/features/chat/api/shipping.api'; import { getAuthHeaders } from '@/shared/utils/auth'; @@ -31,8 +31,8 @@ export async function downloadWorkspaceShippingNoticeExcelFile(businessNo: strin * @param taskId - 正式发货任务号,必须来自当前详情快照。 * @returns 下载完成后解析并触发浏览器保存。 */ -export async function downloadWorkspaceShippingInventoryFile(taskId: string): Promise { - await downloadWorkspaceShippingFile(workspaceShippingInventoryFileUrl(taskId), `${taskId}-inventory.xlsx`); +export async function downloadWorkspaceShippingOnhandFile(taskId: string): Promise { + await downloadWorkspaceShippingFile(workspaceShippingOnhandFileUrl(taskId), `${taskId}-inventory.xlsx`); } /** 下载某订单行实际匹配的库存快照;后端复核该文件号是否为当前行事实。 */ diff --git a/frontend/src/features/chat/shipping/shippingMapping.ts b/frontend/src/features/chat/shipping/shippingMapping.ts index d70f46d0..b96a0cc1 100644 --- a/frontend/src/features/chat/shipping/shippingMapping.ts +++ b/frontend/src/features/chat/shipping/shippingMapping.ts @@ -2,12 +2,12 @@ * features/chat/shipping/shippingMapping.ts * 用途:库存列映射消息 payload 读取与字段对齐 Markdown 生成。 * 依赖:shippingText.normalizeShippingHeaderForDisplay、chat.types、shipping.types、vue-i18n。 - * 逻辑:ShippingInventoryMappingMessage 与 useChatShippingMappingForm 读取 mapping 消息数据。 + * 逻辑:ShippingOnhandMappingFormPayload 与 useChatShippingMappingForm 读取 mapping 消息数据。 */ import i18n from '@/i18n'; import { normalizeShippingHeaderForDisplay } from './shippingText'; import type { ChatMessage } from '../types/chat.types'; -import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types'; +import type { ShippingOnhandMappingFormPayload } from '../types/shipping.types'; const tt = (key: string, params?: Record) => String(params ? i18n.global.t(key, params) : i18n.global.t(key)); @@ -15,24 +15,24 @@ const tt = (key: string, params?: Record) => /** * 从 shipping-inventory-mapping 类型消息中提取 taskId、schema_preview 与 form。 */ -export function getShippingInventoryMappingPayload(chatMsg: ChatMessage): ShippingInventoryMappingFormPayload | null { +export function getShippingOnhandMappingPayload(chatMsg: ChatMessage): ShippingOnhandMappingFormPayload | 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; + const taskId = String((payload as ShippingOnhandMappingFormPayload).taskId || '').trim(); + const schemaPreview = (payload as ShippingOnhandMappingFormPayload).schema_preview; + const form = (payload as ShippingOnhandMappingFormPayload).form; if (!taskId || !schemaPreview || !form) return null; - return payload as ShippingInventoryMappingFormPayload; + return payload as ShippingOnhandMappingFormPayload; } -export function hasShippingInventorySampleRows(chatMsg: ChatMessage): boolean { - const rows = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows; +export function hasShippingOnhandSampleRows(chatMsg: ChatMessage): boolean { + const rows = getShippingOnhandMappingPayload(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]; +export function getShippingOnhandSampleRowText(chatMsg: ChatMessage): string { + const row = getShippingOnhandMappingPayload(chatMsg)?.schema_preview?.sample_rows?.[0]; return Array.isArray(row) ? row.map((cell) => String(cell)).join(' | ') : ''; } diff --git a/frontend/src/features/chat/shipping/shippingProcessingFulfillment.ts b/frontend/src/features/chat/shipping/shippingProcessingFulfillment.ts index 26d8c10c..140f9287 100644 --- a/frontend/src/features/chat/shipping/shippingProcessingFulfillment.ts +++ b/frontend/src/features/chat/shipping/shippingProcessingFulfillment.ts @@ -12,7 +12,7 @@ /** 复核/任务台共用的履约四节点 stage 键。 */ export const FULFILLMENT_PROGRESS_NODES = [ 'building_order', - 'inventory_matching', + 'onhand_matching', 'generating_excel', 'freight_uploading', ] as const; @@ -116,7 +116,7 @@ export function fulfillmentNodeIndexFromStage( if (st === 'completed' || s === 'completed') return 3; if (s === 'freight_uploading' || st === 'automating') return 3; if (s === 'excel_generating' || s === 'generating_excel') return 2; - if (s === 'inventory_matching' || s.startsWith('inventory_')) return 1; + if (s === 'onhand_matching' || s.startsWith('inventory_')) return 1; if ( s === 'building_order' || s === 'order_creating' diff --git a/frontend/src/features/chat/shipping/shippingStepper.spec.ts b/frontend/src/features/chat/shipping/shippingStepper.spec.ts index 88beca33..f3459d62 100644 --- a/frontend/src/features/chat/shipping/shippingStepper.spec.ts +++ b/frontend/src/features/chat/shipping/shippingStepper.spec.ts @@ -43,7 +43,7 @@ describe('shippingStepper', () => { { code: 'upload_complete', status: 'pending' }, ]); const steps = applyShippingProcessingStageToSteps(base, { - stage: 'inventory_matching', + stage: 'onhand_matching', status: 'running', }); expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending', 'pending']); diff --git a/frontend/src/features/chat/shipping/shippingStepper.ts b/frontend/src/features/chat/shipping/shippingStepper.ts index cc96bb0d..590d44f6 100644 --- a/frontend/src/features/chat/shipping/shippingStepper.ts +++ b/frontend/src/features/chat/shipping/shippingStepper.ts @@ -86,9 +86,9 @@ const PROCESSING_STAGE_INDEX_MAP: Record = { duplicate_checking: 1, waiting_review: 1, order_creating: 1, - inventory_source_resolving: 2, - inventory_fetching: 2, - inventory_matching: 2, + onhand_source_resolving: 2, + onhand_fetching: 2, + onhand_matching: 2, excel_generating: 2, freight_uploading: 3, completed: 4, diff --git a/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts b/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts index b7bc0f55..4176f339 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMappingForm.ts @@ -7,17 +7,17 @@ import { nextTick } from 'vue'; import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api'; import { buildShippingApplyMappingTurn } from './shippingTurnActions'; -import { getShippingInventoryMappingPayload } from './shippingMapping'; +import { getShippingOnhandMappingPayload } 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 { ShippingOnhandMappingFormPayload } from '../types/shipping.types'; import type { Ref } from 'vue'; export interface ShippingMappingFormContext { messages: Ref; chatScrollContainer: Ref; - shippingInventorySchemaPreviewCache: Ref>; - shippingInventoryPickerRef: Ref; + shippingOnhandSchemaPreviewCache: Ref>; + shippingOnhandPickerRef: Ref; pendingShippingUploadTaskId: Ref; resolvedShippingTaskId: Ref; newLocalMessageId: (prefix: string) => string; @@ -37,7 +37,7 @@ export interface ShippingMappingFormContext { * @returns 打开、应用和重传库存映射表单的处理函数 */ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) { - const scrollToLastShippingInventoryMapping = async (): Promise => { + const scrollToLastShippingOnhandMapping = async (): Promise => { const container = ctx.chatScrollContainer.value; if (!container) return false; let idx = -1; @@ -56,22 +56,22 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex return true; }; - const openShippingInventoryMappingFormForTask = async (taskId: string): Promise => { + const openShippingOnhandMappingFormForTask = 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); + const payload = getShippingOnhandMappingPayload(chatMsg); if (payload?.taskId?.trim().toUpperCase() === id) return i; } return -1; })(); if (existingIdx >= 0) { - return scrollToLastShippingInventoryMapping(); + return scrollToLastShippingOnhandMapping(); } - const schemaPreview = ctx.shippingInventorySchemaPreviewCache.value[id]; + const schemaPreview = ctx.shippingOnhandSchemaPreviewCache.value[id]; if (!schemaPreview || typeof schemaPreview !== 'object') { ctx.msg.warning(ctx.t('chat.shippingNoticeToast.schemaPreviewMissing')); return false; @@ -101,18 +101,18 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex reservation_id: String(suggested?.reservation_id || '').trim(), }, applying: false, - } as ShippingInventoryMappingFormPayload, + } as ShippingOnhandMappingFormPayload, local_id: ctx.newLocalMessageId('shipping-assistant'), local_only: true, }; ctx.messages.value.push(mappingMsg); await ctx.saveLocalMessageToBackend(mappingMsg); - await scrollToLastShippingInventoryMapping(); + await scrollToLastShippingOnhandMapping(); return true; }; - const applyShippingInventoryMappingForm = async (msgObj: ChatMessage) => { - const payload = getShippingInventoryMappingPayload(msgObj); + const applyShippingOnhandMappingForm = async (msgObj: ChatMessage) => { + const payload = getShippingOnhandMappingPayload(msgObj); if (!payload) return; if (payload.applying) return; const taskId = String(payload.taskId || '').trim(); @@ -159,18 +159,18 @@ export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContex } }; - const reuploadShippingInventoryFromMappingForm = (msgObj: ChatMessage) => { - const payload = getShippingInventoryMappingPayload(msgObj); + const reuploadShippingOnhandFromMappingForm = (msgObj: ChatMessage) => { + const payload = getShippingOnhandMappingPayload(msgObj); if (!payload) return; const taskId = String(payload.taskId || '').trim(); if (!taskId) return; ctx.pendingShippingUploadTaskId.value = taskId; - ctx.shippingInventoryPickerRef.value?.click(); + ctx.shippingOnhandPickerRef.value?.click(); }; return { - openShippingInventoryMappingFormForTask, - applyShippingInventoryMappingForm, - reuploadShippingInventoryFromMappingForm, + openShippingOnhandMappingFormForTask, + applyShippingOnhandMappingForm, + reuploadShippingOnhandFromMappingForm, }; } diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts index b556a6ae..7e91f703 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.spec.ts @@ -24,7 +24,7 @@ const createContext = ( getActiveShippingTaskId: () => 'SN-ACTIVE-001', messages: ref([]), sendShippingMenuMessage: vi.fn(async () => undefined), - openShippingInventoryPicker: vi.fn((_taskId?: string) => true), + openShippingOnhandPicker: vi.fn((_taskId?: string) => true), openShippingNoticePicker: vi.fn((_taskId?: string) => true), executeShippingDecision: vi.fn(async () => true), executeShippingManualUpload: vi.fn(async () => true), @@ -103,12 +103,12 @@ describe('useChatShippingMenuHandler', () => { const { handleShippingMenuAction } = createShippingMenuHandlers(ctx); await handleShippingMenuAction( - { id: 'upload_inventory_file', label: '上传库存文件', message: '请上传库存文件' }, + { id: 'upload_onhand_file', label: '上传库存文件', message: '请上传库存文件' }, undefined, { taskId: 'sn-picker-123' }, ); - expect(ctx.openShippingInventoryPicker).toHaveBeenCalledWith('SN-PICKER-123'); + expect(ctx.openShippingOnhandPicker).toHaveBeenCalledWith('SN-PICKER-123'); }); it('passes explicit taskId into notice picker actions', async () => { diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts index bad1e91e..708a0d7e 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts @@ -14,7 +14,7 @@ export interface ShippingMenuHandlerContext { getActiveShippingTaskId: () => string; messages: Ref; sendShippingMenuMessage: (message: string) => Promise; - openShippingInventoryPicker: (taskId?: string) => boolean; + openShippingOnhandPicker: (taskId?: string) => boolean; openShippingNoticePicker: (taskId?: string) => boolean; openShippingCustomerDialog: (taskId: string) => Promise; executeShippingDecision: ( @@ -77,8 +77,8 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { ctx.openShippingNoticePicker(resolveTaskId()); return; } - if (action.id === 'upload_inventory_file') { - ctx.openShippingInventoryPicker(resolveTaskId()); + if (action.id === 'upload_onhand_file') { + ctx.openShippingOnhandPicker(resolveTaskId()); return; } if (action.id && [ diff --git a/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts index ff96560e..2068af5a 100644 --- a/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingSendHandler.spec.ts @@ -30,7 +30,7 @@ const createContext = ( loadHistory: vi.fn(async () => undefined), sendShippingMenuMessage: vi.fn(async () => undefined), startChatTurn: vi.fn(async () => true), - openShippingInventoryPicker: vi.fn(() => true), + openShippingOnhandPicker: vi.fn(() => true), executeShippingDecision: vi.fn(async () => true), executeShippingManualUpload: vi.fn(async () => true), handleShippingMenuAction: vi.fn(async () => undefined), diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts index 5c0777c5..23c4f0b8 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.spec.ts @@ -39,14 +39,14 @@ const createContext = ( attachments: ref([]), input: ref(''), shippingAutoFlowRequested: ref(false), - shippingInventoryPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), + shippingOnhandPickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), shippingNoticePickerRef: ref({ click: vi.fn() } as unknown as HTMLInputElement), pendingShippingUploadTaskId: ref(''), pendingShippingNoticeTaskId: ref(''), - pendingShippingInventoryFile: ref(null), + pendingShippingOnhandFile: ref(null), resolvedShippingTaskId: ref(''), - shippingInventorySelectionActive: ref(false), - shippingInventorySelectionTaskId: ref(''), + shippingOnhandSelectionActive: ref(false), + shippingOnhandSelectionTaskId: ref(''), getActiveShippingTaskId: () => 'SN-ACTIVE-001', startChatTurn: vi.fn(async () => true), refreshShippingActions: vi.fn(async () => undefined), @@ -100,11 +100,11 @@ describe('useChatShippingUploadHandler', () => { it('opens inventory picker for explicit taskId instead of current active task', () => { const inventoryClick = vi.fn(); const ctx = createContext({ - shippingInventoryPickerRef: ref({ click: inventoryClick } as unknown as HTMLInputElement), + shippingOnhandPickerRef: ref({ click: inventoryClick } as unknown as HTMLInputElement), }); - const { openShippingInventoryPicker } = createShippingUploadHandlers(ctx); + const { openShippingOnhandPicker } = createShippingUploadHandlers(ctx); - const ok = openShippingInventoryPicker('sn-target-100'); + const ok = openShippingOnhandPicker('sn-target-100'); expect(ok).toBe(true); expect(ctx.pendingShippingUploadTaskId.value).toBe('SN-TARGET-100'); @@ -113,11 +113,11 @@ describe('useChatShippingUploadHandler', () => { 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 { handleShippingOnhandSelected } = 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); + await handleShippingOnhandSelected(event); expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({ actionType: 'shipping.upload_inventory', diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts index 840bac07..1bd2c669 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts @@ -35,14 +35,14 @@ export interface ShippingUploadHandlerContext { attachments: Ref; input: Ref; shippingAutoFlowRequested: Ref; - shippingInventoryPickerRef: Ref; + shippingOnhandPickerRef: Ref; shippingNoticePickerRef: Ref; pendingShippingUploadTaskId: Ref; pendingShippingNoticeTaskId: Ref; - pendingShippingInventoryFile: Ref; + pendingShippingOnhandFile: Ref; resolvedShippingTaskId: Ref; - shippingInventorySelectionActive: Ref; - shippingInventorySelectionTaskId: Ref; + shippingOnhandSelectionActive: Ref; + shippingOnhandSelectionTaskId: Ref; getActiveShippingTaskId: () => string; startChatTurn: (options: StartChatTurnOptions) => Promise; refreshShippingActions: () => Promise; @@ -72,8 +72,8 @@ export interface ShippingUploadHandlerContext { */ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) { const resetInventoryTaskSelection = () => { - ctx.shippingInventorySelectionActive.value = false; - ctx.shippingInventorySelectionTaskId.value = ''; + ctx.shippingOnhandSelectionActive.value = false; + ctx.shippingOnhandSelectionTaskId.value = ''; }; const runInventoryUploadChatTurn = async (taskId: string, file: File) => { @@ -93,7 +93,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) }, }, }); - if (!ok) ctx.msg.warning(ctx.t('chat.shippingInventoryUploadFailed')); + if (!ok) ctx.msg.warning(ctx.t('chat.shippingOnhandUploadFailed')); return ok; }; @@ -102,34 +102,34 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) await runInventoryUploadChatTurn(taskId, file); }; - const selectShippingInventoryUploadTask = (taskId: string): boolean => { + const selectShippingOnhandUploadTask = (taskId: string): boolean => { const normalizedTaskId = String(taskId || '').trim().toUpperCase(); if (!normalizedTaskId) { ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId')); return false; } ctx.resolvedShippingTaskId.value = normalizedTaskId; - ctx.shippingInventorySelectionTaskId.value = normalizedTaskId; + ctx.shippingOnhandSelectionTaskId.value = normalizedTaskId; ctx.pendingShippingUploadTaskId.value = normalizedTaskId; - ctx.shippingInventorySelectionActive.value = false; + ctx.shippingOnhandSelectionActive.value = false; - const pendingFile = ctx.pendingShippingInventoryFile.value; + const pendingFile = ctx.pendingShippingOnhandFile.value; if (pendingFile) { - ctx.pendingShippingInventoryFile.value = null; + ctx.pendingShippingOnhandFile.value = null; ctx.pendingShippingUploadTaskId.value = ''; void uploadInventoryForTask(normalizedTaskId, pendingFile).catch((e: unknown) => { - const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed'); + const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingOnhandUploadFailed'); ctx.msg.warning(errorMessage); }); return true; } - ctx.shippingInventoryPickerRef.value?.click(); + ctx.shippingOnhandPickerRef.value?.click(); return true; }; - const cancelShippingInventoryTaskSelection = () => { - ctx.pendingShippingInventoryFile.value = null; + const cancelShippingOnhandTaskSelection = () => { + ctx.pendingShippingOnhandFile.value = null; ctx.pendingShippingUploadTaskId.value = ''; resetInventoryTaskSelection(); }; @@ -258,13 +258,13 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) await runNoticeBatchChatTurn(noticeFiles); }; - const openShippingInventoryPicker = (taskId?: string): boolean => { + const openShippingOnhandPicker = (taskId?: string): boolean => { const resolvedTaskId = String(taskId || ctx.getActiveShippingTaskId() || '').trim().toUpperCase(); if (!resolvedTaskId) { ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId')); return false; } - return selectShippingInventoryUploadTask(resolvedTaskId); + return selectShippingOnhandUploadTask(resolvedTaskId); }; /** @@ -284,23 +284,23 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) return true; }; - const handleShippingInventorySelected = async (event: Event) => { + const handleShippingOnhandSelected = async (event: Event) => { const fileInput = event.target as HTMLInputElement; const file = fileInput.files?.[0]; fileInput.value = ''; const taskId = ctx.pendingShippingUploadTaskId.value; ctx.pendingShippingUploadTaskId.value = ''; if (!file || !taskId) { - ctx.shippingInventorySelectionTaskId.value = ''; + ctx.shippingOnhandSelectionTaskId.value = ''; return; } try { await uploadInventoryForTask(taskId, file); } catch (e: unknown) { - const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingInventoryUploadFailed'); + const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingOnhandUploadFailed'); ctx.msg.warning(errorMessage); } finally { - ctx.shippingInventorySelectionTaskId.value = ''; + ctx.shippingOnhandSelectionTaskId.value = ''; } }; @@ -325,11 +325,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) return { handleShippingAutoUploadFile, handleShippingAutoUploadNoticeBatch, - openShippingInventoryPicker, + openShippingOnhandPicker, openShippingNoticePicker, - selectShippingInventoryUploadTask, - cancelShippingInventoryTaskSelection, - handleShippingInventorySelected, + selectShippingOnhandUploadTask, + cancelShippingOnhandTaskSelection, + handleShippingOnhandSelected, shippingSuggestedPrompt, useShippingSuggestedPrompt, isShippingNoticeBatchSubmitting, diff --git a/frontend/src/features/chat/shipping/useShippingProcessingWorkItem.spec.ts b/frontend/src/features/chat/shipping/useShippingProcessingWorkItem.spec.ts index fe578529..913c6ab6 100644 --- a/frontend/src/features/chat/shipping/useShippingProcessingWorkItem.spec.ts +++ b/frontend/src/features/chat/shipping/useShippingProcessingWorkItem.spec.ts @@ -35,7 +35,7 @@ describe('useShippingProcessingWorkItem', () => { workItemNo: 'OT-20260905-DAC55F90', sourceType: 'eml', status: 'waiting_review', - stage: 'inventory_matching', + stage: 'onhand_matching', progressVersion: 24, lastActivityAt: '2026-09-05T11:25:45Z', submissionNo: 'SOS-1', @@ -43,11 +43,11 @@ describe('useShippingProcessingWorkItem', () => { userStatus: 'waiting_human', uiState: { status: 'waiting_human', - stage: 'inventory_matching', + stage: 'onhand_matching', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [], blocking_reason: { code: 'inventory_shortage_review_required' }, - primary_action: { code: 'retry_inventory_matching' }, + primary_action: { code: 'retry_onhand_matching' }, secondary_actions: [], }, sourceSummary: { @@ -87,7 +87,7 @@ describe('useShippingProcessingWorkItem', () => { expect(api!.projection.value?.workItemNo).toBe('OT-20260905-DAC55F90'); expect(api!.projection.value?.userStatus).toBe('waiting_human'); expect(api!.projection.value?.uiState?.lifecycleStage).toBe('fulfillment_prep'); - expect(api!.projection.value?.uiState?.primary_action?.code).toBe('retry_inventory_matching'); + expect(api!.projection.value?.uiState?.primary_action?.code).toBe('retry_onhand_matching'); expect(api!.error.value).toBeNull(); }); }); diff --git a/frontend/src/features/chat/types/shipping.api.types.ts b/frontend/src/features/chat/types/shipping.api.types.ts index 7a5d1600..163cac3e 100644 --- a/frontend/src/features/chat/types/shipping.api.types.ts +++ b/frontend/src/features/chat/types/shipping.api.types.ts @@ -50,11 +50,11 @@ export type ShippingProcessingStage = | 'candidate_creating' | 'customer_resolving' | 'duplicate_checking' - | 'inventory_source_resolving' + | 'onhand_source_resolving' | 'waiting_review' | 'order_creating' - | 'inventory_fetching' - | 'inventory_matching' + | 'onhand_fetching' + | 'onhand_matching' | 'excel_generating' | 'freight_uploading' | 'completed'; @@ -86,12 +86,12 @@ export type ShippingProcessingActionIntent = | 'confirm_customer' | 'resolve_field_conflicts' | 'adjudicate_duplicate' - | 'open_inventory_match_review' + | 'open_onhand_match_review' | 'open_shortage_review' - | 'upload_inventory_file' - | 'reload_inventory_result' - | 'retry_inventory_preparation' - | 'retry_inventory_matching' + | 'upload_onhand_file' + | 'reload_onhand_result' + | 'retry_onhand_preparation' + | 'retry_onhand_matching' | 'retry_parse' | 'retry_failed_documents' | 'retry_failed_attachments' @@ -106,8 +106,8 @@ export type ShippingProcessingActionIntent = | 'retry_with_latest_rules' | 'recheck_freeze_readiness' | 'retry_task_creation' - | 'retry_inventory_field_mapping' - | 'recheck_inventory_sufficiency' + | 'retry_onhand_field_mapping' + | 'recheck_onhand_sufficiency' | 'recheck_excel_readiness' | 'retry_stp_auto_create' | 'reparse' @@ -128,11 +128,11 @@ export const SHIPPING_PROCESSING_STAGES: readonly ShippingProcessingStage[] = [ 'candidate_creating', 'customer_resolving', 'duplicate_checking', - 'inventory_source_resolving', + 'onhand_source_resolving', 'waiting_review', 'order_creating', - 'inventory_fetching', - 'inventory_matching', + 'onhand_fetching', + 'onhand_matching', 'excel_generating', 'freight_uploading', 'completed', @@ -252,7 +252,7 @@ export interface ShippingProcessingFacts { [key: string]: unknown; } -export interface ShippingInventoryCandidateSetSummary { +export interface ShippingOnhandCandidateSetSummary { id: number; version: number; status: 'draft' | 'frozen' | 'superseded' | 'invalidated'; @@ -262,7 +262,7 @@ export interface ShippingInventoryCandidateSetSummary { manifestSnapshotSha256?: string | null; } -export interface ShippingInventoryCandidateSourceDetail { +export interface ShippingOnhandCandidateSourceDetail { id: number; candidateSetId: number; sourceCode: string; @@ -273,7 +273,7 @@ export interface ShippingInventoryCandidateSourceDetail { sourceConfigVersion?: string | null; } -export interface ShippingInventoryCandidateLineDetail { +export interface ShippingOnhandCandidateLineDetail { candidateLineId: number; candidateSetId: number; lineNo: number; @@ -283,12 +283,12 @@ export interface ShippingInventoryCandidateLineDetail { allowedSourceCodes: string[]; } -export interface ShippingTaskInventoryCandidatesResponse { +export interface ShippingTaskOnhandCandidatesResponse { taskNo: string; - currentSet: ShippingInventoryCandidateSetSummary | null; - sources: ShippingInventoryCandidateSourceDetail[]; - lines: ShippingInventoryCandidateLineDetail[]; - history: ShippingInventoryCandidateSetSummary[]; + currentSet: ShippingOnhandCandidateSetSummary | null; + sources: ShippingOnhandCandidateSourceDetail[]; + lines: ShippingOnhandCandidateLineDetail[]; + history: ShippingOnhandCandidateSetSummary[]; blockingReason?: ShippingProcessingBlockingReason | null; primaryAction?: ShippingProcessingPrimaryAction | null; } @@ -400,15 +400,15 @@ export interface ShippingProcessingProjection { * 权威事实源:summarize_inventory_rpa_latest_attempts(); * 前端按钮禁用/重试文案/状态徽章全部直接读本对象,禁止继续拼接旧字段合成 running。 */ - inventoryPreparation?: ShippingInventoryPreparationSummary | null; + inventoryPreparation?: ShippingOnhandPreparationSummary | null; } /** * 题4A & 7A:逐源 inventory 准备状态(ShippingProcessingProjection.inventoryPreparation)。 * 按实际冻结源 required_sources 为基准分类并暴露当前成功、等待和失败事实。 */ -export interface ShippingInventoryPreparationSummary { - /** 实际任务级冻结源(task.task_frozen_inventory_source_codes),顺序以冻结记录为准。 */ +export interface ShippingOnhandPreparationSummary { + /** 实际任务级冻结源(task.task_frozen_onhand_source_codes),顺序以冻结记录为准。 */ requiredSources: string[]; /** 已就绪:有 prepared 状态 Attempt,且存在有效的 InventoryFile / TaskInventoryLink。 */ preparedSources: string[]; @@ -424,14 +424,14 @@ export interface ShippingInventoryPreparationSummary { * 按冻结源逐源最近 Attempt 摘要(source_code → 结构化记录)。 * 用于 UI tooltip/详情;按钮禁用不直接读本字典,读上面的 required/prepared/pending/failed 集合。 */ - latestAttempts?: Record; + latestAttempts?: Record; } /** * 逐源最近一次 Inventory RPA Attempt 摘要(inventoryPreparation.latestAttempts[sourceCode])。 * 仅用于 UI 展示;业务判定必须走顶层 *_sources 集合。 */ -export interface ShippingInventoryPerSourceAttempt { +export interface ShippingOnhandPerSourceAttempt { sourceCode: string; attemptNo: number; /** queued | running | consumed | failed | skipped */ @@ -795,7 +795,7 @@ export type InventorySourceMethod = | 'rule_evaluation_freeze' | 'legacy_migrated'; -export interface ShippingInventorySourceCandidate { +export interface ShippingOnhandSourceCandidate { source_code: string; display_name?: string | null; warehouse_id?: string | null; @@ -804,12 +804,12 @@ export interface ShippingInventorySourceCandidate { matched_by?: string | null; } -export interface ShippingInventorySourceResolution { +export interface ShippingOnhandSourceResolution { status?: InventorySourceStatus | null; method?: InventorySourceMethod | null; reason?: string | null; release_field_values?: Record; - candidates?: ShippingInventorySourceCandidate[]; + candidates?: ShippingOnhandSourceCandidate[]; destination_candidates?: string[]; evidence?: Record[]; conflicts?: string[]; @@ -817,7 +817,7 @@ export interface ShippingInventorySourceResolution { routing_fingerprint?: string | null; } -export interface ShippingInventorySnapshot { +export interface ShippingOnhandSnapshot { inventory_file_no?: string | null; source_code?: string | null; warehouse_id?: string | null; @@ -893,7 +893,7 @@ export interface ShippingTaskSummary { }; rpa_runtime?: ShippingRpaRuntime | null; rpa_inventory_source?: Record | null; - inventory_source_resolution?: ShippingInventorySourceResolution | null; + inventory_source_resolution?: ShippingOnhandSourceResolution | null; destination_code?: string | null; destination_city?: string | null; destination_country?: string | null; @@ -904,7 +904,7 @@ export interface ShippingTaskSummary { inventory_source_method?: InventorySourceMethod | null; inventory_source_config_version?: string | null; inventory_routing_fingerprint?: string | null; - inventory_snapshot?: ShippingInventorySnapshot | null; + onhand_snapshot?: ShippingOnhandSnapshot | null; created_at?: string | null; updated_at?: string | null; ui_state?: ShippingTaskUiState; @@ -1033,13 +1033,13 @@ export type ShippingProcessGateCode = | 'customer_resolution' | 'duplicate_detection' | 'field_conflict_resolution' - | 'inventory_source_routing' + | 'onhand_source_routing' | 'order_freeze_readiness' | 'task_creation' - | 'inventory_preparation' - | 'inventory_field_mapping' - | 'inventory_matching' - | 'inventory_sufficiency' + | 'onhand_preparation' + | 'onhand_field_mapping' + | 'onhand_matching' + | 'onhand_sufficiency' | 'excel_readiness' | 'artifact_generation' | 'freight_upload_rpa' @@ -1080,17 +1080,17 @@ export type ShippingProcessGateActionCode = | 'retry_with_latest_rules' | 'recheck_freeze_readiness' | 'retry_task_creation' - | 'reload_inventory_result' - | 'retry_inventory_preparation' - | 'poll_inventory_preparation' - | 'upload_inventory_file' - | 'retry_inventory_field_mapping' - | 'retry_inventory_matching' - | 'retry_inventory_from_preparation' - | 'retry_inventory_from_field_mapping' - | 'retry_inventory_from_matching' - | 'open_inventory_match_review' - | 'recheck_inventory_sufficiency' + | 'reload_onhand_result' + | 'retry_onhand_preparation' + | 'poll_onhand_preparation' + | 'upload_onhand_file' + | 'retry_onhand_field_mapping' + | 'retry_onhand_matching' + | 'retry_onhand_from_preparation' + | 'retry_onhand_from_field_mapping' + | 'retry_onhand_from_matching' + | 'open_onhand_match_review' + | 'recheck_onhand_sufficiency' | 'open_shortage_review' | 'recheck_excel_readiness' | 'regenerate_excel_artifact' @@ -1354,7 +1354,7 @@ export interface ShippingTaskDetail extends ShippingTaskSummary { order_snapshot_id?: number | null; order_data_version?: number | null; field_conflicts?: ShippingFieldConflict[] | null; - inventory_verifications?: ShippingInventoryVerification[]; + inventory_verifications?: ShippingOnhandVerification[]; export_artifacts?: ShippingExportArtifact[]; upload_attempts?: ShippingUploadAttempt[]; events: ShippingTaskEvent[]; @@ -1685,7 +1685,7 @@ export interface ShippingFreightNoticeGroupsResponse { reason?: 'po_missing' | 'no_business_notice' | string | null; } -export interface ShippingInventoryUploadResponse { +export interface ShippingOnhandUploadResponse { status: string; message?: string; task_id?: string; @@ -1779,20 +1779,20 @@ export interface ShippingNoticeLayoutSummary { unsupported: number; } -export interface ShippingInventoryVerificationLine { +export interface ShippingOnhandVerificationLine { reservation_id: string; required_qty: string; available_qty: string; status: 'available' | 'shortage' | 'invalid' | string; } -export interface ShippingInventoryVerification { +export interface ShippingOnhandVerification { id: number; status: string; inventory_snapshot_id?: number | null; source_config_version?: string | null; created_at?: string | null; - lines: ShippingInventoryVerificationLine[]; + lines: ShippingOnhandVerificationLine[]; } export interface ShippingExportArtifact { @@ -2413,7 +2413,7 @@ export interface ShippingOrderReviewInventoryMatchedRule { * 库存源单源不可用原因码(unavailable_reasons 的值)。 * 与 backend error_explainability_contract.INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES_EMITTED 对齐。 */ -export type ShippingInventorySourceUnavailableReasonCode = +export type ShippingOnhandSourceUnavailableReasonCode = | 'source_not_found' | 'source_disabled' | 'source_runtime_unavailable' @@ -2427,7 +2427,7 @@ export type ShippingInventorySourceUnavailableReasonCode = * 特别区分:no_inventory_source_candidates(规则未命中)≠ * inventory_source_unavailable(命中但源不可用)≠ require_manual_review(冲突)。 */ -export type ShippingInventorySourceLineBlockReasonCode = +export type ShippingOnhandSourceLineBlockReasonCode = | 'no_inventory_source_candidates' | 'inventory_source_unavailable' | 'require_manual_review' @@ -2435,7 +2435,7 @@ export type ShippingInventorySourceLineBlockReasonCode = | 'manual_inventory_source_invalid' | 'inventory_source_conflicted' | 'inventory_source_changed' - | 'inventory_source_identity_mismatch' + | 'onhand_source_identity_mismatch' | string; /** @@ -2457,7 +2457,7 @@ export interface ShippingOrderReviewInventoryRuleSuggestion { raw_source_codes?: string[]; unavailable_source_codes?: string[]; /** 不可用源编码 → 稳定原因码(非文案) */ - unavailable_reasons?: Record; + unavailable_reasons?: Record; routing_status?: string; rule_versions?: ShippingOrderReviewInventoryRuleVersion[]; matched_rule_ids?: number[]; @@ -2479,7 +2479,7 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection { /** 规则命中但当前不可用的源 */ unavailable_source_codes?: string[]; /** 不可用源编码 → 稳定原因码(非文案;前端用 i18n 渲染) */ - unavailable_reasons?: Record; + unavailable_reasons?: Record; matched_rule_ids?: number[]; matched_rules?: ShippingOrderReviewInventoryMatchedRule[]; rule_versions?: ShippingOrderReviewInventoryRuleVersion[]; @@ -2490,7 +2490,7 @@ export interface ShippingOrderReviewBuildEligibilityLineProjection { rule_source_codes?: string[]; routing_status?: string; can_build?: boolean; - block_reason?: ShippingInventorySourceLineBlockReasonCode | null; + block_reason?: ShippingOnhandSourceLineBlockReasonCode | null; selection_mode?: string; manual_reason?: string; } @@ -2510,7 +2510,7 @@ export interface ShippingOrderReviewBuildEligibilityIssue { raw_rule_source_codes?: string[]; message?: string | null; unavailable_source_codes?: string[]; - unavailable_reasons?: Record; + unavailable_reasons?: Record; explainability?: ShippingExplainabilityReason | null; low_confidence_fields?: Array<{ field_code: string; @@ -3134,13 +3134,13 @@ export interface ShippingOrderReviewLineFulfillmentDecision { /** 行级履约决定码(与后端 ALLOWED_DECISIONS 对齐)。 */ export type ShippingOrderReviewLineFulfillmentDecisionCode = - | 'wait_inventory' + | 'wait_onhand' | 'fulfill_complete_line_now' | 'close_unfulfillable' | 'reopen' | 'use_new_inventory_file' | 'change_inventory_source' - | 'release_inventory_shortage'; + | 'release_onhand_shortage'; /** 行级履约与库存缺口投影行(含 OT 匹配事实与 allowed_actions)。 */ export interface ShippingOrderReviewLineFulfillmentLine { @@ -3195,7 +3195,7 @@ export interface ShippingOrderReviewLineFulfillmentLine { field_id: string; display_name: string; value?: string | null; - value_source?: 'inventory_snapshot' | 'manual_required' | string; + value_source?: 'onhand_snapshot' | 'manual_required' | string; requires_manual?: boolean; }>; /** 字段无法受控解析时的稳定错误码;UI 必须隐藏放行入口。 */ @@ -3300,7 +3300,7 @@ export type ShippingWorkflowItemLifecycleStatus = | 'layout_parsing' | 'extracting' | 'building_order' - | 'inventory_matching' + | 'onhand_matching' | 'generating_excel' | 'pending_review' | 'reparse_failed' diff --git a/frontend/src/features/chat/types/shipping.types.ts b/frontend/src/features/chat/types/shipping.types.ts index d6478765..6f072d58 100644 --- a/frontend/src/features/chat/types/shipping.types.ts +++ b/frontend/src/features/chat/types/shipping.types.ts @@ -272,7 +272,7 @@ export interface ShippingActionButton { source_code?: string; } -export interface ShippingInventoryMappingFormPayload { +export interface ShippingOnhandMappingFormPayload { taskId: string; schema_preview: { sample_rows?: unknown[][]; diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts index b21de571..1168b175 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts @@ -617,7 +617,7 @@ async function mountView(query: Record = {}) { waiting_system_start: '等待系统启动', waiting_to_start: '等待系统启动', order_creating: '等待系统启动', - inventory_matching: '库存匹配', + onhand_matching: '库存匹配', excel_generating: 'Excel 生成', }, }, @@ -731,7 +731,7 @@ async function mountView(query: Record = {}) { shippingProcessing: { stage: { order_creating: '创建正式订单', - inventory_matching: '库存匹配', + onhand_matching: '库存匹配', }, stageLabel: { waiting_system_start: '等待系统启动', @@ -764,8 +764,8 @@ async function mountView(query: Record = {}) { actionCodes: { confirm_customer: '确认客户', resolve_field_conflicts: '处理字段冲突', - retry_inventory_preparation: '重新获取库存', - retry_inventory_matching: '重新匹配库存', + retry_onhand_preparation: '重新获取库存', + retry_onhand_matching: '重新匹配库存', }, }, }, @@ -1545,11 +1545,11 @@ describe('ShippingOrderReviewView layout phase 1', () => { }; shippingProcessingProjection.value = { workItemType: 'order_task', workItemNo: 'SN-RPA-RECOVERY-PENDING', - status: 'failed', userStatus: 'failed', stage: 'inventory_fetching', + status: 'failed', userStatus: 'failed', stage: 'onhand_fetching', progressVersion: 7, currentGate: { status: 'blocked_retryable' }, uiState: { - status: 'failed', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep', - primary_action: { code: 'retry_inventory_preparation', i18n_key: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' }, + status: 'failed', stage: 'onhand_fetching', lifecycleStage: 'fulfillment_prep', + primary_action: { code: 'retry_onhand_preparation', i18n_key: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' }, secondary_actions: [], }, } as any; @@ -1559,7 +1559,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { ui_state: { actions: { primary: { - code: 'retry_inventory_preparation', kind: 'current_gate', enabled: true, + code: 'retry_onhand_preparation', kind: 'current_gate', enabled: true, dispatch: 'mutation', requires_confirmation: false, }, secondary: [], @@ -1579,7 +1579,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(wrapper.get('[data-testid="review-current-task-status"]').text()).not.toContain('自动处理失败'); }); - it('submits retry_inventory_preparation from A even when B.actions lacks the code', async () => { + it('submits retry_onhand_preparation from A even when B.actions lacks the code', async () => { // 回归:右卡只读 A.primary_action 展示「重新获取库存(RPA)」;若仍按 B.actions // 授权,会落到「未识别的动作」。A 展示即写路径授权;capabilities 可作 bypass。 activeCase.value = { @@ -1589,11 +1589,11 @@ describe('ShippingOrderReviewView layout phase 1', () => { }; shippingProcessingProjection.value = { workItemType: 'order_task', workItemNo: 'SN-RPA-A-ONLY', - status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching', + status: 'failed', userStatus: 'retryable', stage: 'onhand_fetching', progressVersion: 3, currentGate: { status: 'blocked_retryable' }, uiState: { - status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep', - primary_action: { code: 'retry_inventory_preparation' }, + status: 'retryable', stage: 'onhand_fetching', lifecycleStage: 'fulfillment_prep', + primary_action: { code: 'retry_onhand_preparation' }, secondary_actions: [], }, } as any; @@ -1606,17 +1606,17 @@ describe('ShippingOrderReviewView layout phase 1', () => { process_gate: { execution_no: 'EXEC-RPA-A-ONLY', current_blocking_gate: { - gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable', + gate_code: 'onhand_preparation', evaluation_version: 2, status: 'blocked_retryable', }, - allowed_actions: ['retry_inventory_preparation'], - recovery_targets: [{ action_code: 'retry_inventory_preparation' }], + allowed_actions: ['retry_onhand_preparation'], + recovery_targets: [{ action_code: 'retry_onhand_preparation' }], }, stage_context: { preparation: { status: 'blocked', source_locked: false, source_options: [{ source_code: 'DSV' }], capabilities: [{ - code: 'retry_inventory_preparation', scope: 'task', - action_code: 'retry_inventory_preparation', enabled: true, + code: 'retry_onhand_preparation', scope: 'task', + action_code: 'retry_onhand_preparation', enabled: true, }], frozen_order_lines: [], lines: [], }, @@ -1638,7 +1638,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith( expect.any(Object), expect.objectContaining({ - actionCode: 'retry_inventory_preparation', + actionCode: 'retry_onhand_preparation', stageCapabilityBypass: true, }), ); @@ -1655,12 +1655,12 @@ describe('ShippingOrderReviewView layout phase 1', () => { }; shippingProcessingProjection.value = { workItemType: 'order_task', workItemNo: 'SN-RPA-CAP-DISABLED', - status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching', + status: 'failed', userStatus: 'retryable', stage: 'onhand_fetching', progressVersion: 5, currentGate: { status: 'blocked_retryable' }, uiState: { - status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep', - primary_action: { code: 'retry_inventory_matching' }, - secondary_actions: [{ code: 'retry_inventory_preparation', enabled: true }], + status: 'retryable', stage: 'onhand_fetching', lifecycleStage: 'fulfillment_prep', + primary_action: { code: 'retry_onhand_matching' }, + secondary_actions: [{ code: 'retry_onhand_preparation', enabled: true }], }, } as any; const taskApi = await import('@/features/chat/api/shipping.api'); @@ -1671,9 +1671,9 @@ describe('ShippingOrderReviewView layout phase 1', () => { process_gate: { execution_no: 'EXEC-RPA-CAP-DISABLED', current_blocking_gate: { - gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable', + gate_code: 'onhand_preparation', evaluation_version: 2, status: 'blocked_retryable', }, - allowed_actions: ['retry_inventory_matching', 'retry_inventory_preparation'], + allowed_actions: ['retry_onhand_matching', 'retry_onhand_preparation'], }, stage_context: { preparation: { @@ -1682,13 +1682,13 @@ describe('ShippingOrderReviewView layout phase 1', () => { failed_source_codes: ['DSV'], capabilities: [ { - code: 'retry_inventory_matching', scope: 'task', - action_code: 'retry_inventory_matching', enabled: false, + code: 'retry_onhand_matching', scope: 'task', + action_code: 'retry_onhand_matching', enabled: false, disabled_reason: 'no_match_result', }, { - code: 'retry_inventory_preparation', scope: 'task', - action_code: 'retry_inventory_preparation', enabled: true, + code: 'retry_onhand_preparation', scope: 'task', + action_code: 'retry_onhand_preparation', enabled: true, disabled_reason: null, }, ], @@ -1710,7 +1710,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(primary.attributes('data-capability-disabled')).toBe('true'); expect(primary.attributes('title')).toContain('暂无库存匹配结果'); // 侧路按钮:能力 enabled → 保持可点,不受主按钮禁用影响。 - const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]'); + const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_onhand_preparation"]'); expect(recovery.attributes('disabled')).toBeUndefined(); // 点击禁用按钮不得触发提交,也不得弹任何 info 提示(此前会弹未翻译 key)。 await primary.trigger('click'); @@ -1789,7 +1789,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { confirmed_task_no: 'SN-PROJECTION-PENDING', process_gate: { execution_no: 'EXEC-PROJECTION-PENDING', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false, - current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' }, + current_blocking_gate: { gate_code: 'onhand_preparation', status: 'blocked_retryable' }, primary_action: { code: 'retry', label_key: 'chat.shippingOrderReview.currentTask.actionRetry' }, }, automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true }, @@ -1875,7 +1875,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { confirmed_task_id: 91, confirmed_task_no: 'SN-SINGLE-SOURCE-1', // 故意下发与投影分叉的 Case 阶段:单源后必须被无视。 - current_stage: { code: 'inventory_matching', label_key: 'inventory_matching', inconsistent: false }, + current_stage: { code: 'onhand_matching', label_key: 'onhand_matching', inconsistent: false }, automation: { status: 'running', retryable: false, can_auto_create: false, can_build: true }, }; shippingProcessingProjection.value = null; @@ -2513,7 +2513,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { }; const wrapper = await mountView({ lifecycle_stage: 'order_review' }); shippingProcessingProjection.value = { - stage: 'inventory_preparation', status: 'processing', + stage: 'onhand_preparation', status: 'processing', uiState: { status: 'running', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [], primary_action: null, secondary_actions: [], @@ -2700,10 +2700,10 @@ describe('ShippingOrderReviewView layout phase 1', () => { // 而不是默认回退到订单复核。 shippingProcessingProjection.value = { status: 'processing', - stage: 'inventory_matching', + stage: 'onhand_matching', uiState: { status: 'processing', - stage: 'inventory_matching', + stage: 'onhand_matching', lifecycleStage: 'fulfillment_prep', lifecycleEntries: [ { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, @@ -2804,10 +2804,10 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft_line_id: 'line-frozen', snapshot_line_id: 1001, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, - inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'], - line_allowed_actions: ['release_inventory_shortage'], + inventory_allowed_actions: ['retry_onhand_preparation', 'retry_onhand_matching'], + line_allowed_actions: ['release_onhand_shortage'], release_template_fields: [ - { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false }, { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, ], release_required_fields: [{ field_id: '102', display_name: '库位' }], @@ -2827,10 +2827,10 @@ describe('ShippingOrderReviewView layout phase 1', () => { ui_state: { process_gate: { execution_no: 'EXEC-FROZEN-LINE', - current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' }, + current_blocking_gate: { gate_code: 'onhand_preparation', status: 'blocked_retryable' }, }, actions: { - primary: { code: 'retry_inventory_preparation', enabled: true, dispatch: 'mutation' }, + primary: { code: 'retry_onhand_preparation', enabled: true, dispatch: 'mutation' }, secondary: [], }, lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }], @@ -2847,10 +2847,10 @@ describe('ShippingOrderReviewView layout phase 1', () => { required_qty: '6', available_qty: null, part_available_qty: '9', shortage_qty: null, source_code: 'DBS', inventory_file_no: 'SIF-LINE-DBS', status: 'shortage', draft_line_id: 'line-frozen', - inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'], - line_allowed_actions: ['release_inventory_shortage'], + inventory_allowed_actions: ['retry_onhand_preparation', 'retry_onhand_matching'], + line_allowed_actions: ['release_onhand_shortage'], release_template_fields: [ - { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false }, { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, ], release_required_fields: [{ field_id: '102', display_name: '库位' }], @@ -2886,26 +2886,26 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false); // 展示态行级动作收纳进更多菜单(⋯):逐项断言授权动作入口存在,不再有常显按钮。 await openLineOverflowMenu(wrapper, 1001); - expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-download_inventory_file-1001"]')).toBeTruthy(); - expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_inventory_preparation-1001"]')).toBeTruthy(); - expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_inventory_matching-1001"]')).toBeTruthy(); - expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-release_inventory_shortage-1001"]')).toBeTruthy(); + expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-download_onhand_file-1001"]')).toBeTruthy(); + expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_onhand_preparation-1001"]')).toBeTruthy(); + expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-retry_onhand_matching-1001"]')).toBeTruthy(); + expect(document.body.querySelector('[data-testid="review-fulfillment-line-action-release_onhand_shortage-1001"]')).toBeTruthy(); expect(workspace.text()).toContain('库存不足'); - await clickLineMenuItem(1001, 'download_inventory_file'); + await clickLineMenuItem(1001, 'download_onhand_file'); expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS'); await openLineOverflowMenu(wrapper, 1001); - await clickLineMenuItem(1001, 'retry_inventory_preparation'); + await clickLineMenuItem(1001, 'retry_onhand_preparation'); expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith( expect.any(Object), expect.objectContaining({ - actionCode: 'retry_inventory_preparation', + actionCode: 'retry_onhand_preparation', payload: { snapshot_line_id: 1001 }, }), ); // Gate 恢复受理后立即启动五阶段轮询,不依赖浏览器手动刷新。 expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(1); await openLineOverflowMenu(wrapper, 1001); - await clickLineMenuItem(1001, 'release_inventory_shortage'); + await clickLineMenuItem(1001, 'release_onhand_shortage'); expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID'); expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001'); const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]'); @@ -2933,9 +2933,9 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft_line_id: 'line-frozen', snapshot_line_id: 1001, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, - line_allowed_actions: ['release_inventory_shortage'], + line_allowed_actions: ['release_onhand_shortage'], release_template_fields: [ - { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false }, { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, ], release_required_fields: [{ field_id: '102', display_name: '库位' }], @@ -2964,7 +2964,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { stage_context: releaseAccepted ? { upload: {} } : { preparation: { frozen_order_lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6' }], - lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-frozen', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], + lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-frozen', line_allowed_actions: ['release_onhand_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], }, }, }, @@ -2974,7 +2974,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { await flushPromises(); // 缺字段短缺行:放行入口在更多菜单,必填补录在行内补录条完成(原因不再强制)。 await openLineOverflowMenu(wrapper, 1001); - await clickLineMenuItem(1001, 'release_inventory_shortage'); + await clickLineMenuItem(1001, 'release_onhand_shortage'); await wrapper.get('[data-testid="review-fulfillment-release-input-1001-102"]').setValue('A-01'); await wrapper.get('[data-testid="review-fulfillment-release-confirm-1001"]').trigger('click'); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -2997,9 +2997,9 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft_line_id: 'line-async', snapshot_line_id: 1002, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, - line_allowed_actions: ['release_inventory_shortage'], + line_allowed_actions: ['release_onhand_shortage'], release_template_fields: [ - { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false }, { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, ], release_required_fields: [{ field_id: '102', display_name: '库位' }], @@ -3024,7 +3024,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { stage_context: advanceDone ? { upload: {} } : { preparation: { frozen_order_lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6' }], - lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-async', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], + lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-async', line_allowed_actions: ['release_onhand_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], }, }, }, @@ -3033,7 +3033,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); await flushPromises(); await openLineOverflowMenu(wrapper, 1002); - await clickLineMenuItem(1002, 'release_inventory_shortage'); + await clickLineMenuItem(1002, 'release_onhand_shortage'); await wrapper.get('[data-testid="review-fulfillment-release-input-1002-102"]').setValue('A-01'); await wrapper.get('[data-testid="review-fulfillment-release-confirm-1002"]').trigger('click'); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -3071,9 +3071,9 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft_line_id: 'line-manual', snapshot_line_id: 1003, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, - line_allowed_actions: ['release_inventory_shortage'], + line_allowed_actions: ['release_onhand_shortage'], release_template_fields: [ - { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'onhand_snapshot', requires_manual: false }, { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, ], release_required_fields: [{ field_id: '102', display_name: '库位' }], @@ -3092,7 +3092,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { stage_context: releaseAccepted ? { upload: {} } : { preparation: { frozen_order_lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6' }], - lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-manual', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], + lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-manual', line_allowed_actions: ['release_onhand_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], }, }, }, @@ -3108,7 +3108,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); await openLineOverflowMenu(wrapper, 1003); - await clickLineMenuItem(1003, 'release_inventory_shortage'); + await clickLineMenuItem(1003, 'release_onhand_shortage'); await wrapper.get('[data-testid="review-fulfillment-release-input-1003-102"]').setValue('A-01'); await wrapper.get('[data-testid="review-fulfillment-release-confirm-1003"]').trigger('click'); await wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].trigger('click'); @@ -3354,7 +3354,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }], process_gate: { gate_status: 'blocked_retryable', blocking_reason_code: 'inventory_file_missing', - primary_action: { code: 'retry_inventory_preparation', label_key: 'retry_inventory_preparation' }, + primary_action: { code: 'retry_onhand_preparation', label_key: 'retry_onhand_preparation' }, }, }, } as any); @@ -3710,7 +3710,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { primary: { code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true, dispatch: 'mutation', - target_surface: 'fulfillment_prep', target_anchor: 'inventory_matching', + target_surface: 'fulfillment_prep', target_anchor: 'onhand_matching', requires_confirmation: false, }, secondary: [], @@ -4340,7 +4340,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { shippingNoticeNo: 'SN-OT-WAITING-INVENTORY', retryable: true, userStatus: 'retryable', - primaryAction: { code: 'retry_inventory_preparation' }, + primaryAction: { code: 'retry_onhand_preparation' }, currentGate: { status: 'blocked_retryable' }, inventoryPreparation: { activeAttemptCount: 1, @@ -4349,7 +4349,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { }, uiState: { status: 'retryable', - primary_action: { code: 'retry_inventory_preparation' }, + primary_action: { code: 'retry_onhand_preparation' }, secondary_actions: [], }, }; @@ -4358,7 +4358,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { ui_state: { actions: { primary: { - code: 'retry_inventory_preparation', kind: 'recovery', enabled: true, + code: 'retry_onhand_preparation', kind: 'recovery', enabled: true, dispatch: 'mutation', requires_confirmation: false, }, secondary: [], @@ -4366,7 +4366,7 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { process_gate: { execution_no: 'EXEC-INVENTORY-WAITING', current_blocking_gate: { - gate_code: 'inventory_preparation', evaluation_version: 1, + gate_code: 'onhand_preparation', evaluation_version: 1, }, }, summary: {}, steps: [], @@ -4418,8 +4418,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { confirmed_task_no: 'SN-WAIT-1', // 故意与 Progress 文案分叉:若宽屏仍直读 Case code,会显示「库存匹配」。 current_stage: { - code: 'inventory_matching', - label_key: 'inventory_matching', + code: 'onhand_matching', + label_key: 'onhand_matching', inconsistent: false, }, automation: { diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index b768e763..91749023 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -850,7 +850,7 @@ const formalTaskActions = computed(() => { /** 行级库存选源动作:只在表格逐行处理,禁止作为任务级按钮出现在右侧"当前任务"卡(避免与表格打勾重复)。 */ const LINE_SCOPE_INVENTORY_ACTIONS = new Set([ - 'override_line_inventory_source', + 'override_line_onhand_source', ]); /** @@ -1888,7 +1888,7 @@ async function executeFormalTaskAction( await nextTick(); scrollWorkbenchAnchor('review-fulfillment-prep-workspace'); }, - inventory_upload: () => scrollWorkbenchAnchor('review-formal-task-todo-panel'), + onhand_upload: () => scrollWorkbenchAnchor('review-formal-task-todo-panel'), order_fields: () => scrollWorkbenchAnchor('review-order-lines-table'), reservation: () => scrollWorkbenchAnchor('review-order-lines-table'), duplicate_review: () => scrollWorkbenchAnchor('review-duplicate-panel'), @@ -2009,7 +2009,7 @@ async function handleCurrentTaskAction( await nextTick(); scrollWorkbenchAnchor('review-formal-task-result-region'); break; - case 'open_inventory_match_review': + case 'open_onhand_match_review': if (hasFormalOt.value) { // 正式 OT 后匹配/缺口语境的真实宿主是通知准备工作区;订单明细表不承载库存结果。 scrollWorkbenchAnchor('review-fulfillment-prep-workspace'); @@ -2043,7 +2043,7 @@ async function handleCurrentTaskAction( } break; } - case 'retry_inventory_matching': { + case 'retry_onhand_matching': { const summary = displayCase.value?.process_gate; if (!summary) return; const result = await submitProcessGatePrimaryAction(summary, { actionCode: code }); @@ -2740,13 +2740,13 @@ async function submitLineOdmChoice(line: { snapshot_line_id?: number | null }) { function formalPreparationLineAllows( line: { snapshot_line_id?: number | null }, - action: 'retry_inventory_preparation' | 'retry_inventory_matching' | 'close_unfulfillable' | 'release_inventory_shortage', + action: 'retry_onhand_preparation' | 'retry_onhand_matching' | 'close_unfulfillable' | 'release_onhand_shortage', ): boolean { const fulfillment = formalPreparationLineFulfillment(line); - if (action === 'close_unfulfillable' || action === 'release_inventory_shortage') { + if (action === 'close_unfulfillable' || action === 'release_onhand_shortage') { return Boolean( fulfillment?.line_allowed_actions?.includes(action) - && (action !== 'release_inventory_shortage' || !fulfillment?.release_field_resolution_error), + && (action !== 'release_onhand_shortage' || !fulfillment?.release_field_resolution_error), ); } return Boolean(fulfillment?.inventory_allowed_actions?.includes(action)); @@ -2758,7 +2758,7 @@ function formalPreparationLineAllows( */ function formalPreparationLineStatusLabel(line: { snapshot_line_id?: number | null; status?: string | null; shortage_qty?: string | number | null }): string { const fulfillment = formalPreparationLineFulfillment(line); - if (fulfillment?.decision?.decision_code === 'release_inventory_shortage') { + if (fulfillment?.decision?.decision_code === 'release_onhand_shortage') { return t('chat.shippingOrderReview.lifecycle.prepare.releaseShortage'); } const status = String(line.status || '').trim().toLowerCase(); @@ -2807,7 +2807,7 @@ async function confirmReleaseInventoryShortage() { try { await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, { draft_line_id: String(line.draft_line_id || ''), - decision_code: 'release_inventory_shortage', + decision_code: 'release_onhand_shortage', reason, release_field_values: releaseInventoryFieldValues.value, expected_draft_version: activeCase.value?.draft?.draft_version, @@ -2896,7 +2896,7 @@ function releaseBarReadyFor(line: { snapshot_line_id?: number | null }): boolean const fulfillment = formalPreparationLineFulfillment(line); const required = releaseBarLineRequiredFields(line); return Boolean( - fulfillment?.line_allowed_actions?.includes('release_inventory_shortage') + fulfillment?.line_allowed_actions?.includes('release_onhand_shortage') && required.every((field) => releaseBarValue(line, field).trim()) && !releaseBarBusy.value[releaseBarKey(line)], ); @@ -2917,7 +2917,7 @@ async function confirmReleaseBar(line: { snapshot_line_id?: number | null }) { try { await decideWorkspaceShippingOrderReviewLineFulfillment(caseNo, { draft_line_id: String(fulfillment.draft_line_id || ''), - decision_code: 'release_inventory_shortage', + decision_code: 'release_onhand_shortage', reason: '', release_field_values: { ...(releaseBarValues.value[key] || {}) }, expected_draft_version: activeCase.value?.draft?.draft_version, @@ -3011,7 +3011,7 @@ async function downloadFormalPreparationLineInventoryFile(line: { /** 行级恢复提交当前 Gate 的精确动作,使用冻结快照行身份。 */ async function retryFormalPreparationLine( snapshotLineId: number | string, - actionCode: 'retry_inventory_preparation' | 'retry_inventory_matching', + actionCode: 'retry_onhand_preparation' | 'retry_onhand_matching', ) { if (!snapshotLineId) return; await submitFormalGateAction(actionCode, { snapshot_line_id: Number(snapshotLineId) }); @@ -3132,20 +3132,20 @@ function overflowItems(line: { shortage_qty?: string | number | null; }): Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise }> { const items: Array<{ key: string; icon: Component; labelKey: string; run: () => void | Promise }> = []; - if (formalPreparationLineAllows(line, 'retry_inventory_matching')) { + if (formalPreparationLineAllows(line, 'retry_onhand_matching')) { items.push({ - key: 'retry_inventory_matching', + key: 'retry_onhand_matching', icon: RefreshCw, - labelKey: inventoryActionLabelKey('retry_inventory_matching')!, - run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_matching'), + labelKey: inventoryActionLabelKey('retry_onhand_matching')!, + run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_onhand_matching'), }); } // 放行缺口:缺字段型短缺行 → 行内展开补录条(替代弹窗);仅缺原因的行 → 旧弹窗(原因已可选)。 - if (formalPreparationLineAllows(line, 'release_inventory_shortage')) { + if (formalPreparationLineAllows(line, 'release_onhand_shortage')) { items.push({ - key: 'release_inventory_shortage', + key: 'release_onhand_shortage', icon: Check, - labelKey: inventoryActionLabelKey('release_inventory_shortage')!, + labelKey: inventoryActionLabelKey('release_onhand_shortage')!, run: () => { if (releaseBarHasFields(line)) expandReleaseBar(line); else openReleaseInventoryShortage(line); @@ -3160,19 +3160,19 @@ function overflowItems(line: { run: () => openCloseLineDialog(line), }); } - if (formalPreparationLineAllows(line, 'retry_inventory_preparation')) { + if (formalPreparationLineAllows(line, 'retry_onhand_preparation')) { items.push({ - key: 'retry_inventory_preparation', + key: 'retry_onhand_preparation', icon: Bot, - labelKey: inventoryActionLabelKey('retry_inventory_preparation')!, - run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_inventory_preparation'), + labelKey: inventoryActionLabelKey('retry_onhand_preparation')!, + run: () => retryFormalPreparationLine(Number(line.snapshot_line_id), 'retry_onhand_preparation'), }); } if (formalPreparationLineInventoryFileNo(line)) { items.push({ - key: 'download_inventory_file', + key: 'download_onhand_file', icon: Download, - labelKey: inventoryActionLabelKey('download_inventory_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory', + labelKey: inventoryActionLabelKey('download_onhand_file') || 'chat.shippingOrderReview.lifecycle.prepare.downloadInventory', run: () => downloadFormalPreparationLineInventoryFile(line), }); } @@ -3246,7 +3246,7 @@ async function saveInlineEdit(line: { } // 库存源覆写沿用既有 Gate 动作(override_line_inventory_source),后端校验后仅重匹配该行。 if (sourceChanged) { - await submitFormalGateAction('override_line_inventory_source', { + await submitFormalGateAction('override_line_onhand_source', { line_no: draft.line_no, source_code: nextSourceCode, }); @@ -3778,7 +3778,7 @@ const preparationWaveSelectableLines = computed(() => formalPreparationLines.val if (!fulfillment) return false; if (['task_created', 'fulfilled', 'closed_unfulfillable'].includes(String(fulfillment.line_status || ''))) return false; return Boolean(fulfillment.can_fulfill_complete_line) - || fulfillment.decision?.decision_code === 'release_inventory_shortage'; + || fulfillment.decision?.decision_code === 'release_onhand_shortage'; })); const allPreparationWaveSelected = computed(() => ( preparationWaveSelectableLines.value.length > 0 diff --git a/frontend/src/features/shipping-notice/shippingI18nParity.spec.ts b/frontend/src/features/shipping-notice/shippingI18nParity.spec.ts index 0444455d..bfad68bd 100644 --- a/frontend/src/features/shipping-notice/shippingI18nParity.spec.ts +++ b/frontend/src/features/shipping-notice/shippingI18nParity.spec.ts @@ -1,8 +1,8 @@ /** * features/shipping-notice/shippingI18nParity.spec.ts * 用途:验证货代发货通知业务域在四种语言中的文案键保持一致。 - * 依赖:admin/chat/workspace 四语言 JSON;只检查货代业务子树,不受其他历史业务域影响。 - * 逻辑:递归收集叶子键并比较集合;覆盖 Schema/库存/聊天通知/会话摘要/工作台待办。 + * 依赖:admin/chat/workspace/errors 四语言 JSON;errors 比较全文件叶子键,其余只检查货代业务子树。 + * 逻辑:递归收集叶子键并比较集合;覆盖 Schema/库存/聊天通知/会话摘要/工作台待办/errors.json。 */ import { describe, expect, it } from 'vitest'; @@ -15,6 +15,10 @@ import chatEn from '@/locales/en/chat.json'; import chatTh from '@/locales/th/chat.json'; import chatZhCn from '@/locales/zh-CN/chat.json'; import chatZhTw from '@/locales/zh-TW/chat.json'; +import errorsEn from '@/locales/en/errors.json'; +import errorsTh from '@/locales/th/errors.json'; +import errorsZhCn from '@/locales/zh-CN/errors.json'; +import errorsZhTw from '@/locales/zh-TW/errors.json'; import workspaceEn from '@/locales/en/workspace.json'; import workspaceTh from '@/locales/th/workspace.json'; import workspaceZhCn from '@/locales/zh-CN/workspace.json'; @@ -46,10 +50,10 @@ describe('shipping notice i18n parity', () => { it('keeps admin inventory configuration keys aligned', () => { expectSameKeys([ - adminZhCn.shippingInventory as LocaleTree, - adminZhTw.shippingInventory as LocaleTree, - adminEn.shippingInventory as LocaleTree, - adminTh.shippingInventory as LocaleTree, + adminZhCn.freightRpa as LocaleTree, + adminZhTw.freightRpa as LocaleTree, + adminEn.freightRpa as LocaleTree, + adminTh.freightRpa as LocaleTree, ]); }); @@ -71,6 +75,15 @@ describe('shipping notice i18n parity', () => { ]); }); + it('keeps errors.json keys aligned', () => { + expectSameKeys([ + errorsZhCn as LocaleTree, + errorsZhTw as LocaleTree, + errorsEn as LocaleTree, + errorsTh as LocaleTree, + ]); + }); + it('keeps workspace shipping notice keys aligned', () => { expectSameKeys([ workspaceZhCn.shippingNotice as LocaleTree, diff --git a/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts b/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts index d5e90c2b..0109ec6c 100644 --- a/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts +++ b/frontend/src/features/shipping-process-gates/components/ProcessGateRecoveryCard.spec.ts @@ -92,7 +92,7 @@ describe('ProcessGateRecoveryCard', () => { technical_auto_only: true, owner_type: 'system', responsible_party: 'worker', - next_action_code: 'retry_inventory_preparation', + next_action_code: 'retry_onhand_preparation', }), canHandle: false, }, @@ -148,15 +148,15 @@ describe('ProcessGateRecoveryCard', () => { summary: baseSummary({ current_blocking_gate: { ...baseSummary().current_blocking_gate!, - gate_code: 'inventory_matching', - next_action_code: 'open_inventory_match_review', + gate_code: 'onhand_matching', + next_action_code: 'open_onhand_match_review', }, - next_action_code: 'open_inventory_match_review', + next_action_code: 'open_onhand_match_review', recovery_targets: [{ - action_code: 'retry_inventory_from_preparation', - target_gate: 'inventory_preparation', - resume_after_gate: 'inventory_matching', - invalidates: ['inventory_snapshot'], + action_code: 'retry_onhand_from_preparation', + target_gate: 'onhand_preparation', + resume_after_gate: 'onhand_matching', + invalidates: ['onhand_snapshot'], }], }), canHandle: true, @@ -185,11 +185,11 @@ describe('ProcessGateRecoveryCard', () => { summary: baseSummary({ current_blocking_gate: { ...baseSummary().current_blocking_gate!, - gate_code: 'inventory_preparation', - next_action_code: 'retry_inventory_preparation', + gate_code: 'onhand_preparation', + next_action_code: 'retry_onhand_preparation', }, - next_action_code: 'retry_inventory_preparation', - allowed_actions: ['retry_inventory_preparation'], + next_action_code: 'retry_onhand_preparation', + allowed_actions: ['retry_onhand_preparation'], task_no: 'SN-TEST-001', navigation: { target: 'task_workspace', task_no: 'SN-TEST-001' }, }), @@ -209,10 +209,10 @@ describe('ProcessGateRecoveryCard', () => { summary: baseSummary({ current_blocking_gate: { ...baseSummary().current_blocking_gate!, - gate_code: 'inventory_matching', - next_action_code: 'retry_inventory_from_preparation', + gate_code: 'onhand_matching', + next_action_code: 'retry_onhand_from_preparation', }, - next_action_code: 'retry_inventory_from_preparation', + next_action_code: 'retry_onhand_from_preparation', }), canHandle: true, }, diff --git a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts index 34baf759..08e271f7 100644 --- a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts +++ b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts @@ -42,15 +42,15 @@ function summary() { execution_no: 'EXEC-1', status: 'blocked', current_blocking_gate: { - gate_code: 'inventory_matching', + gate_code: 'onhand_matching', evaluation_version: 3, status: 'blocked', }, primary_action: { - code: 'retry_inventory_matching', + code: 'retry_onhand_matching', dispatch: 'mutation', }, - allowed_actions: ['retry_inventory_matching'], + allowed_actions: ['retry_onhand_matching'], } as never; } @@ -60,7 +60,7 @@ function capabilitySummary() { execution_no: 'EXEC-1', status: 'blocked', current_blocking_gate: { - gate_code: 'inventory_field_mapping', + gate_code: 'onhand_field_mapping', evaluation_version: 5, status: 'blocked', }, @@ -92,7 +92,7 @@ describe('useShippingProcessGateRecovery', () => { postActionMock.mockResolvedValue({ dispatch: 'async_job', execution_no: 'EXEC-1', - gate_code: 'inventory_matching', + gate_code: 'onhand_matching', attempt: { id: 9, status: 'queued' }, }); }); @@ -101,7 +101,7 @@ describe('useShippingProcessGateRecovery', () => { const { exposed, app } = mountComposable(); const result = await exposed.submitPrimaryAction(summary(), { - actionCode: 'retry_inventory_matching', + actionCode: 'retry_onhand_matching', }); expect(result.outcome).toBe('submitted'); @@ -117,7 +117,7 @@ describe('useShippingProcessGateRecovery', () => { const { exposed, app } = mountComposable(); const result = await exposed.submitPrimaryAction(capabilitySummary(), { - actionCode: 'override_line_inventory_source', + actionCode: 'override_line_onhand_source', stageCapabilityBypass: true, }); @@ -126,8 +126,8 @@ describe('useShippingProcessGateRecovery', () => { expect(getExecutionMock).not.toHaveBeenCalled(); expect(postActionMock).toHaveBeenCalledWith( 'EXEC-1', - 'inventory_field_mapping', - expect.objectContaining({ action_code: 'override_line_inventory_source' }), + 'onhand_field_mapping', + expect.objectContaining({ action_code: 'override_line_onhand_source' }), ); app.unmount(); @@ -138,18 +138,18 @@ describe('useShippingProcessGateRecovery', () => { const result = await exposed.submitPrimaryAction({ execution_no: 'EXEC-1', status: 'processing', - current_gate: { gate_code: 'inventory_preparation', evaluation_version: 7, status: 'running' }, + current_gate: { gate_code: 'onhand_preparation', evaluation_version: 7, status: 'running' }, allowed_actions: [], recovery_targets: [], } as never, { - actionCode: 'retry_inventory_preparation', + actionCode: 'retry_onhand_preparation', stageCapabilityBypass: true, }); expect(result.outcome).toBe('submitted'); expect(postActionMock).toHaveBeenCalledWith( 'EXEC-1', - 'inventory_preparation', - expect.objectContaining({ action_code: 'retry_inventory_preparation' }), + 'onhand_preparation', + expect.objectContaining({ action_code: 'retry_onhand_preparation' }), ); app.unmount(); }); diff --git a/frontend/src/features/shipping-process-gates/types/process-gate.types.ts b/frontend/src/features/shipping-process-gates/types/process-gate.types.ts index 03c2e7ff..f8f323fe 100644 --- a/frontend/src/features/shipping-process-gates/types/process-gate.types.ts +++ b/frontend/src/features/shipping-process-gates/types/process-gate.types.ts @@ -8,8 +8,8 @@ */ import type { ShippingExplainabilityReason, - ShippingInventorySourceLineBlockReasonCode, - ShippingInventorySourceUnavailableReasonCode, + ShippingOnhandSourceLineBlockReasonCode, + ShippingOnhandSourceUnavailableReasonCode, ShippingProcessGateActionCode, ShippingProcessGateActionPresentation, ShippingProcessGateCode, @@ -21,8 +21,8 @@ import type { export type { ShippingExplainabilityReason, - ShippingInventorySourceLineBlockReasonCode, - ShippingInventorySourceUnavailableReasonCode, + ShippingOnhandSourceLineBlockReasonCode, + ShippingOnhandSourceUnavailableReasonCode, ShippingProcessGateActionCode, ShippingProcessGateActionPresentation, ShippingProcessGateCode, diff --git a/frontend/src/features/shipping-progress/actionPresentation.spec.ts b/frontend/src/features/shipping-progress/actionPresentation.spec.ts index 3f0c5fa9..710b7af7 100644 --- a/frontend/src/features/shipping-progress/actionPresentation.spec.ts +++ b/frontend/src/features/shipping-progress/actionPresentation.spec.ts @@ -24,7 +24,7 @@ function projection( submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'blocked', - stage: 'inventory_source_resolving', + stage: 'onhand_source_resolving', progressVersion: 1, lastActivityAt: '2026-08-05T00:00:00Z', currentGate: null, @@ -103,7 +103,7 @@ describe('resolveProcessingActionPresentation', () => { it('does not turn diagnostic gate nextActionCode into a user action', () => { const result = resolveProcessingActionPresentation(projection({ currentGate: { - gateCode: 'inventory_source_routing', + gateCode: 'onhand_source_routing', status: 'blocked', nextActionCode: 'open_inventory_source_review', blockingReasonCode: 'no_inventory_source_candidates', @@ -118,21 +118,21 @@ describe('resolveProcessingActionPresentation', () => { const result = resolveProcessingActionPresentation(projection({ status: 'processing', currentGate: { - gateCode: 'inventory_source_routing', status: 'blocked', nextActionCode: 'retry', + gateCode: 'onhand_source_routing', status: 'blocked', nextActionCode: 'retry', blockingReasonCode: null, attemptNo: 1, }, primaryAction: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} }, availableActions: ['retry_parse', 'view_result'], uiState: { status: 'waiting_human', stage: 'fulfillment_prep', blocking_reason: null, - primary_action: { code: 'retry_inventory_preparation', i18nKey: 'action.retry_inventory_preparation', parameters: {} }, + primary_action: { code: 'retry_onhand_preparation', i18nKey: 'action.retry_onhand_preparation', parameters: {} }, secondary_actions: [ { code: 'view_details', enabled: true }, { code: 'retry_parse', enabled: false }, ], }, })); - expect(result.primary?.actionCode).toBe('retry_inventory_preparation'); + expect(result.primary?.actionCode).toBe('retry_onhand_preparation'); expect(result.secondary?.actionCode).toBe('view_details'); expect(result.overflow).toEqual([]); }); @@ -230,10 +230,10 @@ describe('resolveProcessingActionPresentation', () => { const result = resolveProcessingActionPresentation(projection({ status: 'waiting_human', uiState: { - status: 'waiting_human', stage: 'inventory_fetching', blocking_reason: null, + status: 'waiting_human', stage: 'onhand_fetching', blocking_reason: null, primary_action: { - code: 'retry_inventory_preparation', - i18nKey: 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation', + code: 'retry_onhand_preparation', + i18nKey: 'workspace.shippingNotice.processGate.actionCodes.retry_onhand_preparation', parameters: {}, }, // Gate 工作台可保留受控上传入口;批次卡只消费 primary_action。 @@ -242,7 +242,7 @@ describe('resolveProcessingActionPresentation', () => { }), { surface: 'right' }); expect(result.primary).toMatchObject({ - actionCode: 'retry_inventory_preparation', + actionCode: 'retry_onhand_preparation', labelKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', }); expect(result.secondary).toBeNull(); @@ -251,14 +251,14 @@ describe('resolveProcessingActionPresentation', () => { it('uses the shared inventory presentation for a rematch action', () => { const result = resolveProcessingActionPresentation(projection({ uiState: { - status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null, - primary_action: { code: 'retry_inventory_matching', i18nKey: null, parameters: {} }, + status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null, + primary_action: { code: 'retry_onhand_matching', i18nKey: null, parameters: {} }, secondary_actions: [], }, }), { surface: 'right' }); expect(result.primary).toMatchObject({ - actionCode: 'retry_inventory_matching', + actionCode: 'retry_onhand_matching', labelKey: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', }); }); @@ -332,7 +332,7 @@ describe('resolveProcessingActionPresentation', () => { it('preserves a backend-directed fulfillment preparation target for review navigation', () => { const result = resolveProcessingActionPresentation(projection({ uiState: { - status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null, + status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null, primary_action: { code: 'view_result', targetLifecycleStage: 'fulfillment_prep', @@ -351,7 +351,7 @@ describe('resolveProcessingActionPresentation', () => { it('preserves a backend-directed fulfillment target on a secondary action', () => { const result = resolveProcessingActionPresentation(projection({ uiState: { - status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null, + status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null, primary_action: null, secondary_actions: [{ code: 'view_result', enabled: true, @@ -373,7 +373,7 @@ describe('resolveProcessingActionPresentation', () => { const result = resolveConversationTaskActionPresentation({ task_no: 'SN-1', group: 'needs_action', status_label: 'waiting_human', uiState: { - status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null, + status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null, primary_action: null, secondary_actions: [{ code: 'view_result', enabled: true, diff --git a/frontend/src/features/shipping-progress/actionPresentation.ts b/frontend/src/features/shipping-progress/actionPresentation.ts index c9a64cd7..0df2314f 100644 --- a/frontend/src/features/shipping-progress/actionPresentation.ts +++ b/frontend/src/features/shipping-progress/actionPresentation.ts @@ -32,11 +32,11 @@ const ACTION_CODE_TO_INTENT: Record = { confirm_customer: 'confirm_customer', resolve_field_conflicts: 'resolve_field_conflicts', adjudicate_duplicate: 'adjudicate_duplicate', - open_inventory_match_review: 'open_inventory_match_review', + open_onhand_match_review: 'open_onhand_match_review', open_shortage_review: 'open_shortage_review', - reload_inventory_result: 'reload_inventory_result', - retry_inventory_preparation: 'retry_inventory_preparation', - retry_inventory_matching: 'retry_inventory_matching', + reload_onhand_result: 'reload_onhand_result', + retry_onhand_preparation: 'retry_onhand_preparation', + retry_onhand_matching: 'retry_onhand_matching', reparse_batch: 'reparse_batch', retry_parse: 'retry_parse', retry_failed_documents: 'retry_failed_documents', @@ -52,10 +52,10 @@ const ACTION_CODE_TO_INTENT: Record = { retry_with_latest_rules: 'retry_with_latest_rules', recheck_freeze_readiness: 'recheck_freeze_readiness', retry_task_creation: 'retry_task_creation', - retry_inventory_field_mapping: 'retry_inventory_field_mapping', - recheck_inventory_sufficiency: 'recheck_inventory_sufficiency', + retry_onhand_field_mapping: 'retry_onhand_field_mapping', + recheck_onhand_sufficiency: 'recheck_onhand_sufficiency', recheck_excel_readiness: 'recheck_excel_readiness', - poll_inventory_preparation: 'refresh', + poll_onhand_preparation: 'refresh', poll_freight_upload_rpa: 'refresh', edit_order_fields: 'open_order_review', edit_reservation: 'open_order_review', @@ -86,13 +86,13 @@ const ACTION_CODE_TO_INTENT: Record = { const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']); /** 需要在聊天/右侧展示精确恢复动作文案的正式 action_code。 */ const RECOVERY_ACTION_CODES = new Set([ - 'reload_inventory_result', - 'retry_inventory_preparation', 'retry_inventory_matching', 'retry_parse', + 'reload_onhand_result', + 'retry_onhand_preparation', 'retry_onhand_matching', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', 'retry_freight_upload_rpa', 'retry_order_extraction', 'retry_layout_parsing', 'rematerialize_document', 'reroute_document_profile', 'revalidate_reservation', 'retry_customer_resolution', 'retry_duplicate_detection', 'retry_with_latest_rules', 'recheck_freeze_readiness', - 'retry_task_creation', 'retry_inventory_field_mapping', 'recheck_inventory_sufficiency', + 'retry_task_creation', 'retry_onhand_field_mapping', 'recheck_onhand_sufficiency', 'recheck_excel_readiness', 'retry_stp_auto_create', 'reparse', ]); /** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */ @@ -113,13 +113,13 @@ const FILE_ROW_NAVIGATION_CODES = new Set([ * 或 retry_inventory_matching 等稳定动作码。 */ const INTERNAL_INVENTORY_ACTION_CODES = new Set([ - 'retry_inventory_from_preparation', - 'retry_inventory_from_matching', - 'retry_inventory_field_mapping', - 'retry_inventory_from_field_mapping', - 'poll_inventory_preparation', - 'refresh_inventory_candidate_projection', - 'recheck_inventory_sufficiency', + 'retry_onhand_from_preparation', + 'retry_onhand_from_matching', + 'retry_onhand_field_mapping', + 'retry_onhand_from_field_mapping', + 'poll_onhand_preparation', + 'refresh_onhand_candidate_projection', + 'recheck_onhand_sufficiency', ]); /** @@ -131,13 +131,13 @@ const INTERNAL_INVENTORY_ACTION_CODES = new Set([ export function inventoryActionLabelKey(code: string | null | undefined): string | null { const normalized = String(code || '').trim().toLowerCase(); const keyByCode: Record = { - reload_inventory_result: 'workspace.shippingNotice.processGate.inventoryActions.reloadInventoryResult', - retry_inventory_preparation: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', - retry_inventory_matching: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', - open_inventory_match_review: 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', + reload_onhand_result: 'workspace.shippingNotice.processGate.inventoryActions.reloadInventoryResult', + retry_onhand_preparation: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', + retry_onhand_matching: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', + open_onhand_match_review: 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', open_shortage_review: 'workspace.shippingNotice.processGate.inventoryActions.openShortageReview', - download_inventory_file: 'workspace.shippingNotice.processGate.inventoryActions.downloadInventoryFile', - release_inventory_shortage: 'workspace.shippingNotice.processGate.inventoryActions.releaseInventoryShortage', + download_onhand_file: 'workspace.shippingNotice.processGate.inventoryActions.downloadInventoryFile', + release_onhand_shortage: 'workspace.shippingNotice.processGate.inventoryActions.releaseInventoryShortage', }; return keyByCode[normalized] || null; } diff --git a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts index 45ca2c90..eaee762a 100644 --- a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts +++ b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.spec.ts @@ -135,18 +135,18 @@ describe('ReviewProgressStrip', () => { const wrapper = mountStrip(buildProjection({ status: 'automating', userStatus: 'waiting_human', - stage: 'inventory_fetching', + stage: 'onhand_fetching', currentGate: { - gateCode: 'inventory_preparation', + gateCode: 'onhand_preparation', status: 'blocked_manual', - nextActionCode: 'upload_inventory_file', + nextActionCode: 'upload_onhand_file', blockingReasonCode: 'inventory_file_empty', attemptNo: 3, }, }), true); const title = wrapper.get('[data-testid="review-progress-title"]').text(); expect(title).toContain('待人工处理'); - expect(title).toContain('inventory_fetching'); + expect(title).toContain('onhand_fetching'); expect(title).not.toContain('系统处理中'); expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(false); expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false); diff --git a/frontend/src/features/shipping-progress/mergeProcessingProjection.spec.ts b/frontend/src/features/shipping-progress/mergeProcessingProjection.spec.ts index 3216a1ca..39f1c668 100644 --- a/frontend/src/features/shipping-progress/mergeProcessingProjection.spec.ts +++ b/frontend/src/features/shipping-progress/mergeProcessingProjection.spec.ts @@ -19,7 +19,7 @@ function base(overrides: Partial = {}): ShippingPr submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'blocked', - stage: 'inventory_matching', + stage: 'onhand_matching', progressVersion: 3, lastActivityAt: '2026-08-05T00:00:00Z', currentGate: null, @@ -41,12 +41,12 @@ function base(overrides: Partial = {}): ShippingPr describe('mergeWorkbenchProcessingProjection', () => { it('discards stale incoming with lower progressVersion', () => { const local = base({ progressVersion: 5, stage: 'excel_generating' }); - const incoming = base({ progressVersion: 4, stage: 'inventory_matching' }); + const incoming = base({ progressVersion: 4, stage: 'onhand_matching' }); expect(mergeWorkbenchProcessingProjection(local, incoming)).toBe(local); }); it('replaces whole projection when incoming version is newer', () => { - const local = base({ progressVersion: 5, stage: 'inventory_matching' }); + const local = base({ progressVersion: 5, stage: 'onhand_matching' }); const incoming = base({ progressVersion: 6, stage: 'excel_generating', availableActions: ['download_excel'] }); expect(mergeWorkbenchProcessingProjection(local, incoming)).toEqual(incoming); }); diff --git a/frontend/src/features/shipping-progress/progressWindow.spec.ts b/frontend/src/features/shipping-progress/progressWindow.spec.ts index 36df2734..f6621d89 100644 --- a/frontend/src/features/shipping-progress/progressWindow.spec.ts +++ b/frontend/src/features/shipping-progress/progressWindow.spec.ts @@ -27,7 +27,7 @@ function baseProjection( submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'blocked', - stage: 'inventory_source_resolving', + stage: 'onhand_source_resolving', progressVersion: 1, lastActivityAt: '2026-08-05T00:00:00Z', currentGate: null, @@ -47,8 +47,8 @@ function baseProjection( } describe('progressWindow', () => { - it('anchors inventory_source_resolving at index 7', () => { - expect(stageAbsoluteIndex('inventory_source_resolving')).toBe(7); + it('anchors onhand_source_resolving at index 7', () => { + expect(stageAbsoluteIndex('onhand_source_resolving')).toBe(7); }); it('workbench shows all 15 stages', () => { @@ -85,11 +85,11 @@ describe('progressWindow', () => { it('prefers backend stageNodes status over index heuristic', () => { const nodes = buildProgressWindow(baseProjection({ - stage: 'inventory_source_resolving', + stage: 'onhand_source_resolving', status: 'processing', stageNodes: [ { stage: 'upload_received', absoluteIndex: 0, status: 'passed' }, - { stage: 'inventory_source_resolving', absoluteIndex: 7, status: 'failed' }, + { stage: 'onhand_source_resolving', absoluteIndex: 7, status: 'failed' }, ], }), 'workbench'); expect(nodes[7]?.status).toBe('failed'); diff --git a/frontend/src/features/shipping-progress/stageMapping.spec.ts b/frontend/src/features/shipping-progress/stageMapping.spec.ts index 3f9e41fa..4ce015ed 100644 --- a/frontend/src/features/shipping-progress/stageMapping.spec.ts +++ b/frontend/src/features/shipping-progress/stageMapping.spec.ts @@ -25,11 +25,11 @@ describe('stageMapping', () => { candidate_creating: 'intake_parse', customer_resolving: 'order_review', duplicate_checking: 'order_review', - inventory_source_resolving: 'order_review', + onhand_source_resolving: 'order_review', waiting_review: 'order_review', order_creating: 'fulfillment_prep', - inventory_fetching: 'fulfillment_prep', - inventory_matching: 'fulfillment_prep', + onhand_fetching: 'fulfillment_prep', + onhand_matching: 'fulfillment_prep', excel_generating: 'fulfillment_prep', freight_uploading: 'freight_upload', completed: 'upload_complete', @@ -41,8 +41,8 @@ describe('stageMapping', () => { }); it('过渡态归入对应业务标签(库存准备/充足性→通知准备;人工上传交接→货代上传)', () => { - expect(mapProcessingStageToLifecycle('inventory_preparation')).toBe('fulfillment_prep'); - expect(mapProcessingStageToLifecycle('inventory_sufficiency')).toBe('fulfillment_prep'); + expect(mapProcessingStageToLifecycle('onhand_preparation')).toBe('fulfillment_prep'); + expect(mapProcessingStageToLifecycle('onhand_sufficiency')).toBe('fulfillment_prep'); expect(mapProcessingStageToLifecycle('manual_upload_handoff')).toBe('freight_upload'); }); diff --git a/frontend/src/features/shipping-progress/stageMapping.ts b/frontend/src/features/shipping-progress/stageMapping.ts index 5707247c..8bb9dc3e 100644 --- a/frontend/src/features/shipping-progress/stageMapping.ts +++ b/frontend/src/features/shipping-progress/stageMapping.ts @@ -44,14 +44,14 @@ export const SHIPPING_STAGE_TO_LIFECYCLE: Record = { candidate_creating: 'intake_parse', customer_resolving: 'order_review', duplicate_checking: 'order_review', - inventory_source_resolving: 'order_review', + onhand_source_resolving: 'order_review', waiting_review: 'order_review', order_creating: 'fulfillment_prep', - inventory_fetching: 'fulfillment_prep', + onhand_fetching: 'fulfillment_prep', // 过渡态:库存准备/充足性归入通知准备。 - inventory_preparation: 'fulfillment_prep', - inventory_matching: 'fulfillment_prep', - inventory_sufficiency: 'fulfillment_prep', + onhand_preparation: 'fulfillment_prep', + onhand_matching: 'fulfillment_prep', + onhand_sufficiency: 'fulfillment_prep', excel_generating: 'fulfillment_prep', freight_uploading: 'freight_upload', // 过渡态:人工上传交接归入货代上传。 diff --git a/frontend/src/features/shipping-progress/workbenchActionRegistry.spec.ts b/frontend/src/features/shipping-progress/workbenchActionRegistry.spec.ts index ad62b90e..605f8f40 100644 --- a/frontend/src/features/shipping-progress/workbenchActionRegistry.spec.ts +++ b/frontend/src/features/shipping-progress/workbenchActionRegistry.spec.ts @@ -27,7 +27,7 @@ function projection( submissionNo: 'SOS-1', intakeNo: 'SNI-1', status: 'blocked', - stage: 'inventory_matching', + stage: 'onhand_matching', progressVersion: 1, lastActivityAt: '2026-08-05T00:00:00Z', currentGate: null, @@ -53,7 +53,7 @@ describe('workbenchActionRegistry', () => { it('registers Gate fulfillment actions and does not retain legacy aliases', () => { for (const code of [ - 'retry_inventory_matching', + 'retry_onhand_matching', 'mark_manual_uploaded', 'retry_freight_upload_rpa', 'regenerate_excel_artifact', @@ -88,7 +88,7 @@ describe('workbenchActionRegistry', () => { }); it('hides write actions when actionsExecutable=false but keeps view_result', () => { - expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.retry_inventory_matching, { + expect(shouldRenderWorkbenchAction(WORKBENCH_ACTION_REGISTRY.retry_onhand_matching, { actionsExecutable: false, surface: 'review', })).toBe(false); @@ -113,64 +113,64 @@ describe('workbenchActionRegistry', () => { expect(payload?.action_code).toBe('totally_unknown_action'); }); - it('exposes Gate retry_inventory_matching as primary for review Footer', () => { + it('exposes Gate retry_onhand_matching as primary for review Footer', () => { const result = resolveProcessingActionPresentation(projection({ uiState: { - status: 'waiting_human', stage: 'inventory_matching', blocking_reason: null, - primary_action: { code: 'retry_inventory_matching', label_key: 'x' }, secondary_actions: [], + status: 'waiting_human', stage: 'onhand_matching', blocking_reason: null, + primary_action: { code: 'retry_onhand_matching', label_key: 'x' }, secondary_actions: [], }, currentGate: { gateCode: 'inventory_match', status: 'blocked', - nextActionCode: 'retry_inventory_matching', + nextActionCode: 'retry_onhand_matching', blockingReasonCode: 'inventory_shortage', attemptNo: 1, }, availableActions: ['refresh'], }), { surface: 'review', actionsExecutable: true }); - expect(result.primary?.intent).toBe('retry_inventory_matching'); - expect(result.primary?.actionCode).toBe('retry_inventory_matching'); + expect(result.primary?.intent).toBe('retry_onhand_matching'); + expect(result.primary?.actionCode).toBe('retry_onhand_matching'); expect(result.secondary).toBeNull(); }); - it('routes backend retry_inventory_matching through the formal Gate todo action', () => { + it('routes backend retry_onhand_matching through the formal Gate todo action', () => { const result = resolveProcessingActionPresentation(projection({ uiState: { - status: 'retryable', stage: 'inventory_matching', blocking_reason: null, - primary_action: { code: 'retry_inventory_matching', label_key: 'x' }, secondary_actions: [], + status: 'retryable', stage: 'onhand_matching', blocking_reason: null, + primary_action: { code: 'retry_onhand_matching', label_key: 'x' }, secondary_actions: [], }, currentGate: { - gateCode: 'inventory_matching', + gateCode: 'onhand_matching', status: 'blocked_retryable', - nextActionCode: 'retry_inventory_matching', + nextActionCode: 'retry_onhand_matching', blockingReasonCode: 'inventory_match_failed', attemptNo: 1, }, }), { surface: 'review', actionsExecutable: true }); - expect(result.primary?.actionCode).toBe('retry_inventory_matching'); + expect(result.primary?.actionCode).toBe('retry_onhand_matching'); const resolved = resolveWorkbenchActionItem(result.primary!, { postCreate: true }); expect(resolved?.reviewBehavior).toBe('todo_panel'); - expect(resolved?.todoActionCode).toBe('retry_inventory_matching'); + expect(resolved?.todoActionCode).toBe('retry_onhand_matching'); }); it('routes merged inventory rematch through the formal Gate todo action', () => { const result = resolveProcessingActionPresentation(projection({ uiState: { - status: 'retryable', stage: 'inventory_preparation', blocking_reason: null, - primary_action: { code: 'retry_inventory_matching', label_key: 'x' }, secondary_actions: [], + status: 'retryable', stage: 'onhand_preparation', blocking_reason: null, + primary_action: { code: 'retry_onhand_matching', label_key: 'x' }, secondary_actions: [], }, currentGate: { - gateCode: 'inventory_preparation', + gateCode: 'onhand_preparation', status: 'blocked_retryable', - nextActionCode: 'retry_inventory_matching', + nextActionCode: 'retry_onhand_matching', }, }), { surface: 'review' }); const resolved = resolveWorkbenchActionItem(result.primary!, { postCreate: true }); - expect(result.primary?.intent).toBe('retry_inventory_matching'); + expect(result.primary?.intent).toBe('retry_onhand_matching'); expect(resolved?.reviewBehavior).toBe('todo_panel'); - expect(resolved?.todoActionCode).toBe('retry_inventory_matching'); + expect(resolved?.todoActionCode).toBe('retry_onhand_matching'); }); it('shows RPA upload retry instead of manual upload entries when Gate 19 is blocked', () => { diff --git a/frontend/src/features/shipping-progress/workbenchActionRegistry.ts b/frontend/src/features/shipping-progress/workbenchActionRegistry.ts index b82afdb0..986e1d85 100644 --- a/frontend/src/features/shipping-progress/workbenchActionRegistry.ts +++ b/frontend/src/features/shipping-progress/workbenchActionRegistry.ts @@ -135,37 +135,37 @@ export const WORKBENCH_ACTION_REGISTRY: Record { + it('uses the workspace authorization endpoint instead of an object storage URL', () => { + // 关键断言:浏览器只能使用后端鉴权下载代理,不能得到 MinIO bucket/key。 + expect(inboundReportDownloadUrl(42)).toBe('/api/workspace/inbound-report-files/42/download'); + }); + + it('keeps manual compensation routes in the admin namespace', () => { + expect(String(listFailedInboundRpaUnits)).toContain('inbound-rpa-units?status=failed'); + expect(String(retryInboundRpaUnit)).toContain('/api/admin/inbound-rpa-units/'); + expect(String(resendInboundReportFile)).toContain('/api/admin/inbound-report-files/'); + }); +}); diff --git a/frontend/src/features/workspace/api/receipt-report.api.ts b/frontend/src/features/workspace/api/inbound-report.api.ts similarity index 71% rename from frontend/src/features/workspace/api/receipt-report.api.ts rename to frontend/src/features/workspace/api/inbound-report.api.ts index c5acdec0..83a68ee8 100644 --- a/frontend/src/features/workspace/api/receipt-report.api.ts +++ b/frontend/src/features/workspace/api/inbound-report.api.ts @@ -1,5 +1,5 @@ /** - * features/workspace/api/receipt-report.api.ts + * features/workspace/api/inbound-report.api.ts * 用途:工作台收料归档列表与受控下载 API。 * 依赖:requestJson、getAuthHeaders。 * 逻辑:列表由服务端按当前接收人/管理员授权裁剪;下载始终经过工作台鉴权代理。 @@ -8,7 +8,7 @@ import { requestJson } from '@/shared/api/client'; import { getAuthHeaders } from '@/shared/utils/auth'; -export type ReceiptReportFile = { +export type InboundReportFile = { id: number; original_filename: string; content_type?: string | null; @@ -22,7 +22,7 @@ export type ReceiptReportFile = { download_url: string; }; -export type ReceiptRpaUnit = { +export type InboundRpaUnit = { id: number; source_code: string; warehouse_id?: string | null; @@ -40,8 +40,8 @@ export type ReceiptRpaUnit = { * 核心逻辑:不接收 user_id 或对象存储参数,服务端以当前会话和排程接收人关系授权。 * @returns 脱敏归档元数据和受控下载地址。 */ -export const listWorkspaceReceiptReportFiles = (limit = 100) => requestJson<{ items: ReceiptReportFile[] }>( - `/api/workspace/receipt-report-files?limit=${encodeURIComponent(String(limit))}`, +export const listWorkspaceInboundReportFiles = (limit = 100) => requestJson<{ items: InboundReportFile[] }>( + `/api/workspace/inbound-report-files?limit=${encodeURIComponent(String(limit))}`, { headers: getAuthHeaders() }, ); @@ -51,21 +51,21 @@ export const listWorkspaceReceiptReportFiles = (limit = 100) => requestJson<{ it * @param fileId - 收料归档文件主键。 * @returns 由后端再次校验接收人权限的下载路径。 */ -export const receiptReportDownloadUrl = (fileId: number) => `/api/workspace/receipt-report-files/${encodeURIComponent(String(fileId))}/download`; +export const inboundReportDownloadUrl = (fileId: number) => `/api/workspace/inbound-report-files/${encodeURIComponent(String(fileId))}/download`; /** 管理员读取失败收料单元;普通用户不调用此管理端接口。 */ -export const listFailedReceiptRpaUnits = () => requestJson<{ items: ReceiptRpaUnit[] }>( - '/api/admin/receipt-rpa-units?status=failed&limit=100', { headers: getAuthHeaders() }, +export const listFailedInboundRpaUnits = () => requestJson<{ items: InboundRpaUnit[] }>( + '/api/admin/inbound-rpa-units?status=failed&limit=100', { headers: getAuthHeaders() }, ); /** 管理员以必填原因新建失败单元的独立人工重试事实。 */ -export const retryReceiptRpaUnit = (unitId: number, reason: string) => requestJson( - `/api/admin/receipt-rpa-units/${encodeURIComponent(String(unitId))}/retry`, +export const retryInboundRpaUnit = (unitId: number, reason: string) => requestJson( + `/api/admin/inbound-rpa-units/${encodeURIComponent(String(unitId))}/retry`, { method: 'POST', headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' }, body: JSON.stringify({ reason }) }, ); /** 管理员仅重发已归档文件的企微消息,不会重新导出。 */ -export const resendReceiptReportFile = (fileId: number) => requestJson( - `/api/admin/receipt-report-files/${encodeURIComponent(String(fileId))}/resend`, +export const resendInboundReportFile = (fileId: number) => requestJson( + `/api/admin/inbound-report-files/${encodeURIComponent(String(fileId))}/resend`, { method: 'POST', headers: getAuthHeaders() }, ); diff --git a/frontend/src/features/workspace/api/receipt-report.api.spec.ts b/frontend/src/features/workspace/api/receipt-report.api.spec.ts deleted file mode 100644 index 0e709483..00000000 --- a/frontend/src/features/workspace/api/receipt-report.api.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * features/workspace/api/receipt-report.api.spec.ts - * 用途:锁定收料报表列表与下载地址的工作台契约。 - * 依赖:receipt-report.api、vitest。 - * 逻辑:普通接收人只能经工作台受控下载,不拼接对象存储地址。 - */ - -import { describe, expect, it } from 'vitest'; -import { - listFailedReceiptRpaUnits, receiptReportDownloadUrl, resendReceiptReportFile, retryReceiptRpaUnit, -} from './receipt-report.api'; - -describe('receiptReportDownloadUrl', () => { - it('uses the workspace authorization endpoint instead of an object storage URL', () => { - // 关键断言:浏览器只能使用后端鉴权下载代理,不能得到 MinIO bucket/key。 - expect(receiptReportDownloadUrl(42)).toBe('/api/workspace/receipt-report-files/42/download'); - }); - - it('keeps manual compensation routes in the admin namespace', () => { - expect(String(listFailedReceiptRpaUnits)).toContain('receipt-rpa-units?status=failed'); - expect(String(retryReceiptRpaUnit)).toContain('/api/admin/receipt-rpa-units/'); - expect(String(resendReceiptReportFile)).toContain('/api/admin/receipt-report-files/'); - }); -}); diff --git a/frontend/src/features/workspace/components/WorkspaceSidebar.spec.ts b/frontend/src/features/workspace/components/WorkspaceSidebar.spec.ts index 1df4d0fa..110de342 100644 --- a/frontend/src/features/workspace/components/WorkspaceSidebar.spec.ts +++ b/frontend/src/features/workspace/components/WorkspaceSidebar.spec.ts @@ -41,7 +41,7 @@ const i18n = createI18n({ admin: '管理控制台', applications: '应用管理', scheduleRuns: '排程记录', - receiptReports: '收料文件', + inboundReports: '收料文件', shippingNotice: '货代发货', shippingCustomers: '客户主数据', shippingMyTasks: '我的待办', @@ -68,7 +68,7 @@ async function mountSidebar(user: { role: string; is_platform_admin?: boolean }) { path: WORKSPACE_PATHS.applications, name: 'workspace-applications', component: { template: '
' } }, { path: WORKSPACE_PATHS.profile, name: 'workspace-profile', component: { template: '
' } }, { path: WORKSPACE_PATHS.scheduleRuns, name: 'workspace-schedule-runs', component: { template: '
' } }, - { path: WORKSPACE_PATHS.receiptReports, name: 'workspace-receipt-reports', component: { template: '
' } }, + { path: WORKSPACE_PATHS.inboundReports, name: 'workspace-inbound-reports', component: { template: '
' } }, { path: WORKSPACE_PATHS.feedback, name: 'workspace-feedback', component: { template: '
' } }, { path: WORKSPACE_PATHS.updates, name: 'workspace-updates', component: { template: '
' } }, { path: WORKSPACE_PATHS.shippingNoticeCustomers, name: 'workspace-shipping-customers', component: { template: '
' } }, diff --git a/frontend/src/features/workspace/components/WorkspaceSidebar.vue b/frontend/src/features/workspace/components/WorkspaceSidebar.vue index 823e384d..b037a784 100644 --- a/frontend/src/features/workspace/components/WorkspaceSidebar.vue +++ b/frontend/src/features/workspace/components/WorkspaceSidebar.vue @@ -33,7 +33,7 @@ const primaryLinkItems = [ { path: WORKSPACE_PATHS.profile, labelKey: 'workspace.nav.profile', icon: User, match: ['workspace-profile'] }, { path: WORKSPACE_PATHS.applications, labelKey: 'workspace.nav.applications', icon: LayoutGrid, match: ['workspace-applications'] }, { path: WORKSPACE_PATHS.scheduleRuns, labelKey: 'workspace.nav.scheduleRuns', icon: Clock, match: ['workspace-schedule-runs'] }, - { path: WORKSPACE_PATHS.receiptReports, labelKey: 'workspace.nav.receiptReports', icon: FileDown, match: ['workspace-receipt-reports'] }, + { path: WORKSPACE_PATHS.inboundReports, labelKey: 'workspace.nav.inboundReports', icon: FileDown, match: ['workspace-inbound-reports'] }, ] as const; const secondaryLinkItems = [ diff --git a/frontend/src/features/workspace/composables/useWorkspaceNavigation.ts b/frontend/src/features/workspace/composables/useWorkspaceNavigation.ts index 6cf1ebc8..ca216364 100644 --- a/frontend/src/features/workspace/composables/useWorkspaceNavigation.ts +++ b/frontend/src/features/workspace/composables/useWorkspaceNavigation.ts @@ -21,7 +21,7 @@ const ROUTE_NAME_TO_SIDEBAR: Record = { 'workspace-knowledge-base': 'knowledge_base', 'workspace-knowledge-base-group': 'knowledge_base', 'workspace-schedule-runs': 'schedule_runs', - 'workspace-receipt-reports': 'receipt_reports', + 'workspace-inbound-reports': 'receipt_reports', 'workspace-shipping-customers': 'shipping_notice', 'workspace-shipping-tasks': 'shipping_notice', 'workspace-shipping-my-tasks': 'shipping_notice', diff --git a/frontend/src/features/workspace/constants/routes.ts b/frontend/src/features/workspace/constants/routes.ts index f7903444..8e513b61 100644 --- a/frontend/src/features/workspace/constants/routes.ts +++ b/frontend/src/features/workspace/constants/routes.ts @@ -11,7 +11,7 @@ export const WORKSPACE_PATHS = { updates: '/workspace/updates', knowledgeBase: '/workspace/knowledge-base', scheduleRuns: '/workspace/schedule-runs', - receiptReports: '/workspace/receipt-reports', + inboundReports: '/workspace/inbound-reports', shippingNotice: '/workspace/shipping-notice/my-tasks', shippingNoticeCustomers: '/workspace/shipping-notice/customers', shippingNoticeTasks: '/workspace/shipping-notice/tasks', @@ -35,7 +35,7 @@ export const LEGACY_VIEW_TO_PATH: Record = { updates: WORKSPACE_PATHS.updates, knowledge_base: WORKSPACE_PATHS.knowledgeBase, schedule_runs: WORKSPACE_PATHS.scheduleRuns, - receipt_reports: WORKSPACE_PATHS.receiptReports, + receipt_reports: WORKSPACE_PATHS.inboundReports, shipping_notice: WORKSPACE_PATHS.shippingNotice, accounting_voucher_check: WORKSPACE_PATHS.accountingVoucherCheck, contract_payment: WORKSPACE_PATHS.contractPayment, diff --git a/frontend/src/features/workspace/pages/ReceiptReportFilesPage.spec.ts b/frontend/src/features/workspace/pages/InboundReportFilesPage.spec.ts similarity index 65% rename from frontend/src/features/workspace/pages/ReceiptReportFilesPage.spec.ts rename to frontend/src/features/workspace/pages/InboundReportFilesPage.spec.ts index 598a995f..5e5d049d 100644 --- a/frontend/src/features/workspace/pages/ReceiptReportFilesPage.spec.ts +++ b/frontend/src/features/workspace/pages/InboundReportFilesPage.spec.ts @@ -1,26 +1,26 @@ /** - * features/workspace/pages/ReceiptReportFilesPage.spec.ts + * features/workspace/pages/InboundReportFilesPage.spec.ts * 用途:验证收料归档页的接收人与管理员补偿权限边界。 - * 依赖:Vue Test Utils、Vue I18n、receipt-report.api、Workspace 上下文。 + * 依赖:Vue Test Utils、Vue I18n、inbound-report.api、Workspace 上下文。 * 逻辑:普通接收人只能下载获授权文件;管理员才会查询失败单元并看到重发/重试操作。 */ import { flushPromises, mount } from '@vue/test-utils'; import { createI18n } from 'vue-i18n'; import { describe, expect, it, vi } from 'vitest'; -import ReceiptReportFilesPage from './ReceiptReportFilesPage.vue'; +import InboundReportFilesPage from './InboundReportFilesPage.vue'; import { WORKSPACE_KEY } from '../composables/workspace.context'; -const listWorkspaceReceiptReportFiles = vi.fn(); -const listFailedReceiptRpaUnits = vi.fn(); -const resendReceiptReportFile = vi.fn(); +const listWorkspaceInboundReportFiles = vi.fn(); +const listFailedInboundRpaUnits = vi.fn(); +const resendInboundReportFile = vi.fn(); -vi.mock('../api/receipt-report.api', () => ({ - listWorkspaceReceiptReportFiles: (...args: unknown[]) => listWorkspaceReceiptReportFiles(...args), - listFailedReceiptRpaUnits: (...args: unknown[]) => listFailedReceiptRpaUnits(...args), - receiptReportDownloadUrl: (id: number) => `/download/${id}`, - resendReceiptReportFile: (...args: unknown[]) => resendReceiptReportFile(...args), - retryReceiptRpaUnit: vi.fn(), +vi.mock('../api/inbound-report.api', () => ({ + listWorkspaceInboundReportFiles: (...args: unknown[]) => listWorkspaceInboundReportFiles(...args), + listFailedInboundRpaUnits: (...args: unknown[]) => listFailedInboundRpaUnits(...args), + inboundReportDownloadUrl: (id: number) => `/download/${id}`, + resendInboundReportFile: (...args: unknown[]) => resendInboundReportFile(...args), + retryInboundRpaUnit: vi.fn(), })); const i18n = createI18n({ @@ -29,7 +29,7 @@ const i18n = createI18n({ messages: { en: { workspace: { - receiptReports: { + inboundReports: { title: 'Receipt Files', hint: 'hint', refresh: 'Refresh', loading: 'Loading', empty: 'Empty', file: 'File', site: 'Site', warehouse: 'Warehouse', createdAt: 'Created', expiresAt: 'Expires', action: 'Action', download: 'Download', resend: 'Resend to WeCom', failedUnits: 'Failed receipt units', @@ -41,7 +41,7 @@ const i18n = createI18n({ }); function mountPage(role: string) { - return mount(ReceiptReportFilesPage, { + return mount(InboundReportFilesPage, { global: { plugins: [i18n], provide: { [WORKSPACE_KEY as symbol]: { currentUser: { role } } }, @@ -49,12 +49,12 @@ function mountPage(role: string) { }); } -describe('ReceiptReportFilesPage permissions', () => { +describe('InboundReportFilesPage permissions', () => { it('does not expose administrator compensation actions to a recipient', async () => { - listWorkspaceReceiptReportFiles.mockResolvedValue({ items: [{ + listWorkspaceInboundReportFiles.mockResolvedValue({ items: [{ id: 1, original_filename: 'receipt.xlsx', file_size: 12, sha256: 'a'.repeat(64), }] }); - listFailedReceiptRpaUnits.mockResolvedValue({ items: [{ id: 9, source_code: 'DBS-A', status: 'failed' }] }); + listFailedInboundRpaUnits.mockResolvedValue({ items: [{ id: 9, source_code: 'DBS-A', status: 'failed' }] }); const wrapper = mountPage('user'); await flushPromises(); @@ -63,12 +63,12 @@ describe('ReceiptReportFilesPage permissions', () => { expect(wrapper.text()).toContain('Download'); expect(wrapper.text()).not.toContain('Resend to WeCom'); expect(wrapper.text()).not.toContain('Failed receipt units'); - expect(listFailedReceiptRpaUnits).not.toHaveBeenCalled(); + expect(listFailedInboundRpaUnits).not.toHaveBeenCalled(); }); it('shows failed-unit compensation only to an administrator', async () => { - listWorkspaceReceiptReportFiles.mockResolvedValue({ items: [] }); - listFailedReceiptRpaUnits.mockResolvedValue({ items: [{ + listWorkspaceInboundReportFiles.mockResolvedValue({ items: [] }); + listFailedInboundRpaUnits.mockResolvedValue({ items: [{ id: 9, source_code: 'DBS-A', warehouse_id: 'WH-01', status: 'failed', error_code: 'RPA.TIMEOUT', }] }); @@ -79,15 +79,15 @@ describe('ReceiptReportFilesPage permissions', () => { expect(wrapper.text()).toContain('Failed receipt units'); expect(wrapper.text()).toContain('DBS-A / WH-01'); expect(wrapper.text()).toContain('Retry with reason'); - expect(listFailedReceiptRpaUnits).toHaveBeenCalledOnce(); + expect(listFailedInboundRpaUnits).toHaveBeenCalledOnce(); }); it('uses the notification resend action without creating another export', async () => { - listWorkspaceReceiptReportFiles.mockResolvedValue({ items: [{ + listWorkspaceInboundReportFiles.mockResolvedValue({ items: [{ id: 7, original_filename: 'receipt.xlsx', file_size: 12, sha256: 'b'.repeat(64), }] }); - listFailedReceiptRpaUnits.mockResolvedValue({ items: [] }); - resendReceiptReportFile.mockResolvedValue({}); + listFailedInboundRpaUnits.mockResolvedValue({ items: [] }); + resendInboundReportFile.mockResolvedValue({}); const wrapper = mountPage('admin'); await flushPromises(); @@ -95,7 +95,7 @@ describe('ReceiptReportFilesPage permissions', () => { await flushPromises(); // 重发只调用归档文件的通知接口,不存在浏览器侧重新导出入口。 - expect(resendReceiptReportFile).toHaveBeenCalledWith(7); + expect(resendInboundReportFile).toHaveBeenCalledWith(7); expect(wrapper.text()).not.toContain('Export'); }); }); diff --git a/frontend/src/features/workspace/pages/ReceiptReportFilesPage.vue b/frontend/src/features/workspace/pages/InboundReportFilesPage.vue similarity index 70% rename from frontend/src/features/workspace/pages/ReceiptReportFilesPage.vue rename to frontend/src/features/workspace/pages/InboundReportFilesPage.vue index b8c88118..a5815c05 100644 --- a/frontend/src/features/workspace/pages/ReceiptReportFilesPage.vue +++ b/frontend/src/features/workspace/pages/InboundReportFilesPage.vue @@ -1,22 +1,22 @@